400 likes | 405 Vues
CSCI/CMPE 4341 Topic: Programming in Python Review: Exam II. Xiang Lian The University of Texas – Pan American Edinburg, TX 78539 lianx@utpa.edu. Review. Textbook Self-Review Exercises Quick Quiz Exercises Lecture slides (Chapters 6-9) Lists, Tuples, and Dictionaries
E N D
CSCI/CMPE 4341 Topic: Programming in PythonReview: Exam II Xiang Lian The University of Texas – Pan American Edinburg, TX 78539 lianx@utpa.edu
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
Review • Multiple Choice • True/False Statements • Programming • Find bugs • Write the code • Bonus Question (20 extra points)
Chapter 6: Lists, Tuples, and Dictionaries • Creation and manipulation of sequences • String • List • Tuple • Creation and manipulation of Dictionary • Methods of sequences and Dictionary
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
Example of Sequences Name sequence (C) Position number of the element within sequence C
Creating Sequences – String • Strings • Use quotes • string1 = "hello" • Empty string • string2 = "" • Error! • string1[0]="A"
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!
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
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
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
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 • deldictionaryName [key]
Sorting and Searching Lists • Sorting a list • Use the sort method • Searching a list • Use the index method
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
Object Orientation • Classes • Encapsulate data • Attributes • Encapsulate functions • Behaviors • Act as blueprints • Objects are instantiated from classes • Implement information hiding
Class Declaration • Defining a Class • Class header • Keyword classbegins definition • Followed by name of classand colon (:) • Body of class • Indented block of code • Documentation string • Describes the class • Optional • Appears immediately after class header
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
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
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
Destructors • 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
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
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
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
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 try: fromTkinterimport * # for Python2 exceptImportError: fromtkinterimport * # for Python3
Frame Label Widget Entry Text Button Checkbutton Radiobutton Menu Canvas Scale Listbox Key Scrollbar Subclass name Class name Menubutton tkinter Overview Widget subclasses:
Label Component – Label • Labels • Display text or images • Provide instructions and other information • Created by tkinter class Label
Entry Component – TextBox • Textbox • Areas in which users can enter text or programmers can display a line of text • Created by Entry class • <Return> event occurs when user presses Enter key inside Entry component
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
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)
Keyboard Event Handling • Keyboard events generated when users press and release keys
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?
XML Documents • XML documents end with .xml extension • XML marks up data using tags, which are names enclosed in angle brackets • <tag> elements </tag> • 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
XML Namespaces • Provided for unique identification of XML elements • Namespace prefixes identify namespace to which an element belongs <Xiang:CSCI/CMPE4341> Topic: Programming in Python </Xiang:CSCI/CMPE4341>
Print XML declaration Open text file if it exists Print root element List of special characters and their entity references Replace special characters with entity references #!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 ("""<?xml version = "1.0"?>""") # open data file try: file = open( "names.txt", "r" ) except IOError: sys.exit( "Error opening file" ) print ("<contacts>") # write root element # list of tuples: ( special character, entity reference ) replaceList = [ ( "&", "&" ), ( "<", "<" ), ( ">", ">" ), ( '"', """ ), ( "'", "'" ) ] # replace special characters with entity references for currentLine in file.readlines(): for oldValue, newValue in replaceList: currentLine = currentLine.replace( oldValue, newValue ) fig16_02.py
Extract first and last name Remove carriage return Print contact element Print root’s closing tag # extract lastname and firstname last, first = currentLine.split( ", " ) first = first.strip() # remove carriage return # write contact element print (""" <contact> <LastName>%s</LastName> <FirstName>%s</FirstName> </contact>""" % ( last, first )) file.close() print ("</contacts>") fig16_02.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) fig16_04.py
Good Luck! Q/A