CSCI/CMPE 4341 Topic: Programming in Python Review: Final Exam Xiang Lian The University of Texas...
-
Upload
cassandra-golden -
Category
Documents
-
view
240 -
download
0
Transcript of CSCI/CMPE 4341 Topic: Programming in Python Review: Final Exam Xiang Lian The University of Texas...
CSCI/CMPE 4341 Topic: CSCI/CMPE 4341 Topic: Programming in PythonProgramming in Python
Review: Final ExamReview: Final Exam
Xiang LianThe University of Texas – Pan American
Edinburg, TX [email protected]
Review
• Textbook– Self-Review Exercises– Quick Quiz – Exercises
• Time– 8am - 9:45am, May 14 (Thursday)
• Place– ENGR 1.290 (classroom)
2
Review
• Lecture slides– Basic concepts in Python– Control Structures– Functions– Lists, Tuples, and Dictionaries– Introduction to Object-Oriented Programming– Graphical User Interface Components– Python XML Processing– Database & SQL
3
Review
• Multiple Choices
• True/False Statements
• Programming– Debugging– Write the code
• Bonus Question
4
Chapter 1: Python
• Python is a scripting language– It is not compiled as an executable file
• Python– Structured programming
• Divide and conquer
– Object-oriented programming• Class and object
– Data encapsulation– Inheritance– Polymorphism
5
Chapter 2: Basic Concepts in Python Programming
• Arithmetic operators and their precedence
• Commonly used Python rules/functions– print()
6
Arithmetic Operators
• Symbols– * # multiply– / # divide– % # modulus– ** # exponential– // # floor division
• Order– Operators are done in order of parenthesis, exponents,
multiply and divide (left to right), and lastly add and subtract (left to right)
7
Chapters 3 & 4: Control Structures
• The syntax of basic sequence, selection, and repetition structures in Python– Selection
• if, if/else, if/elif/else
– Repetition• while, for
8
Syntax of Control Structure
9
total = total + Gradecounter = counter + 1
if Grade>=60: print ("Passed")
if Grade>=60: print ("Passed")else: print ("Failed")
10
for Repetition Structure
• The for loop– Function range is used to create a list of values
– range ( integer )
» Values go from 0 to given integer
– range ( integer1, integer2)
» Values go from first up to second integer
– range ( integer1, integer2, integer )
» Values go from first up to second integer, but increases in intervals of the third integer
– The loop will execute as many times as the value passed
– for counter in range ( value ):
[0, integer-1]
[integer1, integer2-1]
[integer1, integer2-1]
10
Chapter 5: Functions
• Modules and pre-defined functions– import moduleName– math
• math.floor ()
• math.ceil ()
– random• random.randrange()
• Syntax of user-defined functions
11
12
Module math Functions
• Module– Contains function definitions and other elements
• All of which are related in some way
– Calling a function• functionName ( argument1, argument2 )
– The import keyword is used to include a module– Invoking functions from a module
• Use the module name followed by the dot operator (.)
• moduleName.functionName( argument )
13
Random-Number Generation
• The random module– Used to generate a random number for the
programmer– Function randrange
• Generates a number from the first argument up to, but not including, the second argument
• Each number in the range has the same likelihood of being selected by the function
– random.randrange(a, b)
14
User-Defined Functions
• Definitions– Functions must be defined before they are used– def functionName ( paramList ):
• functionName is a valid identifier
• paramList is a comma separated list of parameters received
• The actions of the functions then follows– They should all be indented appropriately
– The actions are also called the block or the function body
Chapter 6: Lists, Tuples, and Dictionaries
• Creation and manipulation of sequences– String– List – Tuple
15
Example of SequencesC[0] -45 C[-12]
C[1] 6 C[-11]
C[2] 0 C[-10]
C[3] 72 C[-9]
C[4] 34 C[-8]
C[5] 39 C[-7]
C[6] 98 C[-6]
C[7] -1345 C[-5]
C[8] 939 C[-4]
C[9] 10 C[-3]
C[10] 40 C[-2]
C[11] 33 C[-1]
Name sequence (C)
Position number of the element within
sequence C16
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!
17
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
18
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
19
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
20
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 (self)• All methods must at least specify this one parameter• Represents object of class from which a method is
called• Called self by convention
21
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
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
Chapter 8: Graphical User Interface Components
• Components– Label – Entry– Button– Checkbutton & Radiobutton
24
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
25
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)
26
Chapter 9: Python XML Processing
• XML documents– Tree structure – Tags– Elements– Data
27
Chapter 10: Database & SQL
• Relational database– Database schema– A set of relational tables
• SQL (Structured Query Language)– A database language– Syntax of SQL
• Use Python to submit SQL to databases
28
Example of Table: Employees
29
SQL
• A program might select data from the table to create a query result – E.g., to retrieve the location of each department, in
increasing order by Department number
– SQL: • SELECT DISTINCT Department, Location
FROM Employees
ORDER BY Department
30
SQL Results
31
SQL on Books Database
• SELECT * FROM tableName– SELECT * FROM Authors
– SELECT AuthorID, LastName FROM Authors
• SELECT columnName1, columnName2, … FROM tableName WHERE criteria– SELECT Title, EditionNumber, Copyright
FROM Titles
WHERE Copyright > '2014'
32
Example of Using pyodbc Packagehttp://en.wikibooks.org/wiki/Python_Programming/Dat
abase_Programming
import pyodbc DBfile = '/data/MSAccess/Music_Library.mdb'conn = pyodbc.connect('DRIVER={Microsoft Access Driver (*.mdb)};DBQ='+DBfile)#use below conn if using with Access 2007, 2010 .accdb file#conn = pyodbc.connect(r'Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ='+DBfile)cursor = conn.cursor() SQL = 'SELECT Artist, AlbumName FROM RecordCollection ORDER BY Year;'for row in cursor.execute(SQL): # cursors are iterable print (row.Artist, row.AlbumName) # print row # if print row it will return tuple of all fields cursor.close()conn.close()
33
Good Luck!Good Luck!
Q/AQ/A