1 / 40

Xiang Lian The University of Texas – Pan American Edinburg, TX 78539 lianx@utpa

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

wsprouse
Télécharger la présentation

Xiang Lian The University of Texas – Pan American Edinburg, TX 78539 lianx@utpa

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CSCI/CMPE 4341 Topic: Programming in PythonReview: 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

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

  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

  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

  6. Example of Sequences Name sequence (C) Position number of the element within sequence C

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

  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!

  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

  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

  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

  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 • deldictionaryName [key]

  13. Dictionary Methods

  14. Dictionary Methods (cont'd)

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

  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

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

  18. 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

  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

  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

  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

  22. 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

  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

  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  

  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

  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 try: fromTkinterimport * # for Python2 exceptImportError: fromtkinterimport * # for Python3

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

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

  29. 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

  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

  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)

  32. Mouse Event Handling (cont'd)

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

  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?

  35. 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

  36. 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>

  37. 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 = [ ( "&", "&amp;" ), ( "<", "&lt;" ), ( ">", "&gt;" ), ( '"', "&quot;" ), ( "'", "&apos;" ) ] # replace special characters with entity references for currentLine in file.readlines(): for oldValue, newValue in replaceList: currentLine = currentLine.replace( oldValue, newValue ) fig16_02.py

  38. 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

  39. # 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

  40. Good Luck! Q/A

More Related