Presentation is loading. Please wait.

Presentation is loading. Please wait.

CSCI/CMPE 4341 Topic: Programming in Python Review: Exam II Xiang Lian The University of Texas – Pan American Edinburg, TX 78539

Similar presentations


Presentation on theme: "CSCI/CMPE 4341 Topic: Programming in Python Review: Exam II Xiang Lian The University of Texas – Pan American Edinburg, TX 78539"— Presentation transcript:

1 CSCI/CMPE 4341 Topic: Programming in Python Review: Exam II Xiang Lian The University of Texas – Pan American Edinburg, TX 78539 lianx@utpa.edu

2 Review Textbook –Self-Review Exercises –Quick Quiz –Exercises Lecture slides (Chapters 6-9) –Lists, Tuples, and Dictionaries –Object-Oriented Programming –Graphical User Interface Components –Python XML Processing –Exercises 2

3 Review Multiple Choice True/False Statements Programming –Find bugs –Write the code Bonus Question (20 extra points) 3

4 Chapter 6: Lists, Tuples, and Dictionaries Creation and manipulation of sequences –String –List –Tuple Creation and manipulation of Dictionary Methods of sequences and Dictionary 4

5 Introduction Data structures –Structures that hold and organize information Sequences –Also known as arrays in other languages (e.g., C++) –Store related data types –3 types Strings Lists Tuples Mappings –In most languages called hashes or associative arrays –Dictionaries are the only python mapping container Key-value pairs 5

6 Example of Sequences C[0]-45C[-12] C[1]6C[-11] C[2]0C[-10] C[3]72C[-9] C[4]34C[-8] C[5]39C[-7] C[6]98C[-6] C[7]-1345C[-5] C[8]939C[-4] C[9]10C[-3] C[10]40C[-2] C[11]33C[-1] Name sequence (C) Position number of the element within sequence C 6

7 Creating Sequences – String Strings –Use quotes string1 = "hello" –Empty string string2 = "" Error! –string1[0]="A" 7

8 Creating Sequences – List Lists –Use brackets –Separate multiple items with a comma list1 = [1, 2, 3, 4] –Empty list list2 = [] Length of the list –len (list1) list1[0]=0 # OK! 8

9 Creating Sequences – Tuple Tuples –Use parenthesis –Separate multiple items with a comma tuple1 = (1, 2, 3, 4) tuple1 = 1, 2, 3, 4 –Empty tuple tuple2 = () –Singleton (or one-element tuple) singleton3 = 1, Comma (,) after 1 identify the variable signleton3 as a tuple Error! –tuple1[0]=0 9

10 Differences Between Lists and Tuples Differences –Tuples and lists can both contain the same data aList = [ 1, 2, 3, 4 ] aTuple = ( 1, 2, 3, 4 ) –For practical purposes though each is used to hold different types of items 10

11 Dictionaries Key-value pairs – Unordered collection of references – Each value is referenced through key in the pair – Curley braces ({}) are used to create a dictionary – When entering values Use { key1:value1, … } Keys must be immutable values – strings, numbers and tuples Values can be of any Python data type 11

12 Operations in Dictionaries Access dictionary element –dictionaryName [key] –dictionaryName [key] = value # update the value of an existing key Add key-value pair –dictionaryName [newKey] = newValue Delete key-value pair –del dictionaryName [key] 12

13 Dictionary Methods 13

14 Dictionary Methods (cont'd) 14

15 Sorting and Searching Lists Sorting a list –Use the sort method Searching a list –Use the index method 15

16 Chapter 7: Introduction to Object- Oriented Programming in Python Classes –Attributes Private attributes Class attributes –Methods Constructor: __init__ Get and Set methods Destructor: __del__ Objects –Creation of objects Inheritance –syntax 16

17 Object Orientation Classes –Encapsulate data Attributes –Encapsulate functions Behaviors –Act as blueprints Objects are instantiated from classes –Implement information hiding 17

18 Class Declaration Defining a Class –Class header Keyword class begins definition –Followed by name of class and colon (:) –Body of class Indented block of code –Documentation string Describes the class Optional Appears immediately after class header 18

19 Class Declaration (cont'd) Defining a Class –Constructor method __init__ Executes each time an object is created Initialize attributes of class Returns None –Object reference All methods must at least specify this one parameter Represents object of class from which a method is called Called self by convention 19

20 Get and Set Methods Access methods –Allow data of class to be read and written in controlled manner –Get and Set methods Allow clients to read and write the values of attributes respectively 20

21 Private Attributes Data and attributes not to be accessed by clients of a class Private attributes preceded with double underscore (__) –Causes Python to perform name mangling Changes name of attribute to include information about the class For example, attribute __hour in class Time becomes _Time__hour 21

22 Destructors –Method is named __del__ –Executed when object is destroyed No more references to object exist –Performs termination housekeeping before Python reclaims object memory Typically used to close network or database connections 22

23 Class Attributes One copy of attribute shared by all objects of a class Represents “class-wide” information –Property of the class, not an object of the class Initialized once in a class definition –Definition of class attribute appears in body of class definition, not a method definition Accessed through the class or any object of the class –May exist even if no objects of class exist 23

24 Inheritance: Base Classes and Derived Classes Base class –Called superclass in other programming languages –Other classes inherit its methods and attributes Derived class –Called subclass in other programming languages –Inherits from a base class –Generally overrides some base class methods and adds features 24

25 Chapter 8: Graphical User Interface Components GUI packages –tkinter Each GUI component class inherits from Widget Components –Label –Entry –Button –Checkbutton & Radiobutton Events –Mouse events –Keyboard events 25

26 tkinter Module Python’s standard GUI package – tkinter module tkinter library provides object-oriented interface to Tk GUI toolkit Each GUI component class inherits from class Widget GUI consists of top-level (or parent) component that can contain children components Class Frame serves as a top-level component 26 try: from Tkinter import * # for Python2 except ImportError: from tkinter import * # for Python3

27 27 tkinter Overview Frame Label Entry Text Button Checkbutton Radiobutton Menu Canvas Scale Listbox Scrollbar Menubutton Widget Key Subclass name Class name Widget subclasses:

28 Label Component – Label Labels –Display text or images –Provide instructions and other information –Created by tkinter class Label 28

29 Entry Component – TextBox Textbox –Areas in which users can enter text or programmers can display a line of text –Created by Entry class event occurs when user presses Enter key inside Entry component 29

30 Button Component – Button Buttons –Generates events when selected –Facilitate selection of actions –Created with class Button –Displays text or image called button label –Each should have unique label 30

31 Checkbutton and Radiobutton Components Checkbox –Small white square –Either blank or contains a checkmark –Descriptive text referred to as checkbox label –Any number of boxes selected at a time –Created by class Checkbutton Radio button –Mutually excusive options – only one radio button selected at a time –Created by class Radiobutton Both have on/off or True/False values and two states – selected and not selected (deselected) 31

32 Mouse Event Handling (cont'd) 32

33 Keyboard Event Handling Keyboard events generated when users press and release keys 33

34 Chapter 9: Python XML Processing XML documents –Tree structure –Tags –Elements –Data –Namespaces How to use Python to output XML documents? How to parse XML documents using Python packages? 34

35 XML Documents XML documents end with.xml extension XML marks up data using tags, which are names enclosed in angle brackets – elements –Elements: individual units of markup (i.e., everything included between a start tag and its corresponding end tag) –Nested elements form hierarchies –Root element contains all other document elements 35

36 36 XML Namespaces Provided for unique identification of XML elements Namespace prefixes identify namespace to which an element belongs Topic: Programming in Python

37  2002 Prentice Hall. All rights reserved. Outline 37 fig16_02.py #!c:\Python\python.exe # Fig. 16.2: fig16_02.py # Marking up a text file's data as XML. import sys # write XML declaration and processing instruction print (""" """) # open data file try: file = open( "names.txt", "r" ) except IOError: sys.exit( "Error opening file" ) print (" ") # write root element # list of tuples: ( special character, entity reference ) replaceList = [ ( "&", "&" ), ( "<", "<" ), ( ">", ">" ), ( '"', """ ), ( "'", "&apos;" ) ] # replace special characters with entity references for currentLine in file.readlines(): for oldValue, newValue in replaceList: currentLine = currentLine.replace( oldValue, newValue ) Print XML declarationOpen text file if it existsPrint root elementList of special characters and their entity referencesReplace special characters with entity references

38  2002 Prentice Hall. All rights reserved. Outline 38 fig16_02.py # extract lastname and firstname last, first = currentLine.split( ", " ) first = first.strip() # remove carriage return # write contact element print (""" %s """ % ( last, first )) file.close() print (" ") Extract first and last nameRemove carriage returnPrint contact elementPrint root’s closing tag

39  2002 Prentice Hall. All rights reserved. Outline 39 fig16_04.py # Fig. 16.4: fig16_04.py # Using 4DOM to traverse an XML Document. import sys import xml.etree.ElementTree as etree # open XML file try: tree = etree.parse("article2.xml") except IOError: sys.exit( "Error opening file" ) # get root element rootElement = tree.getroot() print ("Here is the root element of the document: %s" % \ rootElement.tag) # traverse all child nodes of root element print ("The following are its child elements:" ) for node in rootElement: print (node)

40 Good Luck! Q/A


Download ppt "CSCI/CMPE 4341 Topic: Programming in Python Review: Exam II Xiang Lian The University of Texas – Pan American Edinburg, TX 78539"

Similar presentations


Ads by Google