CSCI/CMPE 4341 Topic: Programming in Python Review: Exam II Xiang Lian The University of Texas –...

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

Transcript of CSCI/CMPE 4341 Topic: Programming in Python Review: Exam II Xiang Lian The University of Texas –...

  • CSCI/CMPE 4341 Topic: Programming in Python Review: Exam IIXiang LianThe University of Texas Pan AmericanEdinburg, TX [email protected]

  • ReviewTextbookSelf-Review ExercisesQuick Quiz ExercisesLecture slides (Chapters 6-9)Lists, Tuples, and DictionariesObject-Oriented ProgrammingGraphical User Interface ComponentsPython XML ProcessingExercises*

  • ReviewMultiple ChoiceTrue/False StatementsProgrammingFind bugsWrite the codeBonus Question (20 extra points)*

  • Chapter 6: Lists, Tuples, and DictionariesCreation and manipulation of sequencesStringList TupleCreation and manipulation of DictionaryMethods of sequences and Dictionary *

  • IntroductionData structuresStructures that hold and organize informationSequencesAlso known as arrays in other languages (e.g., C++)Store related data types3 typesStringsListsTuplesMappingsIn most languages called hashes or associative arraysDictionaries are the only python mapping containerKey-value pairs*

  • Example of SequencesName sequence (C)Position number of the element within sequence C*

    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]

  • Creating Sequences String StringsUse quotesstring1 = "hello"Empty stringstring2 = ""Error!string1[0]="A"

    *

  • Creating Sequences ListListsUse bracketsSeparate multiple items with a commalist1 = [1, 2, 3, 4]Empty listlist2 = []Length of the listlen (list1) list1[0]=0 # OK! *

  • Creating Sequences TupleTuplesUse parenthesisSeparate multiple items with a commatuple1 = (1, 2, 3, 4)tuple1 = 1, 2, 3, 4Empty tupletuple2 = ()Singleton (or one-element tuple)singleton3 = 1,Comma (,) after 1 identify the variable signleton3 as a tupleError!tuple1[0]=0

    *

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

    *

  • DictionariesKey-value pairsUnordered collection of referencesEach value is referenced through key in the pairCurley braces ({}) are used to create a dictionaryWhen entering valuesUse { key1:value1, }Keys must be immutable valuesstrings, numbers and tuplesValues can be of any Python data type*

  • Operations in DictionariesAccess dictionary elementdictionaryName [key]dictionaryName [key] = value # update the value of an existing keyAdd key-value pairdictionaryName [newKey] = newValueDelete key-value pairdel dictionaryName [key]*

  • Dictionary Methods*

    Method

    Description

    clear()

    Deletes all items from the dictionary.

    copy()

    Creates and returns a shallow copy of the dictionary (the elements in the new dictionary are references to the elements in the original dictionary).

    get( key [, returnValue] )

    Returns the value associated with key. If key is not in the dictionary and if returnValue is specified, returns the specified value. If returnValue is not specified, returns None.

    has_key( key )

    Returns 1 if key is in the dictionary; returns 0 if key is not in the dictionary.

    items()

    Returns a list of tuples that are key-value pairs.

    keys()

    Returns a list of keys in the dictionary.

    popitem()

    Removes and returns an arbitrary key-value pair as a tuple of two elements. If dictionary is empty, a KeyError exception occurs. [Note: We discuss exceptions in Chapter 12, Exception Handling.] This method is useful for accessing an element (i.e., print the key-value pair) before removing it from the dictionary.

  • Dictionary Methods (cont'd)*

    setdefault( key [, dummyValue] )

    Behaves similarly to method get. If key is not in the dictionary and dummyValue is specified, inserts the key and the specified value into dictionary. If dummyValue is not specified, value is None.

    update( newDictionary )

    Adds all key-value pairs from newDictionary to the current dictionary and overrides the values for keys that already exist.

    values()

    Returns a list of values in the dictionary.

    iterkeys()

    Returns an iterator of dictionary keys. [Note: We discuss iterators in Appendix O, Additional Python 2.2 Features.]

    iteritems()

    Returns an iterator of key-value pairs. [Note: We discuss iterators in Appendix O, Additional Python 2.2 Features.]

    itervalues()

    Returns an iterator of dictionary values. [Note: We discuss iterators in Appendix O, Additional Python 2.2 Features.]

    Fig. 5.14Dictionary methods.

  • Sorting and Searching ListsSorting a listUse the sort methodSearching a listUse the index method

    *

  • Chapter 7: Introduction to Object-Oriented Programming in PythonClassesAttributesPrivate attributesClass attributesMethodsConstructor: __init__Get and Set methodsDestructor: __del__ObjectsCreation of objectsInheritancesyntax*

  • Object OrientationClassesEncapsulate dataAttributesEncapsulate functionsBehaviorsAct as blueprintsObjects are instantiated from classesImplement information hiding*

  • Class DeclarationDefining a ClassClass headerKeyword class begins definitionFollowed by name of class and colon (:)Body of classIndented block of codeDocumentation stringDescribes the classOptionalAppears immediately after class header

    *

  • Class Declaration (cont'd)Defining a ClassConstructor method __init__Executes each time an object is createdInitialize attributes of classReturns NoneObject referenceAll methods must at least specify this one parameterRepresents object of class from which a method is calledCalled self by convention

    *

  • Get and Set Methods Access methodsAllow data of class to be read and written in controlled mannerGet and Set methodsAllow clients to read and write the values of attributes respectively

    *

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

    *

  • DestructorsDestructorsMethod is named __del__Executed when object is destroyedNo more references to object existPerforms termination housekeeping before Python reclaims object memoryTypically used to close network or database connections

    *

  • Class Attributes One copy of attribute shared by all objects of a classRepresents class-wide informationProperty of the class, not an object of the classInitialized once in a class definitionDefinition of class attribute appears in body of class definition, not a method definitionAccessed through the class or any object of the classMay exist even if no objects of class exist

    *

  • Inheritance: Base Classes and Derived ClassesBase classCalled superclass in other programming languagesOther classes inherit its methods and attributesDerived classCalled subclass in other programming languagesInherits from a base classGenerally overrides some base class methods and adds features *

  • Chapter 8: Graphical User Interface ComponentsGUI packagestkinterEach GUI component class inherits from WidgetComponentsLabelEntryButtonCheckbutton & RadiobuttonEventsMouse eventsKeyboard events

    *

  • tkinter ModulePythons standard GUI package tkinter moduletkinter library provides object-oriented interface to Tk GUI toolkitEach GUI component class inherits from class WidgetGUI consists of top-level (or parent) component that can contain children componentsClass Frame serves as a top-level component*try:from Tkinter import * # for Python2 except ImportError: from tkinter import * # for Python3

  • *tkinter OverviewWidget subclasses:

  • Label Component LabelLabels Display text or imagesProvide instructions and other informationCreated by tkinter class Label

    *

  • Entry Component TextBoxTextboxAreas in which users can enter text or programmers can display a line of textCreated by Entry class event occurs when user presses Enter key inside Entry component

    *

  • Button Component ButtonButtonsGenerates events when selectedFacilitate selection of actionsCreated with class ButtonDisplays text or image called button labelEach should have unique label

    *

  • Checkbutton and Radiobutton ComponentsCheckboxSmall white square Either blank or contains a checkmarkDescriptive text referred to as checkbox labelAny number of boxes selected at a timeCreated by class CheckbuttonRadio buttonMutually excusive options only one radio button selected at a timeCreated by class RadiobuttonBoth have on/off or True/False values and two states selected and not selected (deselected)*

  • Mouse Event Handling (cont'd)*

    Event format

    Description

    Mouse button n has been selected while the mouse pointer is over the component. n may be 1 (left button), 2 (middle button) or 3 (right button). (e.g., ).

    ,

    Shorthand notations for .

    Mouse button n has been released.

    Mouse is moved with button n held down.

    Mouse button n has been Prefix clicked over the component.

    Prefix may be Double or Triple.

    Mouse pointer has entered the component.

    Mouse pointer has exited the component.

    Fig. 10.10Mouse event formats.

  • Keyboard Event HandlingKeyboard events generated when users press and release keys

    *

    Event format

    Description of Event

    Any key has been selected.

    Any key has been released.

    key has been selected or released.

    ,

    Shorthand notation for

    and .

    Shorthand notation for . This format works only for printable characters (excluding space and less-than sign).

    key has been selected while Prefix is held down. Possible prefixes are Alt, Shift and Control. Note that multiple prefixes are also possible (e.g., ).

    Fig. 10.13Keyboard event formats.

  • Chapter 9: Python XML ProcessingXML documentsTree structure TagsElementsDataNamespacesHow to use Python to output XML documents?How to parse XML documents using Python packages?*

  • XML DocumentsXML documents end with .xml extensionXML 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 hierarchiesRoot element contains all other document elements

    *

  • *XML NamespacesProvided for unique identification of XML elementsNamespace prefixes identify namespace to which an element belongs

    Topic: Programming in Python

    2002 Prentice Hall. All rights reserved.Outline

    *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 instructionprint (""" """)

    # open data filetry:file = open( "names.txt", "r" )except IOError:sys.exit( "Error opening file" ) print ("") # write root element # list of tuples: ( special character, entity reference )replaceList = [ ( "&", "&" ),( "", ">" ),( '"', """ ),( "'", "'" ) ] # replace special characters with entity referencesfor currentLine in file.readlines():for oldValue, newValue in replaceList:currentLine = currentLine.replace( oldValue, newValue )

    2002 Prentice Hall. All rights reserved.Outline

    *fig16_02.py# extract lastname and firstnamelast, first = currentLine.split( ", " )first = first.strip() # remove carriage return

    # write contact elementprint ("""%s%s""" % ( last, first )) file.close() print ("")

    2002 Prentice Hall. All rights reserved.Outline

    *fig16_04.py# Fig. 16.4: fig16_04.py# Using 4DOM to traverse an XML Document. import sysimport xml.etree.ElementTree as etree # open XML filetry:tree = etree.parse("article2.xml")except IOError:sys.exit( "Error opening file" ) # get root elementrootElement = tree.getroot()print ("Here is the root element of the document: %s" % \rootElement.tag)

    # traverse all child nodes of root elementprint ("The following are its child elements:" )

    for node in rootElement:print (node)

  • Good Luck!Q/A

    *****