New User Special Price Expires in

Let's log you in.

Sign in with Facebook


Don't have a StudySoup account? Create one here!


Create a StudySoup account

Be part of our community, it's free to join!

Sign up with Facebook


Create your account
By creating an account you agree to StudySoup's terms and conditions and privacy policy

Already have a StudySoup account? Login here

Web Page Design

by: Lisette Hodkiewicz

Web Page Design CS 2100

Lisette Hodkiewicz
GPA 3.83

Lotfi Othmane

Almost Ready


These notes were just uploaded, and will be ready to view shortly.

Purchase these notes here, or revisit this page.

Either way, we'll remind you when they're ready :)

Preview These Notes for FREE

Get a free preview of these Notes, just enter your email below.

Unlock Preview
Unlock Preview

Preview these materials now for free

Why put in your email? Get access to more of this material and other relevant free materials for your school

View Preview

About this Document

Lotfi Othmane
Class Notes
25 ?




Popular in Course

Popular in ComputerScienence

This 151 page Class Notes was uploaded by Lisette Hodkiewicz on Wednesday September 30, 2015. The Class Notes belongs to CS 2100 at Western Michigan University taught by Lotfi Othmane in Fall. Since its upload, it has received 5 views. For similar materials see /class/216884/cs-2100-western-michigan-university in ComputerScienence at Western Michigan University.

Similar to CS 2100 at WMU

Popular in ComputerScienence


Reviews for Web Page Design


Report this Material


What is Karma?


Karma is the currency of StudySoup.

You can buy or earn more Karma at anytime and redeem it for class notes, study guides, flashcards, and more!

Date Created: 09/30/15
Chapter 4 Dictionaries Whenlndioes Won t Do Lotfi Ben Othmane Department of Computer Science Western Michigan University 1272009 1 Roadmap Overview Creating a Dictionary Dictionary Operations String Formatting Dictionary Methods Example of Use of Dictionary 1272009 2 1 Overview I Dictionary is a data structure in which you can refer to each value by name I Unlike sequence where you refer to a value using a number I Elements of a dictionary are not ordered 1272009 3 1 Overview Cont I A dictionary is a set of pairs of keys and their corresponding values I A key is separated from its values by a colon the n u items are separated using commas gtgtgt phonebooki39AllcE39123439Bth39345639Dav1d39345 Bethy Alicey Davldv Create a dictionary gtgtgt phonebook 39beth 39 1234 345 Traceback most recent call last File quotltpyshell3gtquot line 1 in ltmodulegt phonebook39bethw KeyEzrcr 39beth39 gtgtgt phonebook39aethq 3456 access a dictionary Dictionary keys are case sensitive 1272009 2 Creating a Dictionary I dict type method creates a dictionary from another mapping Create a dictionary from a list gtgtgt items name3939Jchn39 39age3942 gtgtgt ddictitems gtgtgt dt 39name 391 Access values of items using key name JO n gtgtgt dt 39 John John is a value and not a key Traceback most recent call last File quotltpy5nell15gtquot llne 1 1n ltmodulegt In 39 d39J 1272009 2 Creating a DictionaryCont gtgtgt ddlctname39Jchn39age42 gtgtgt d Create a dictionary 39 39 42 39name39 gtgtgt Contacts 39Al 39John39l 39l 23 39foo drive39 Create a dictionary where an item includes many values 39 ddre39 39Bar drlve39 39Alice39 a 39 oo drive39ll 39phone39 123 addre 39foo drivev accessadictionary elements gtgtgt Contacts39AllCe39 39addre 39foo drlve39 1272009 3 Dictionary Operations lend returns the number of items key value pairs ind dk returns the Value associated with the key k dk vassociates the value v with the key k deldk deletes the item with key k k in dchecks whether there is an item in d that has the key k 1272009 3 Dictionary Operations Cont gtgtgt Contacts i39Beth39 39phone39 456 39addre39 39Bar drive39 39Allce39 i39phone39 123 39addre39 39foo auve39ii gtgtgt lencontacts Get the length of a dictionary 2 gtgtgt 1311Contact54Allce39 Get the length of a sub dictionary 2 i i gtgtgt contactsBeth1 Access a dictionary using key Beth 39phone39 456 39addre39 39Bar drlve39 gtgtgt contacts 39beth39 Access an item using a key that does not exist in the dictionary Traceback most recent call last File quotltpysheut32gtquot line 1 in ltmodulegt contactsi39 KeyEzror 39b th39 gt 39betb39i39phinE39 444 39addre39 39ancthc 1 IlV gt i i 4 U2 gtgt contacts 39Beth39 39phone39 456 a dre39 39Bar drive39 39phone39 123 39addre39 39foo drlve39 39beth 39 addre 39 39 another drive 39 H 44 72009 Associate a value to key beth ice39 A i 39phone39 3 Dictionary Operations Cont gtgtgt cont t5 39Beth39 phone39 456 39addre39 39Bar drlve39 39Allce39 39phane39 12 39addre39 39foc drive39 39beth39 i39phone39 3 444 39addre39 39another drive gtgtgt iel contacts39Bet39 Delete a record from a dictionary 39Allce39 i39phone39 123 39addre39 39foo duve39 beth39 39phone39 444 39addre39 39another drive39 gtgtgt contacts 39Allce39 i39phone39 123 39addre39 39foo duve39 39beth39 i39phone39 444 39addre39 39another drive gtgtgt 39Allce39 1r Contacts True Check if a key exist in a dictionary gtgtgt 39Bk 39 Contacts False 1272009 9 3 Dictionary Operations Cont I Run example ch4 1py Output of the program Phone number p or address a a Beth39s address 1s Bar street 42 1272009 to 4 String Formatting I Use key to refer to the key used to access a dictionary inside the string gtgtgt people t39Beth39 i39phene39 39910239 39addr 39Bar street 4239 39A lice39 t39phone39 39234139 39addr39 39Foo drlve 2339 39Cecl 139 39 hone39 39 15 39 39addrquot 39Baz avenue 9039 gtgtgt quotBeth39s mfermetlon time hsquot peo le quotBeth39s information i39phone39 39910239 addr39 Bar Stre at quot Format string using data from a dictionary 1272009 4 String Formatting Cont I Use key keys as conversion specifiers gtgtgt template quot39lthtmlgt ltt adgtlttltlegtt1tlEsltt1tlegtltheadgt ltrgtetextsltpgt t39tltle39 39My Home Page39 39text39 39Welceme t t my home pagei 39 gtgt pint template 9 data use keys and d39 t39 nary as lthtml converSIon specmers for template ad t1tlegtltheadgt d gt lthe gtlttitlegtMy Home Pagelt ltbo ygt lthlgtMy Home Pagelthlgt ltpgtWelcome o my home pagetltpgt ltbodygt 1272009 5 Dictionary Methods Clear method copy method fromkeys method get method hasikey method items methods keys methods pop method popitem method setdefaut method update method values method 1272009 51 clear Method I Remove all items from the dictionary gtgtgt xll gtgtgt gtgtgt x39name 39John39 gtgtgt y l39name39 gtgtgt xll gtgtgt x ll gtgtgt y l39name39 gtgtgt xy gtgtgt x l39name39 39John39l gtgtgt xclear gtgtgt x 39John l 39John39l ll gtgtgt y ll 1272009 y variable still has an element although x does not clear method removes all items from dictionary x and y 52 copy Method Return a new dictionary with the same key the values I are not copied but referenced gtgtgt username39 39admin 39machlnes39 foc39 39bar39 39baz39 gtgt y gtgtgt yusemame mlh Modification ofthe value for key username gtgtgt y machmes remove bari on dictionary y The method does not gtgt 2 change the value for the key on dictionary x 39username39 39admln39 39machlnes39 39foo39 39baz39n gtgtgt y l39username39 39mlh39 39machines39 39foo39 39baz39 gtgtgt X39mach1nes39 append39t d39 gtgtgt X 39username39 admin 39machlnes39 foo39 39baz39 39third39 gtgtgt y l39username 39 machlnes39 39foo39 39baz39 thlrd39l gtgtgt x39mah1nes39 139third39 Modification ofthe list for key machines on dictiona y is also apglied to dictionary x y y r y gtgtgt X l39username39 39admin39 39machlnes39 oo 39thl third39l gtgtgt y 39thlrd39 39thlrd39 l39username39 39mlh39 39machines39 39foo39 1272009 15 53 fromkeys Method Create a new dictionary with the given keys each with I a default value Create a new dictionary With keys prowded in the list Default values are None gtgtgt dictfromkeys name39 39age l39age39 None 39name39 None gtgtgt mydic dictfromkeys39name39 39age39 39unknrwn 39 gtgtgt mydic 39age39 39 unknown i 39name39 39 unknown ii Create a new dictionary with keys provided in the list Default values are unknown 1272009 54 get Method Access a dictionary items If the element does not exist do not throw an error but return a default value indicating the key does not exist in the dictionar An error is thrown when we access a dictionary using a key for item that does not exist in the dictionary Traceback most recent call last pinp igt 39 Ragesls39aldyictignary item and report NA if the a 39Dame39 item does not exist nt dget name39 39NA39 gtgtgt 1 gtgtgt ii d39name39 p 1 Odulegt Access a dictionary item and report None if the dget39name39 element does not exist gtgtgt d39name39 John dget39name39 Access a dictionary item 1272009 55 haskey Method Check whether a dictionary has a given key The method returns False as the key does not exist gtgtgt dii gtgtgt dhasikey39name False gtgtgt d39nam33939Jhn39 gtgtgt dhasikey39name39 True The method returns True as the key exist 1272009 56 items Method Returns all the items of a dictionary in the format key value as a list gtgtgt d l39tltle39 39Pythcn Web Slte39 39url39 39httpwwwtpyt hcrnorg39 39spam39 0 gtgtgt dit url39 39httpwwwpythonorg39 39Spam39 0 39title39 39 Python Web Slte39 gtgtgt d The method returns the list of all items l39url39 39httpwwwpythonorg39 39spam39 0 39title39 39Pytho 11 Web Site39l The method does not change the dictionary d 1272009 19 57 keys Method I Return a list of all keys in a dictionary gtgtgt d 39tltle 39Python Web Slte 39url39 httpwwwpyt honerg39 39spam39 0 keys 39url 39spam39 39title39 List of keys in dictionary d 1272009 20 58 pop Method Get the value corresponding to a given key and then remove the key value pair from the dictionary gtgt 1 i39url 39httpwwwpythonorg39 39spam39 0 39tltle39 Pytho Get the value of key url and remove 39httpWWpython org39 the key and value from d d i39spam39 0 39tltle39 39Python Web site39 gtgtgt dpop Traceback mos recent call last File quotltpy5nell52gtquot line 1 in ltmodulegt pcgtp TypeEor pop expected a least 1 arguments got 0 Pop method requires a key as a parameter 1272009 21 59 popitem Method Pop the first item from the dictionary gtgtgt d i39spam39 0 39tltle39 39Python Web Site39 Tipi39 fpgemm Pop the first item from the dictionary 39txtle39 39Python Web Slte39 1272009 22 510 setdefault Method Access an item in a dictionary using a key similar as get method If there is no item in the dictionary with the required key then create a new item with key value provided as parameters 39title39 Python Web Site39 gtgtgt dsetdefault39ul39 39Pythencom39 gitgon39com39 Create an item with valuekey url Python H to gtlt Hvrr D o 5 o 0 39title39 39Python Web Site39 39 om39 m with key url 39 39P 1 39Python Gom39 Access existing Ite gtgt 39url39 39Pythoncom39 39title39 39Python Web Site39 1272009 5 I Update a dictionary with elements values of another dictionary gtgtgt d l39url39 39Python Om39 39tltle39 39Python Web Slte39 gtgt x 39uxl39 39wwnpychc1Lom39 gtgtgt x 39ur gtgtgt dupdate x gtgt d l39url39 1272009 1 1 update Method 39wwwpythoncom39l 39wwwpythoncom39 39tltle39 39Python Web slte39 Update dictionary d with value of the key url from dictionary x 512 values Method I Return the list of the values in a dictionary l39url39 39wwwpythoncom39 39title39 39Python Web site39 gt dvalues 39wwpythoncom39 39Python Web 311339 Return the values of all items of a dictionary 1272009 25 6 Example of Use of Dictionary A simple database A dictionary with person names as keys Each person is represented as another dictionary with the keys 39phone39 and 39addr39 referring to their phone number and address respectively 39phone39 39234139 39addr39 39Foo drive 2339 39Beth39 39phone39 39910239 39addr39 39Bar street 4239 39Cecil39 p on 39315839 39addr39 39Baz avenue 9039 l 1272009 26 6 Example of Use of Dictionary Cont Descriptive labels for the phone number and address These will be used when printing the output labels hone number39 39addr39 39address39 name rawiinput39Name 39 Are we looking for a phone number or an address request rawiinput39Phone number p or address a 39 Use the correct key 39 quot key 39phone39 Only try to print information if the name is a valid key in our dictionary if name in people print quots39s s is s name labelskeypeoplenamekey 1272009 27 6 Example of Use of Dictionary Cont I Code output gtgt The code here returns the address of Beth Name Beth Phone number p or address a a Beth39s address ls Bar street 42 gtgt is RESTART gtgtgt Name Alice Phone number p or address a a Allce39s address is Foo drive 23 The code here returns the address of Alice 1272009 23 Conclusion The chapter covered 0 O O 0 1272009 What is a dictionary How to create a dictionary Dictionary operations A set of methods that can used with dictionary Files and Stuff V Lotfi Ben Othmane Department of Computer Science Western Michigan University 3312009 1 Roadmap I Overview I Operations on files I Iterating over file contents 33 1 2009 1 Overview I Files are used to store data in a structured or non structured format 0 Example of nonstructured file is text file 0 Example of structured file is shelve I Files are stored on media such as disk They are used to access stored data retrieve data or change the content of a file 33 1 2009 2 Operation on files I Opening files I Reading and writing I Reading and writing lines I Closing files I Example 33 1 2009 21 Opening Files I The function to open a file is 0pennamemodeLbufferingJJ Value I r Read mode default modea file is opened read mode if the mode is not specifie w Write mode a Append mode b Binary mode added to other mode default is text mode Readwrite mode added to other mode 3312009 21 Opening Files Cont gtgtgt fl openx39c textscmef11etxt39 An error raises when file to be opened does not exist Traceback most recent call last Flle quotltpyshellff0gtquot llne 1 1n ltmodulegt t39 IOErroz Errno 2 No such file or directory 39Ctextsomefil etxt39 gtgtgt f1 openr39CTaaChingSpr1ng 2009CSZlUOScurceCodEsCmef1l e txt gtgtgt flreadline quotname 39Magnus Lie Hetland39 nquot Open a file and read a ine 33 2009 22 Reading and Writing read reads data from the file I I write writes data to the file I seek moves to a specified position I tel0 gives the current cursor position gtgtgt fl open1quotCTeachlng3pr1ng 2009CSZLOQSourcetiodesomefll e txt 39 gtgtgt flread4 Read 4 character 39 nam39 gtgtgt f1 read Read content quote 39Magnus Lie Hetland39 nemail 39ma nusf00bar39 nlangu age python39 nnimport t1mennDear namennI would 11k e to learn how to program ear you language langua ge 77 1t methlng I sh d Consld r nnAn y the wa 15 so on y 15 email our correct email addressnnFoovllle t1measc t1mennOscar Frozzbozzquot 3312009 7 22 Reading and Writing Cont I Example of writing to and reading from a file gtgtgt flopenr39CTeah1ngsg1ng 200932lOOSureZodesmaflle txt3939w39 gtgtgt Open the file and write to the file gtgtgt flwr1te39hello 39 gtgtgt flwrite39word 39 gtgtgt deOSE Close the file gtgtgt flopenI39CTeachlng Spllng 2009CS2lOOScurceCCdesomef1le txt3939r I gtgtgt f1read Read from the file 39hello word 39 3312009 23 Reading and Writing Lines I Readline reads from the file I Readlinen reads n characters I Readlines reads all lines of a file I Writelinesist writes a list or a string to a file 3312009 9 23 Reading and Writing Lines Cont gtgtgt flopenrquotcTeachlhg5pnhg 2DD9CSZlOCiSouIce odesom llletxtquot gtgtgt flreadlines Read all lines fromthe file 391 hello word n39 392 0 word n39 393 hello wor d n39 394 hello word 391 gt fl39read 5 Read 5 characters from the file gtgtgt flseekw Change pointerto position 0 gtgtgt f1read5 h i l e gti flIeadliI1e5Ftead the next 5 characters O gtgtgt flwritelinesquotn hell wCIdquot gtgtgt fl39f1 3h Writeastring to the file gtgtgt flread11nes gtgtgt f1 39 555k 9 The data is not written to the file WHY gt readllnes 391 hello word n39 392 hello word n39 393 hello wor n39 t hello wor 391 3312009 to 23 Reading and Writing Lines Cont gtgtgt flopenrquot eflletxtquotquotr gtgtgt flreadlines TeachingSpIing ZOO9CSZlOOSourceCodesom File is open with readwrite mode 391 hello word n39 392 hello word n39 393 hello wor d n39 394 hello word 391 gtgtgt flwritelinesquotn hello wordquot gtgtgt flflush gtgtgt fl readl lnes gtgtgt flseeklol Textk w nentothef e flreadlines 391 hello word n39 392 hello word n39 393 hello wor d n39 394 hello word n hello word39 3312009 ll 24 Closing Files I Flush writes text in buffer to the file I Closeclosesafile writelinesquotn hello wordw seek 0 readlines 0105e ClosethefHe 391 hello word n39 392 hello word h39 393 hello wor d n39 394 hello word n hello wordn hello word39 3312009 12 3 Iterating over File Contents I Iterating byte by byte I Iterating one line at a time I Iterating with fileinput I Example Wat2009 13 31 Iterating Byte by Byte gtgtgt jef precesschar gtgtgt filename rquotCTeach1ngSpr1ng 2003CSZlQOSourCeCode someflletxtquot gtgtgt fZOpen filenamei Use read and while loop to iterate gtgtgt 11 True and read a file byte by byte Charf readl if it Char 1 Break is used to exist the loop process char i i iD J amt2009 14 32 Iterating One Line at a Time gtgtgt f39ClOSEQ Use readline and while loop to iterate pen fllename Tina and read a file line by line lin readline s F 7 line39 Break is used to exitthe loop process line 1 hello word 2 hello word 3 hello word 4 hello word n hello wordn hello ward war2009 15 32 Iterating One Line at a Time gtgtgt f openfilename gtgtgt f llne ll freadlines rocess line p freadnes function returns a list that we iterate on 1 hello word 2 hello word 3 hello word 4 hello word n hello wordn hello word war2009 is 33 Iterating with fileinput gtgtgt ffileinput f l Read a text file into an gtgtgt ines i einputinput i ename gtgtgt lines Iterator ltfile1nputFileInput instance at 0x02625C88gt gtgtgt l1nesnext0 391 hello word n39 Use next method and gtgtgt linesreadllne readHneOto getHnesfron 392 hello word n39 the Iterator 393 hello word n39 An open textfile can not be gtgtgt linesfileinputinputfilename opened agah Traceback most recent call last Fi quotltpysnell91gtquot line 1 in ltmodulegt le nputinputfilehsme File quotCPytnon26llbfileinputpyquot line 102 in input raise Ru timeErzor quotinput already active RuntimeErrez input already active gtgtgt filein utclose p Cbsea b Wat2009 t7 34 Example gtgtgt filename rquotCTeaCh1ngSpr1ng 2009CSZlOOSOuICeCOde somefiletxt openfilename 39 gtgt f 39Thls w39 ls the flrst llne39 gtgtgt1wi gtgt f 39This second third openfilename vThiS is the first linemv Read file content into 3 gtgtgt second tupb 39This is the second linen39 gtgtgt third This is the third llnen39 gtgtgt f Close Read file content into a list gtgtgt lines llstopenfllenameH gtgtgt ines 39Thls is the first 11nen39 39Thls is the second llnen39 39 Thls is the thlrd llnen39 amt2009 m Conclusion In this chapter we covered 0 How to open and close a file 0 Modes of opening files 0 Reading from a writing to a file 0 Iterating over file content 3312009 19 x Chapter 3955 C o39ndiftionals Loops And some cher Statements Lotfi Ben Othmane Department of Computer Science Western Michigan University 232009 1 Roadmap Overview Conditional Statements Loop Statements Advanced Statements 232009 2 Blocks Boolean Values Assertions 1 Overview 232009 11 Blocks A block is a group of statements A block could be set to be executed only if a condition is true A block could be set to be executed several times loop A group is created by indenting part of the code ie putting spaces in front of the statements x1 while xlt1oo x1 Example of prim x statement blocks print quotLast number isquotx 232009 4 12 Boolean Values values True and False Python interpreter associates 0 and 1 to boolean Traceback most ecen call last e quotltpy5helli r18gtquot r l or name 39true39 gtgtgt False0 True gtgtgt l False gtgtgt Nonel False gtgtgt None0 232009 False line 1 in ltmodulegt is not deflned Check if a value or expression if it is boolean or not 12 Boolean Values Cont Python interpreter conside rs the following values when evaluated as boolean false None 0 0 I J The function boo evaluates a value as a boolean variable gtgtgt boolm False gtgtgt bool Fal gtgtgt boolNOne False gtgtgt booll True gtgtgt bool 0 False Evaluation as a Boolean variable of expressions strings and numbers gtgtgt boolwcs2looquot True gtgtgt bool 232009 False 12 Assertion I Assertion is equivalent to if not condition Crash program I Could be used to make sure that to continue in the program a condition must be evaluated to True 10 0 lt age lt 100 39 age 1 Condition evaluatedto False gtgtgt gtgtgt a Condition evaluated to True gtgtgt 1 Traceback most recent call last File quotltpyshell33gtquot llne 1 in ltmodulegt assert age lte1 AssertiOnErrOr 232009 2 Conditional statements I A statement or a block of statements that is executed only if a condition is evaluated to be True If the condition is evaluated to be False than the statement or the block of statements is not executed 232009 21 Conditional Statement Clauses I A conditional statement has the following syntax If condition True 39 Blockt0 execute X1 If statement ifx1 print quotI am equal to 1 x I A conditional statement may include an else clause x1 ifx1 39 m It 1quot prfn am equa 0 X Else clause else print i am not equal to 1quotx 232009 21 Conditional Statement Clauses Cont I A conditional statement may include else ifquot statement using the clause elif num input39Enter a number 39 if num gt 0 print 39The number is positive elif num lt 0 elif clause print 39The number is negative39 else print 39The number is zero39 232009 21 Conditional Statement Clauses Cont I A conditional statement may have nesting blocks 232009 number input39Enter a number between 1 and 10 39 if number lt 10 if number gt 1 print 39Great else else print 39Wrong Nested conditional statement print 39Wrong 22 Comparison Operators I Comparison operators are used to compare things Expression Description X y x equals y X lt y x is less than y x gt y x is greater than y Table of x gt y x Is greater than or equal to y operators x lt y x is less than or equal to y X y x is not equal to y xis y xandy are the same object x is not y x and y are different objects x in y x is a member of the container eg sequence y 232009 Xnotiny x is not a member of the container eg sequence y 22 Comparison Operators Cont The Equality Operator Operator sign is used to check if two things are equal gtgtgt quotfooquotquotfooquot Compare 2 string values Compare a variable with a string value Compare a variable and a value which are of different data type 232009 22 Comparison Operators Cont The Identity Operator Operator is used to check if two things have the same identity gtgtgt xy123 gtgtgt z123 x and z are equal x and y have the same identity True x and 2 DO NOT have the same identity 232009 22 Comparison Operators Cont The Membership Operator Operator in used to check if a value or variable is a member of another value or variable name rawiinput39What is your name 39 if 39s39 in name The code checks if s is a print 39Your name contains the letter quotsquot39 member 0f the inPUt String else print 39Your name does not contain the letter quotsquot39 What 15 your name Lotfi Your name does not contaln the letter Example of the above program execution 232009 15 22 Comparison Operators Cont String and Sequence Comparisons Strings are compared based on the order of their characters Sequences are compared based on the order of their items gtgtgt quotalphaquot lt quotBetaquot String comparison False gtgtgt quotalphaquot lt quotbetaquot True gtgtgt 12lt13 List comparison Tru gtgtgt 12lt11 False gtgtgt 134gt2111 Nested list comparison False 232009 is 22 Comparison Operators Cont I Use boolean operator to combine conditions if number lt 10 and number gt 1 print 39Great else print 39Wrong Use of and operator if number lt 10 or number gt 1 print 39Great else Use of or operator print 39Wrong 232009 17 3 Loops I A statement or a block of statements that is executed many times A loop requires a condition to stop the loop While we aren t stopped Send mail Wait for some time Logical example of loops this is not python code 232009 1 a 31 while Loops I while statement is used to repeat a block of statements while any condition is evaluated to be True 1 while xlt 100 Example 1 of while loop print X X 1 name H Example 2 of while loop while not name name rawiinput39Please enter your name 39 print 39Hello s name 232009 1 9 32 for Loops I for statement is used to repeat a block of statements for each element of a set words 39this 39is39 39an39 39ex39 39parrot39 fOVWOVdinWOVd51 Loop for all items in the list print word for number in range1101 Loop for all items in the range print number from 1 to 100 last number less than 101 232009 20 33 Types of Looping I Iterating over a range I Iterating over dictionaries I Parallel iteration I Numbered iteration 232009 21 331 Iterating Over a Range I Iterating over a range of numbers I Ranges work like slices first value last value step gtgtgt Iange10 I 0 1 2 3 4 5 7 a 9 Useofthefunctlon range gtgtgt range172 1 3 5 gtgtgt rangel6 1 2 3 4 5 gtgtgt is number m rangel72 I print numbe Iterating over range 1 35 t Output of the loop or 232009 22 332 Iterating Over Dictionaries I Loop over the keys of a dictionary 39Z39 6 Iterating over a dictionary 39ccrresponds to i dkey y corresponds to 2 x corresponds to 1 2 corresponds to 6 Output of the loop 232009 333 Parallel Iteration I Iterating over two sequences at the same time I May use built in function Zip to construct a list that combines two lists gtgtgt names 39anne39 39heth39 39gecrge39 39damon39 gtgtgt ages 12 45 32 gtgtgt 1 1 Ln rangelennames Loop overtwo I39Sts prrnt names1 391339 agesi 39years o1d39 anne is 12 years old Output of looping overtwo lists c 39 o1d anne39 12 39beth39 45 39george39 32 39damon39 102 age 1n zipnames ages prrnt name 39rs39 a e 39years old39 2 09 Zip two lists and loop over the new list 2 334 Numbered Iteration I Iterate over a sequence and have access to the index of the current object gtgtgt names anne39 39beth geCrge 39damon39 gtgtgt namesappend39cxxxbv39 gtgtgt names Construct sequence strings 39anne39 39beth39 39george39 39damcn39 39cxxxbv39 gtgtgt stringsnames gtgtgt strings 39anne39 39beth39 39george39 39damon39 39cxxxbv39 gtgtgt f string in strings r 39xxx39 1 string strings index 39 censored39 indexl Iterate over a sequence and change the content of any item that contains xxx gtgtgt strings 39anne39 39beth39 39george39 damon39 39Censored39 232009 34 Breaking Out of Loops The break statement The continue statement I The pass statement The While Truebreakldiom The else clause in a Loop 232009 341 The break statement I Statement break ends a loop gtgtgt I m math writ Sqrt The range function generates a gtgtgt 17 n 17 range 939 039 1 sequence of100 items starting Got Wm f 99 d d39 to if root 1ntroot for an en quot 93 Er n The loop breaks when the quot quot root of a number is an integer 31 232009 341 The continue statement I The continue statement causes the current iteration to end and jump to the beginning of the next Skips the rest of the loop body and start a new iteration gtgtgt 5 n y range99 o 71 ti Prints only integers who s root square is an integer 81 64 49 36 Output ofthe loop 25 16 9 232009 4 343 The pass statement I An empty block is illegalin Python Statement pass could be used to fix the problem gtgtgt 1f nam quot7 hnquot Legal blocks Cll39 i No finished yet 7 Use of pass statement print 39Aecess Denied39 3 elif name gtgtgt if name quotJohnquot prlnt 39 eieomequot eli name 39 3 Not finished yet eiif name 39Blll39 print 39Aeeess Deniea39 legaIbIOCkS File quotltpyshell82gtquot line 5 e 39fn Bill39 232009 Indentation ror expected an indented block 344 The while Truebreak Idiom I while True loop provides the ability to loop indefinitely I break statement provides the ability to end a loop While True loops that breaks onlz when the user enter Return gtgtgt Willa True word rawilnpul 39Please enter a word 39 if 1 word r 39 JEQ39 it do sometning witn the word print 39The werj was 39 word Please enter a ward 232100 The word was 632100 The loop breaks when the Please enter a word userenter Return 232009 345 The else Clause in a Loop I An else in a loop is only executed if the loop did not break gtgtgt 5 n t range99 81 71 root Sqrtn 1139 root 1 int root Run else block only ifthe 7 Eng 1quot loop statement does not thaL le break print Didn39t find 1tlquot Dldn39t find it 232009 4 Advanced Statements I Import statements I Assignment magic I List comprehension I Executing and evaluating strings 232009 41 Import Statements I Import something from a module gtgtgt Sqrt6 sqrt method is not builtin function so Python throw an error Traceback most recent call last File quotltpyshelllllgt line 1 in ltmodulegt name 39sqrt39 15 not defined 39 math Import module math and call function sqrt gtgtgt math 5 rt 6 2 4494897427831779 on the module modulenameDOTfunctIon gtgtgt impng39 math 3 foo gtgtgt foosqrt4 2 0 gtgtgt sqrt 4 Import module math and give it another name Traceback most recent call last File quotltpy3hellllEgtquot line 1 in ltmodulegt 4 NameE ro name 39sqrt39 is not defined gtgtgt 1 math impi WZOOQ y W 4 Import all functions of module math 33 42 Assignment Magic I Sequence assignments I Chained assignments I Augmented assignments 232009 34 421 Sequence Assignments I Assign several assignments simultaneously gtgtgt xyz 123 gtgtgt pani x y z Assign a set of values to a set of 1 2 3 variable The numberof items on both gtgtgt x39y Fl39 2 sides must be the same Traceback most recent call la t File quotltpy5hell123gt line 1 1n ltmodulegt X Yr Z ValueEzror need more 15151 2 values to unpack I Unpack a sequence In a variable gtgt valuesl2 5 gtgtgt values 1 2 5 232009 421 Sequence Assignments Cont I Assign a data returned by a function to a tuple gtgtgt Scoundrel cbln39 39glrlfziend39 gtgtgt key value scoundrelpopitem gtgtgt 1 i keyvalue glrlfrlend Marlon l39name39 39F 39Marl irlly l gtgtgt key value scoundrelpopitem gtgtgt p1lai keyvalue I name Robin Each tuple returned by popitem method is assigned to variables key and value 232009 422 Chained Assignments Used to bind several variables to the same value I gtgtgt xysqrt9 gtgtgt x 30 Value returned by the function is 3 Y assigned to both variables 232009 37 323 Augmented Assignments I Short form of some types of assignments I Example xx3 could be written x3 gtgtgt x 3 gtgtgt X3 Augmented assignments as gtgtgt x arithmetic operations 0 gtgtgt x5 gtgtgt var39 fo39 gtgtgt var2 Augmented assignments as operations on strings v v v 39foofoo39 232009 33 43 List comprehension I Construct a list from other lists Example of lists construction gtgtgt Xx 3 x 1 range10 0 4 9 1e 25 3e 49 e4 81 gtgtgt Xy 1 x 1n range3 2 y 11 range3 0 0 0 1 0 2 1 0 1 1 1 2 2 0 2 1 2 2 gtgtgt xx 1 x 1 range10 1f x30 0 9 36 31 232009 44 Executing and Evaluating Strings I Execute or evaluate a python code provided a string I Statement Leo executes a string as a python code I Statement La evaluates an expression I Execute statement can execute a string in a scope different to the current one The scope data structure is a dictionary 232009 20 441 Use of exec statement I Regular use of exec statement gtgtgt axe quotprlnt 39Hello woxldl quot Hello world I Use of exec statement using a scope sqrt Execute a code using exec statement in the current scope Traceback most recent call last Elle quotltpyshell96gtquot line l in ltmodulegt Object is not callable 7 sqrt gtgtgt mys copeii gtgtgt exat quotsqrt lquot 1n myscope gtgtgt sqrt 4 Execute a code using exec statement in myscoge scope and W201 access myscoge dictionary gtgtgt myscope39sqrt39 442 Use of eval statement I Use of eval statement Evaluates an expression entered by a user gtgtgt evalmawilnputUEIlce an arithmeth expresSlsn quot Enter an arlthmetic expresslon 43e5 2 232009 21 Conclusion I In this chapter we covered 0 Conditional statements 0 Loop statements 0 Statements that support several iterations 232009 43 22 Chapter 2 Lists and Tu pieS V Lotfi Ben Othmane Department of Computer Science Western Michigan University 1152009 1 Roadmap Sequences 0 Sequence overview 0 Operations on sequences 0 Membership to a sequence 0 Functions for sequences Lists 0 List overview 0 List operations 0 List methods Tuples 0 Tuple overview o Tuples operations 1152009 1 Sequences o A sequence is a data structure in which elements are numbered Example of sequences Lists tuples and string A sequence is a collection of variables A sequence may include one or more sequences Below are some examples of sequences 0 O O IDLE Z 6 gtgtgt edward 39Edward Gumby39 42 Sequence edward gtgtgt john 39Jclhn Smith39 50 gtgtgt database edward john gtgtgt database Sequence database Edward Gumby39 42 39John Smith39 50 1152009 gtgtgt 11 Operations on sequences I Sequence indexing I Sequence slicing I Adding sequences I Sequence multiplication I Code example for sequences operations 1152009 111 Sequence indexing 0 First element of a sequence has index 0 or 0 and the last element has index 1 gtgtgt greeting quothelloquot gtgtgt greetingm FIrstelement h gtgtgt greetinqkl Last element 0 gtIgt greetingM Last element gtgtgt firstrawiinputquotyearz quotO yearEIZ 9 Firstelementfrom lrS an inputfunction I 1152009 5 111 Sequence indexing Cont Print out a date given year month and day as numbers 1 mon s 39January39 February3939March3939April3939May3939June3939July39 39August39 September3939October3939November3939December39 sequence for months A list with one ending for each number from 1 to 31 12342oth 21 2223243o31 endings 39st 39nd39 39rd39 17 39th39 39st39 39nd39 39rd39 7 39th39 39St39 year rawiinput39Year 39 month rawiinput39Month 112 39 day rawiinpuwDay L31 Intfunctlon converts monthinumber intmonth The data Input to dayinumber intday Integer Remember to subtract 1 from month and day to get a correct index monthiname monthsmonth7number1 ordinal day endingsday7number1 pri ntSEglognthiname 39 39 ordinal 39 39 year MOdUIe omput 111 Sequence indexing Cont I Execute source code file Ch2 1py Year 200 Month 1712 1 Output ofthe module Day 1 3 7 l 8 January 8th 2009 gtgtgt 1152009 112 Sequence slicing I Slicing used to access a range of elements I Below are some examples of slicing 3 4 5 6 7 8 9 10 gtgtgt numbers 1 2 if DMZ 3 a N Slice from element at index 3 to before gtgt numbers 3 1 element at index 6 which is 5 8 9 gtgtgt numbers 71 0 gtgtgt numbers 2 3 4 5 5 7 s 9 10 gtgtgt numbers 2 Slice from the default start position 0 l 2 toelementatindexbefor gtgtgt numbers092 7 9 1 3 5 3 Slice from t2he indeXOto Index8 9 1 gtgtgt numbers using step gtgt 1152009 1 13 Adding sequences Addition of sequences is possible whenever sequences are of the same data structure Examples are below Addition of two sequences having same data structure gtgtgt edward 39Edward Gumby 42 gtgtgt john 39Jchn Smlth39 50 gtgtgt edward john 39Edward Gumby39 42 39John Smith39 50 gtgtgt 1 2 3 4 6 Addition oftwo sequences 1 2 3 439 I 6 of integers gtgtgt 39Hellr 39 39worldl39 gilllo world Addition of two sequences of string 1152009 114 Sequence multiplication 1152009 I Multiply a sequence by a number creates a new sequence L 1 Multiply a sequence of a string llahellohellohello39 35 3 3 Multiply a sequence Nine 5 Multiply a sequence that has None None None None Noneemptyvaue gtgtgt se gtgtgt se Multiply an empty list gtgtgt se5 gtgtgt 115 Code example for sequences operations Example code file Ch2 2py Prints a sentence in a centered quotboxquot of correct width Note that the integer division operator only works in Python 22 and newer In earlierversions simply use plain division sentence rawiinputquotSentence quot screeniwidth 80 textiwidth ensentence boxiwidth textiwidth 6 leftimargin screeniwidth boxiwidth 2 39 t rm print39 39 leftimargin 3939 boxiwidth2 3939 print39 39 leftimargin 39l 39 39 39 textiwidth 39 l39 print39 39 leftimargin 39l 39 sentence 39 l39 print39 39 leftimargin 39l 39 39 39 textiwidth 39 l39 print39 39 leftimargin 3939 boxiwidth2 3939 rint 9152009 ll 15 Code example for sequences operations Cont I Output generated by the execution of module ch2 2py gtgtgt RESTART gtgtgt Sentence quotH2 l5 Very naughty boyquot eeeeeeeeeeeeeeeeeeeeeeeee 77 l l Dashes are added see quotHe 15 very naughty boyquot multiplications in the code i i eeeeeeeeeeeeeeeeeeeeeeeee 77 ins2009 12 12 Membership to a sequence l Check whether a value exist in a sequence I Use of in operator to check if a value is a member of a sequence The membership statement returns a booean value True False to indicate if a value is member of a sequence or not gtgtgt permissions 39w x is not memberoi rw 39x39 permissions False gtgtgt w 4 permisslons Wyisamembem trw True insmug 12 Membership to a sequence Cont Example code file Ch2 3py Check a user name and password ase 39albert39 39123439 39dilbert39 39424239 39smith39 39752439 39jones39 39984339 username rawinput39User name 39 pin rawinput39PN code 39 if username pin in database print 39Access granted39 insmug 12 Membership to a sequence I Output generated by the execution of module Ch2 339py User name and password are not member of the sequence So the module does not output the grant access message gtgtgt RESTART gtgt User name Lotfi 1234 RESTART Access granted User name and password are member of the sequence So the result is Access granted 1152009 13 Functions for sequences Function len max and min are built in functions that returns respectively the length maximum and minimum of a sequence gtgtgt students Ji n39quot1 1m3939Ar 39J lla gtgtgt 16115tudent5 Length of the sequence 4 gtgtgt ma StUdentS Maximum of the sequence Tim39 gtgtgt mm students Minimum of the sequence 39Andrew Minimum of the se uence gtgtgt m1n52371 q 1 gtgtgt max 5 2 3 7 1 Maximum of the sequence 7 ins2009 2 Lists Lists are mutable sequence That is you can I change the list content I Function list converts a string to a list I Function join converts a list to a string gtgtgt mylistlistquotscript programmmgquot Convertastringtoasequence gtgtgt mylist 1536T1111 1tprlo1g111ra1m1 I W 11 W 1T gtgtgt quotjoinmylist vscript programingv Convert a sequence to a string gtgtgt 1152009 21 Lists operations I Changing an element I Deleting an element I Changing a sequence sice 1152009 211 Changing an element I Use assignment to change individual items gtgtgt x123 gtgtgt x16 Change value ofthe item at index 1 1 6 3 gtgtgt 1152009 19 211 Deleting an element I Use reserved word delin a statement to delete an element from a list gtgtgt Students 39John39 39Tlm39 39Andrew39 39Julla39 gtgtgt 1421 students3 gtgtgt mien Delete from the sequence the John39 39Tlm39 39Andrew39 element at index 3 1152009 20 211 Changing a sequence slice I Sequence assignments could be used to change sequence using slicing range of elements gtgtgt Students 39John39 39Tlm39 39Andrew39 gtgtgt students 2 39Thomas 39Steve39 39Brlan39 gtgtgt S 39John39 39Tim39 39Thomas39 39Steve39 39Brlan39 gtgtgt Lookfor content change as the sequence assignments changes the list of elements starting at index 2 1152009 21 22 Lists methods Append method Count method Extend method Index method Insert method Pop method Remove method Reverse method Sort method Sorted method 1152009 22 221 Append method I append method is used to append an object to the end of a list Add an element with value 3 as integer to the end of the list gtgtgt students 39John39 39Tlm39 39Thomas39 39steve39 39Brlan39 gtgtgt Studentsappend3 gtgtgt students 39John39 39Tm39 39Thomas39 39Steve39 gtgtgt students append 39nm39 gtgtgt students 39John39 39Tlm39 39Brlan39 3 39Thomas39 39Steve39 Brlan39 3 39Tlm39 Add an element with value Tim to the end of the list 1152009 222 Count method I Count the occurrence of an element in the list gtgtgt students 39John39 39Ti 39 39Thomas39 39steve39 gtgtgt students count 39Tlm39 2 39Brlan39 3 The element with value Tim occurs 2 times in the list students 39Tlm39 1152009 223 Extend method Extends a given list with elements from another list I gtgtgt al23 gtgtgt b678 Original lists gtgtgt a 1 2 3 gtgtgt aextendb Extended St gtgtgt a 1 2 3 5 7 3 It is similar to the operation of assigning to a slice list gt a 1 2 3 Original lists gtgtgt b 6 7 8 gtgtgt alena b gtgtgt 6 Extended list 1 2 3 6 7 8 1152009 223 Extend method Cont It is different from concatenation which does not change one of the list but copies both lists to a new list gtgtgt a 1 2 3 Original lists gtgtgt b 6 7 8 gtgtgt 31 1 2 3 6 7 8 gtgtgt a 1 2 3 gtgtgt aab gtgtgt a copied lists 1152009 224 Index method I Provides the index of the first occurrence of a value in a list gtgtgt students 39John39 39Andrew39 39Tim39 39FC t3939TanE39 gtgtgt Students3 39Robert39 H I H gtgtgt studentsindexquotT1mquot ndex of the element Tim gtgt t JdentS 2 Value of the element at m index 2 I The method returns an error if the value does note exist in the gtgtgt studentsindex 39 Jennifer39 Value xJenniferi does not Traceback most recent call last eX39Sl file quotltpyshell34gt line 1 in ltmodulegt udents index 1 39 Jennife 39 St ValueError listindexx x not in list 1152009 27 225 Insert method I Inserts an element in the list Original list gtgtgt Students John39 39Andrew39 39Tim39 39Robert39 39Jane39 gtgtgt students33 gtgtgt students insert 3 quotJennifeIquot gtgtgt Students 39John39 39Andrew 39Tim39 39Jennlfer39 39Robert39 Jane39 Updated list includes element Jennifer 1152009 23 226 Pop method I Removes the element at the top of the list and returns it gtgtgt students 4 Original list 39John 39Andrew39 39Tlm 39Jennifer39 Robert39 39Janew gtgtgt studentspop I I 39Jane39 Returned Item It Is also removed gtgtgt students 39thn39 39Andrew39 39Tlm39 39Jennlfer39 39Robert39 New list I Python does not have push method but you can use append method add an element to the end of the list 1152009 227 Remove method I Removes the first occurrence of a value gtgtgt students original 31 39John39 39Andrew39 39Tlm39 39Jennlfer39 39Robert39 gtgtgt students remove quotTimquot gtgtgt Btu Hts Remove an element 39John39 39Andrew39 39Jennlfer39 Robert39 gtgtgt studentsremove quotTimquot Remove an elementthat does not exist in the list T most recent call 165 File quotltpy5hell43gtquot line 1 in ltmodulegt studentsremovequotT1mquot ValueE g 1 1stemovex x not in list 1152009 228 Reverse method I Reverses the order of the elements in the list gtgtgt students Original list 39John39 39Andrew39 39Tlm39 gtgtgt studentsreverse gtgtgt Students 39Jane 39Robert39 39Jennlfer39 39Jennlfer39 39Robert39 39Jane39 39Tim39 Andrew39 39John39 Reversed list 1152009 229 Sort method I Sorts a list gtgtgt students Original list of strings 39Jane39 39Robert39 39Jennifer39 39Tim39 39Andrew39 39John39 gtgtgt studentssort Sorted St gtgtgt Stu nts 39Andrew39 39Jane39 39Jennlfer39 39John39 39Robert39 39Tlm39 gt gt numb rs4278l0 I I gtgtgt numbersjort Sorted list of Integers gtgtgt numb 0 l 2 4 7 3 Sorted list I Sorts a list using as a keythe length of the values gtgtgt students Original list 39Andrew39 39Jane 39Jennlfer39 39John39 39Robert 39Tim39 gtgtgt students sort keylen Sorted list using the length of gtgtgt Students elements as the key 39Tllml 39Jane39 39John39 39Andrew39 39Robert 39Jennifer39 Len3 Len4 Len4 Len6 Len6 Len7 1152009 229 Sort method Cont I Sorts using argument reverse gtgtgt numbers4278l0 numbers sort reverseTrue gtgtgt numbers Sort a list on reverse 8 7 4 2 I 0 gtgtgt numbers4278l0 gtgtgt numberssort gtgtgt numbers 0 l 2 4 7 8 I Note Sort method DOES NOT return values sorted method returns sorted list gt ents Tim39 Jane39 John39 Andrew39 39Robert39 39Jennlfer39 gtgtgt ystudentssort Regular sort gtgtgt y Returned value of sort gtgtgt 1 mi y methOd None gtgtgt Psortemstudents Returned value of sorted gtgt method 1152009 39Andrew39 39Jane 39 39Jennlfer39 39John39 39Robert39 39Tim39 229 Sort method Cont I Sort a list that is referenced using two variables gtgtgt x 39Tim39 39Robert39 39John39 39Jennlfer39 39Jane39 39Andrew39 gtgtgt X gtgtgt 50rt The listx Is referenced In the variable y gtgtgt y 39Andrew39 39Jane39 39Jennlfer39 39John39 39Robert 39Tim39 gtgtgt X 39Andrew39 39Jane39 39Jenmfer39 39John39 39Robert 39Tlm39 The variables x and y refer to the same sorted list ll52009 34 229 Sort method Cont I Sort a list that is copied to a second variable gtgt x 39Andrew39 39Jane39 39Jenmfer39 John39 39Robert 39Tlm39 gtgtgt yx gtgtgt X The listXIs copied toa newlisty 39Andrew39 39Jane39 39Jennlfer39 39John39 39Robert39 39Tm39 gtgtgt y 39Andrew39 39Jane39 39Jenmfer39 39John39 39Robert39 39Tlm39 gtgtgt y sort reverseTrue gtgt y 39Tim39 39Robert 39John39 39Jennifer39 39Jane39 39Andrew39 gtgtgt X 39Andrew39 39Jane39 39Jennlfer39 39John39 39Robert 39Tlm39 The variables x and y do not refer the same list 1152009 35 3 Tuples I Overview of tuples I Tuples operations 1152009 36 31 Overview of tuples Tuples are nonmutable sequence That is you can not change the list content Function tuple converts a sequence to a tuple gtgtgt 124 Tuple creation 1 2 4 I gtgtgt mple quotPythonquot Convert a string to a tuple 1P1 1 1 1 1b 101 1n1 y t gtgtgt tuple247 7 Convert a list to a tuple 1152009 32 Tuples operations Access an element of a tuple Access a range of elements of a tuple gtgtgt xtuplequotPythCnquot Create a tuple 4 Access an element of a tuple gtgtgt x 4 7 01 1H1 Accessaslice ofatuple 1152009 Conclusion u The chapter covered 0 Sequences 0 Lists 0 Tuples 1152009 39 20 7 Chapterquot 9quot M519 is Methods Preparerties and Iterators Lotfi Ben Othmane Department of Computer Science Western Michigan University 3242009 1 Roadmap Constructors Item Access Iterators Generators 3242009 2 Constructors Overview Override Constructors Calling Superclass Constructor Using Super Function 3242009 1 1 Overview A constructor is an initialization method called automatically right after an object of the class is created Example of class that do not use a constructor class FooBar1 def initself value42 Division by O is an error selfmyVaIue vaue We get here a traceback error Example of class that do use a constructor class FooBar2 def finitiself value42 selfmyVaIue vaue 3242009 A 1 1 Overview Cont class FooBar1 does not have a constructor object f1 is of type FooBar1 so variable gtgtgt f1FooBarl myValue does not get a value when the object gtgtgt flmyValue is created Traceback most recent Call last F112 quotltpyshellllgt line 1 in ltmodulegt A FooBarl instance has no attribute 39myValue39 gtgtgt f1 myValue class FooBar2 does have a constructor 42 objecth is of type FooBar2 so variable gtgtgt f2FooBar2 V I d t I h th b t gtgtgt f2myValue my aue oes ge ava uew en eo Jec Is 42 created method ilnlii Is called 3242009 12 Override Constructors I Each class may inherit one or more super classes I A subclass inherits attributes and methods of super classes I When a method is called on an object of a class Python calls the method that is defined in the class If it does not exist it calls the method from the super classes 3242009 12 Override Constructors Cont I Definition of a superclass class Bird def finitiself selfhungry 1 print I am a Bird def eatself if selfhungry print 39Aaaah selfhungry 0 else print 39No thanks I Definition of subclass 1 Class Bird1Bird pass 3242009 12 Override Constructors Cont Definition of a subclass 2 class SongBirdBird def iinit self selfsound 39Squawk def singself print selfsound 3242009 12 Override Constructors Cont In the following examples class Bird1 inherits the constructor of class Bird But class SongBird overrides inherited constructor gtgtgt blBirdl Object b1 called constructor of class Bird 1 am 6 EH superclass of class Bird1 gtgtgt b2SongB1rd gtgtgt b2 Sing Object b1 called constructor of class SongBird 353 and did not call the constructor of class Bird eat Traceback most recent call last F112 quotltpy5nell31gt line 1 in b2eat ltmcdulegt Elle quotltpy5hell19gtquot line 6 39 39 nqy in eat if 591 AttribuCeError songsird instance nas no attzlbute hunqry39 We called a method sing of class SongBird szzoog and method eat of superclass Bird 13 Calling Superclass Constructor I If a constructor is defined for a subclass it overrides the constructor of the superclass A subclass that has its own constructors may call the constructor of its super class by calling it in its constructor I Example of sub class that calls its constructor and the constructor of its superclass 3242009 13 Calling Superclass Constructor Cont I Example of sub class that calls its constructor and the constructor of its superclass class SongBirdBird def finitiself Birdiinitiself selfsound 39Squawk def singself print selfsound gtgtgt Sb SO I am a Bird gtgtgt Sbsing Squawk gtgtgt sbeat Aaaah 3242009 M Ward The constructor of the class and its super class are both called 14 Using super Function super function is used to call the constructor and methods of super classes Example of the use of Super function class SongBirdBird def iinitfsef superSongBird selfiiniti selfsound 39Squawk def singself print selfsound 3242009 l2 14 Using super Function Cont I Example of the use of Super function Cont 0 3242009 Run Che1py gtgtgt SbSongBird gtgtgt Sbsing Squawkl gtgtgt Sbeat Aaaah gtgtgt sbeat No thanks The constructor of the class and its super class are both called N 3242009 Item Access Basic Sequence and Mapping Protocol Subclassing list dict and str Properties Static and Class methods 21 Basic Sequence and Mapping Protocol I Sequences are collection of items I To implement a sequence we need 0 2 methods len and getitems if the sequence is immutable o 4 methods len and getitems setitm and delitem if the sequence is non immutable 3242009 21 Basic Sequence and Mapping Protocol Cont I lensef returns the number of items getitemself key returns the value for the specified key setitemself key value stores a value and associates it with a key delitemself key deletes an item associated with the specified key 3242009 21 Basic Sequence and Mapping Protocol Cont I Code Example def checklndexkey Is the given key an acceptable index To be acceptable the key should be a nonnegative integer If it is not an integer a TypeError is raised if it is negative an lndexError is raised since the sequence is of infinite length if not isinstancekey int long raise TypeError if keylt0 raise lndexError 3242009 21 Basic Sequence and Mapping Protocol Cont I Code Example Cont class ArithmeticSequence effinitiself start0 step1 Initialize the arithmetic sequence start the first value in the sequence step the difference between two adjacent values changed a dictionary of values that have been modified by the user selfstart start Store the start value selfstep step Store the step value selfchanged No items have been modified 3242009 21 Basic Sequence and Mapping Protocol Cont Code Example Cont def getitemself key an item from the arithmetic sequence checklndexkey try return selfchangedkey Modified except KeyError otherwise return selfstart keyselfstep calculate the value def setitemself key value Change an item in the arithmetic sequence checklndexkey 3242009 selfchangedkey value Store the changed value 21 Basic Sequence and Mapping Protocol Cont gtgtgt SAr1thmetiCSequenCel2 Create an object gtgtgt s4 9 if 5 Access objects gtgtgt area Traceback most recent call lasi File quotltpyshelll4gtquot line 1 in ltmodulegt erea File quotCTeachinqSpring 2oo9cszioosOuicecOdechaeaquot line 25 in Aiqetitemi checkIndeXkey File quotCTeachinqSpring 2ooecszioosOucecOdece9e3quot line 9 in checklndex 1f keylt0 raise IndeXEI IndeXEr Raising errors from the object gtgtgt s 39 one39 Traceback most ecent call last File quotltpy5hell15gtquot line 1 in ltmoddlegt 539one39 File quotCTeachinqSping zooecsziooSeucecOdechee3quot line 28 in Aigetitemi checkIndexlkey File quotCTeachinqSpring zooecszioosOurcecOdecage if not 15instancekey int eErrO 3242009 loug raise Typ yo 20 22 Subclassing Classes list dict and str I To get more functionalities of sequences dictionary list and str you may need to inheritthe appropriate sequence class I Example of sub classing of a sequence class class CounterListlist defiinitiself args superCounterList selfiinitiargs selfcounter 0 def igetitemiself index selfcounter 1 return superCounterList selfigetite miindex 3242009 21 22 Subclassing Classes list dict and str Cont gtgtgt c1 CounterListrangelO l 0 1 2 3 4 5 5 7 3 9 Accessthellst gtgtgt Clreverse gtgtgt Cl 9765432101 I gtgtgt el c13 Call method Inherited from the lIst cass 5 4 3 2 l 0 gtgtgt clcounter 0 gtgtgt c14 A Use of the attribute defined In class CounterList gtgtgt clCounter gtgtgt c14c15 7 gtgtgt clcounter 3 3242009 22 23 Properties I Accessor methods methods used to retrieve get an attribute or rebind set an attribute some attributes I Example of Python code that uses accessors class rectangle def lnitiself selfwidth 0 selfheight 0 def seISizegeh size Set attributes width and height selfwidthselfheight size def getSizeSe 3 Get attributes width and height return selfwidth self height 3242009 23 23 Properties Cont I Use of class rectangle gtgtgt rrectangle 5 gtgtgt rwidth 10 gtgtgt rgetSize 10 5 gtgtgt rsetSizelOO40 setamibutes 1 get attributes gtgtgt rhe1 h 4 gtgtgt 3 width 100 gtgtgt rgetSize 100 40 3242009 24 23 Properties Cont l Properties are attributes that are defined through their accessors and are used to simplify access to attributes I Example of code forthe use of Properties import time class rectangle2 def iinit7self selfwidth 0 selfheight 0 def setSizeseIf size selfwidthsefheight size elfchange timestrftimequotYmd HMS limeocaltime def getSizeself selfaccessed timestrftimequotYmd HMS timelocaltime return selfwidth selfheight sizepropertygetSizesetSize 3242009 23 Properties Cont Use of class rectangle2 gtgtgt r2 rectangle2 gtgtgt r2setSlze2943 r2change 3920090317 12443339 gtgtgt r2getSize 29 43 gtgtgt r2accessed 3920090317 12444539 gtgtgt r2setSize2943 set attributes width and height get attributes width and height Access hiden time attribute Change 3920090317 12451939 3242009 24 Accessors Methods To have code executed when an attribute is accessed you must override some methods getattributeself name attribute name is accesse getattrself name attribute name is accessed and the object has no such attribute setattrfelf name value attempt is made to bindthe attri ute name to value delattr self name attempt is made to delete the attribute name 3242009 27 24 Accessors Methods Cont Example of code selfwidth 0 self39he39ght 0 isetattri method def isetat triself name value 39 name size selfwidth selfheight value print quotcalled isetattri se39 Update the value on the dictionary Do not call the set method again self dictiname value by using regular variable def igetat triself name assignment if name quotSizequot 39 isetattri method print quotigetattr quot return selfwidth selfheight el e se raise AttributeError 3242009 23 24 Accessors Methods Cont Outcome of the program execution gtgtgt r3 Rectangle3 gtgtgt r3size3443 Call igetattri method called isetattri gtgtgt r3 39ze getattL Call isetattri method E4 43 3242009 29 24 Static Method and Class Methods Class method are executed on the class attribute Static method are executed on the class Static methods unlike class methods are defined without self argument 3242009 30 24 Static Method and Class Methods Cont class MyCIass statiCmethod Static method def smeth print 39this is a static method39 print quotclasscounterquot mycountergetcounter print quotobjectcounterquotobjectcounter 3242009 24 Static Method and Class Methods Cont classmethod def cmethcs Class method try clscasscounter1 except Exception e clscasscounter0 print e print 39this is a class method39 print quotclasscounter classcounter print quotobjectcounter cscasscounter def omethsef regUIar methOd try selfobjectcounter1 except Exception e selfobjectcounter0 print e print 39this is a class method39 3242009 printquotclasscounter classcounter print quotobjectcounter seifobjectcounter 24 Static Method and Class Methods Cont gtgtgt C1MyClass gtgtgt c2 smeth Call static method objecgcountif l The variable on all objects of gtgtgt C Cmet this is a class method the Class are Changed objectcount 2 objectcounter 1 Each object change its gtgtgt clometh variables this 15 a class method objectcounter 1 3242009 3 Iterators To iterate means to repeat something several times A class supporting iteration implements iiteri method which returns an iterator which is an object with a method next callable without arguments With Iterator class vou do not need to have all elements of a sequence in memory Fibs method without the use of iterator def fibsnum result 0 1 tori in rangenum2 resultappendresult2 result1 return result 3242009 34 3 Iterators Cont I Fibs class using iterator class Fibs def finitiself selfa 0 selfb 1 def nextsef next method selfa selfb selfb selfasefb return selfa def iiter self ineri method return self 3242009 3 Iterators Cont I Use of Fibs class gtgtgt flbs Fibsu gtgtgt in f 1r fibs m u Breaks after 8 mmmeH Next method may raise exception Stoplteration when iterator has no more items 3242009 4 Generator I A Generator is a kind of iterator but defined with regular function syntax I Generators have a statement yield that returns one item ata time of a kind of sequence for each call Nested list I nested 1 2 3 4 5 We want to get the list of items from the list 3242009 37 4 Generator Cont I Generator method to solve the problem def attenmeSted The function use yield for sublist in nested statement which returns one for element in sublist element at a me yield element gtgtgt nested 1 2 3 4 5 gtgtgt f um AL flattennested print num Call of the generator flatten 1 2 3 4 5 3242009 Conclusion We D O O O 0 3242009 covered Magic methods Constructor I Override constructors I Use of super class constructor Item access I Properties I Static and Class methods Iterator I Implements iiteri and neXtmethods Generator I Kind of iterator but uses regular function syntax and a statement yie 20 Chapter 7 More Abstraction V Lotfi Ben Othmane Department of Computer Science Western Michigan University yrs2009 i Roadmap Overview Creating a Class Attributes and Methods Class Namespace Inheritance and Superclass Interface and Introspection 21 92009 2 1 Overview I Class A collection of attributes data and a set of methods functions for accessing those attributes It is synonym to type or kind Examples person table book page I Object Is an instance of a class Example C82100 is an object of class course 21 92009 1 Overview Cont I Polymorphism Use of the same operations applied on different types of data Example use sign to add two strings or to add two integers I Encapsulation Hide an important details about how an object works from the outside word I Inheritance Create a specialized classes from general classes Example shape is a general class and a specialized one could be circle or rectangle 21 92009 4 1 Overview Cont I Example of the use of polymorphism gtgtgt 39Fish39 39License39 39FlshLicense39 gtgtgt 12 Plus operator works for string and 3 gtgtgt ief addxy also 39meger r xy gtgtgt add39Fish39quotLicensequot FlshLicense39 Function add works for string and also gtgtgt add45 integer 9 gtgtgt len 39Fmrd39 gtgtgt lam 139 2 5 7623 Function len works for string and also 5 list 2192009 5 1 Overview Cont I Example of the use of Encapsulation Create an object of class Person definition of gtgtgt me Persom class person will be visited later gtgtgt megreet greeting method returned an error here DO we KNOW WHY Traceback most recent call last File quotltpyshell27gtquot line 1 in ltmeduiegt megeet File quotltpyshell18gtquot line prll tt 2 l o quotselfname AttibuteE Person instance has no attribute 39name39 gtgtgt mesetNamequotLotfi Ben othmanequot gtgtgt megetNamilln Call method setName and getName on the object me ane39 7 in qeet Call method greeton the object me This time we get a greeting not error DO we KNOW WHY 2192009 6 2 Creating a Class I A class has a set of attributes and a set of methods Below is an example of a class definition imetaclassi is a directive we use to tell Python to use the new class style when we use a version older than Python version 3 imetaclassi type Use new style of classes Class Person A class definition starts with the word class than def setNamesef name the name of the class selfname name Class Person has three methods They all use def getNameself the property name return selfname def greetself print quotHello quotselfname 2192009 7 2 Creating a Class Cont Example of the use of class Person gtgtgt foo Person Create object foo of class Person gtgtgt foosetNamequotLtfl Ben Othmanaquot Ethiog thmane Call the39methods of the class or gtgtgt foo5etNamequotLotfi Ben ochmanequot 300988 Its attrlbUteS gtgtgt foogetName 39Lotfi Ben Othmane39 We get an errorwhen we try to gtgtgt fooName access an attribute that does Tzaceback most recent call last Otexmt39nthe dass File quotltpy5hell46gtquot line 1 in ltmodulegt e AitributeError Person instance has no atiribute 39Name39 gtgtgt fOO namequotLotf1 Beniothmane quot gtgtgt foogetName We can access an attribute for Lotf1 Beneothmane39 read orwrite 2192009 3 2 Creating a class Cont One of the differences between a method and a function Is the use of a parameter type self gtgt A 5 lass Amethod has selfreserved methodself word as parameter prlnt h e a elflquot jEI gtgtgt deg funct10n print quotI do not have a self gtgtgt 001655 Method method does not require a parameter a value for self parameter not have a self 2192009 9 3 Attributes and Methods Attributes and methods are by default public To mark an attribute or a method as private within Python we use double underscore before the name of the attribute or method Person instance at OXOZ4S4F58gt Person setName Lctfl B2 name gtgtgt foo chmanen Attributes and methods of gtgtgt foo the class Person are 39Lotfl Ben Othmane39 7 accessible from outside the gtgtgt fOO SetNamequotLCtf1 BED Otlimanequot Class 2192009 3 Attributes and Methods Cont Definition of a class with private and public methods and attributes class Person def setNamesef name selfname name def getNameself return selfname def greetself print quotHello quotselfname Methods setName getName greet and attribute Name are public Method idoubleunderscoreself is defidoubleunderscoreself private print quotaccess double underscorequot def ioneunderscoreself print quotaccess one underscore def publicunderscoreself smog sel idoubleunderscoreo 3 Attributes and Methods Cont gtgtgt me PPerson gtgtgt 1 gre gtgtgt lpusimdemre gimme Methods who s names is prefixed with one or two underscores are not public gtgtgt I gtgtgt me PPersOn gtgtgt meeoneungerscorell Method doubeunderscore is not access one un ersccre gtgtgt meidoubleunderscore access39ble Traceback most recent Call last Flle quotltpy5hell94gtquot line 1 in ltmodulegt mei bleunderscore AttributeError PPerson i gtgtgt me 7PPersonidoubleunderscore access double underscore Method doubeunderscore is accessible through ng the use of the name of the class stance has no attrlbjte 39 doubleunderscore39 m 4 Class namespace I Regular scripts and programs are executed in the global namespace Class code is executed in the class namespace NOT in the global namespace 2l 92009 l3 4 Class namespace Cont u gtgtgt 1 fomx quotquotquotquot X X Afunction definition gtgtgt liif MemberCounter members 0 iii 1n1tself MemberCounter membersl A class definition gtgtgt foo 5 Call to a function gtgtgt mlMemberCounter gtgtgt mLmlH Call to the class Its method and Its gtgtgt ml members attribute gtgtgt vars 39MemberCounter39 ltclass main MemberCounter at 0x02691900gt 397 ibulltlnsgi39 ltmodule 3947E311t137 39 builtrlngt 39Aipackagegi39 No me 39ml39 lt47main MemberCounteirlnstance at 0x0268C760gt 39Ainame 39 39Aimaingi39 39foo39 ltfunctlon foo at 0x0268E970gt 3947 4739 N Notice that attribute members is not in Zia2009 the global scope M 4 Class namespace Cont gtgtgt gtgtgt ml mberCounter m2 MemberCounter mlin1t gtgtgt ml 2 gtgtgt gtgtgt 3 gtgtgt 3 gtgtgt gtgtgt 3 gtgtgt mlmembers 39cs210039 Create two instances of class MemberCounter m1 and m2 v v v m2 inn m2 members ml members Each instance of MemberCounter class has its own scope ml members quot 52100quot m2 members 2192009 5 Inheritance and Superclass Python supports inheritance from a single or multiple classes A subclass in Python may override a superclass method A subclass inherits all of a superclass methods and attributes 2192009 5 Inheritance and Superclass Cont class Filter def initself selfbocked def filterself sequence return x forx in sequence if x not in selfblocked class SPAMFilterFilter SPAMFiIter is a subclass of Filter def initself Overrides init method from Filter superclass sefbocked 39SPAM39 Definition of class SPAMFiteras a subclass of class Filter In class SPAMFifer we override class Filter 2192009 17 5 Inheritance and Superclass Cont gtgtgt f Filter gtgtgt finit gtgtgt ffilterl23 1 2 3 gtgtgt SSPAMFilter gtgtgt sinit gtgtgt sfilter39SPAM3939e gs3939SPAM3939bacon3939emall3939Amazoncom39 39eggs39 39bacon39 39emal 39 391 q 1 39Amazoncom otice 1 Method filter is inherited from the supercalss 2 Method inif is overridden in the subclass 3 The list provided to the method filterapplied on object 5 is filtered using the method specified in the subclass 2192009 13 5 Inheritance and Superclass Cont I lssublass method could be used to check inheritance of a class from a a superclass lsinstance method could be used to check if an object is an instance of a specified class gtgtgt issubclassSPAMFilter Filter True Zisgswbdas Filter SPAMFllter We use issubclass to check if a gtgtgt lsinstance 5 str class is a subclass of a another False class gtgtgt islnstances Filter We use isinstance to check if 7 object 5 is of type Filter str or gtgtgt SPAMFilteribasesi SPAMFiter ltclass imalnid llter at 0x02691960gt gtgtgt 57cla357 ltclass imalniSPAMFllter at 0x02688300gt 213992009 19 ue gtgtgt issubclass Filter SPAMFilter Fal Se 5 Inheritance and Superclass Cont I Python supports multiple inheritances Le a class could be a subclass of more than one class I The use of multiple superclasses should be with special care as it may lead to unforeseen complications 0 Eg should be known that if two superclasses use the same name of a method the method that is inherited by the subclass isthe method from the class that is the lastin the list of superclasses ZlgZOOQ 20 5 Inheritance and Superclass Cont class Calculator def calculateself expression selfvalue evalexpression class Talker def talkself print 39Hi my value is39 selfvalue class TalkingCalculatorCalculator Talker pass Class TalKingCacuator has two superclasses which are Calculator and Talker 2192009 5 Inheritance and Superclass Cont gtgtgt tc TalkingCalculator calculatequot35Equot V talk Class TalkingCaculatorinherited from its 139 my in rm superclasses two methods calculate and e 2 gtgtgt tamalue talk It also Inherited attribute value v v v rtrt on v v v rt 0 2192009 6 Interface and Introspection I With Python there is no interface However Python supports introspection I Introspection is the ability to get information about an object his attributes methods modules source file etc 21 92009 23 6 Interface and Introspection Cont Method hasattr checks if an object has a gtgtgt nasattr to talk39 rue spectfled method or attribute gtgtgt hasattrtc39talk1n39 False gtgtgt getattrtcquottalk1ngquot Does mat existquot 39Does net exist39 gtgtgt getattrtcquotlalkquotquotices not existquot ltbound method TalkingCalculatortalk of ltimainiTalk1ngCalculat4 r lnstance at 0x02686EEOgtgt gtgtgt callablegetatrtc 39fncrd39 NoneH alse gtgtgt callablegetattrtc39Calculata39None True gtgtgt Setattr tc 39name39 39Jchn39 gtgtgt tC39name Method setattr sets a value for a specified 39JOhn39 tt 39bute on an ob39ect gtgtgt C i i a n J l39name39 39John39 39value39 19 idicti returns the scope of the object 2192009 24 6 Interface and lntrospection Cont gtgtgt rpm 1 spe gtgtgt getmemberstc ido i None 397 ulei i 7 nd method TalklngcalculatorCalculate of lt malniJ39alklngCalculat 39 ct 1m 39 39 mam 39 39calculate39 ltme or mstance at 0x02686EEOgtgt 39name39 39JOE39 39talk ltbound me thod TalklngCalculatortalk of ltimalniTalkingcalculator instanc e at 0x02686EEOgtgt 39value39 19 2192009 Getmembers function returns the methods and attributes of an object Conclusion I In this chapter we covered 0 What is a class an object polymorphism inheritance and encapsulation o How to create a class 0 What are private and public attributes and methods 0 What is and object scope o How to use inheritance and superclass o How to use introspection 2192009 Instant Hacking The Basics V 162009 Lotfi Ben Othmane Department of Computer Science Western Michigan University Roadmap Installing Python Scripting with Python Python help Using Python language Getting input from a user Using modules Creating programs 162009 Introduction I Websitewwwpythonorg I We use Python 26 for Windows operating system Windows XP Windows Vista I Other operating systems that support Python 0 Linux and Unix 0 Macintosh I Other implementations lronPython Windows Jython Java Django 162009 3 1 Installing Python I Download msiinstallation for Python 26 from the link htt www thonor download I Run the downloaded msi file by double clicking on it from windows explorer I Follow the instructions provided by the wizard until you finish the installation I The installation program creates a shortcut on the computer desktop 162009 1 Installing Python Cont 7i Python Shell l l File Edit Sh l Debug Options Windaws Help an Le 12666721 Dc 2 1Ee quotcop ghtquot quotcreamsquot n quotllCEnSEUquot in mite znfcmacmn 2 113 63 1H3 v15m 32 b1 llncelt an wnj Python IDLE cm interface and an data is inn 5 nu v thi a any ax SE11 ID 0 IECEl IE EZUIB l1 l620 09 2 Scripting with Python Generate an output Arithmetic operations Arithmetic operations with integers Arithmetic operations with decimals 1620 09 IDLE 26 gtgtgt print quotHello worldquot Hello world gtgtgt 22 4 gtgtgt 12 0 gtgtgt 102 05 gtgtgt 102 00 gtgtgt 32 1 gtgtgt 302 10 gtgtgt 302 15 gtgtgt 32 1 gtgtgt 3 Python Help Python v26 documentation Welcome This lithe documentationior Python 2 6 last updated Oct 02 2008 Parts oflhe documentation What39s new in Python 26 Changes since previous major release Tutorial start here Using P than V now to use Pytnon on dirterentplattornis Language Reference descnaes syntax and language elements Libraty Reference Extending and Embedding tutorial for 0c programmers PythonC API reference for 0c programmers Installing Python Modules lnfomiatlon for installers amp sysadmin Distributing Python Modules snaring modules iintn otners Keep tnis underyourpilloiv Documenting Python guide for doounientauon autnors Python HOWTOs inadepth documents on Speclflc topics Indices and tables Global Module Index 4 Overview of the Basics of Python Language I Variables I Statements I Functions 162009 41 variables A variable is a holder of a value It has a name which is used to refer to its value A variable name must start with a character not a decimal A variable could be assigned a value 162009 9 41 Variables Cont gtgtgt 12 Notconectvaname SyntaXError can39t assign to literal SyntaxError invalid syntax gtgtgt 1313 gtgtgt bl5 Variable assignment gtgt bl gtgtgt bl3 gtgtgt b1 8 gtgtgt 162009 10 42 Statements It is a legitimate combinations of variables reserved words functions and values that does something Examples 0 Print x o X3 llBQEIEB u 43 Functions A little program you can use to perform a task gtgtgt Xpow23 gtgtgt X Power function gtgtgt Z3 gtgtgt Xpow 2 3 Absolute value gtgtgt Xalos 710 function gt X Round function gtgtgt round 1 02 O 0 mm gtgtgt l 2 5 Getting Input from a User IDLE 26 gtgtgt inputquotH0w old are youquot How old are you30 30 gtgtgt X inputquotEnter X quot Enter X 3 gtgtgt y X 3 gtgtgt y 9 gtgtgt p1nr y 9 gtgtgt inputirawquotte5tquot Traceback most recent call last File quotltpyshell5gtquot line 1 in ltmodu1egt inputirawquottestquot NameError name 39inputiraw is not defined gtgtgt rawiinputquottestquot testTrue 39True39 gtgtgt lie2009 is 6 Using Modules Functions are organized in modules In Python you need to import a module or function before using it Except builtin functions Import a module to the interpreter import module name Call of a function within module module namefunction nameparametersi 182009 Module import Error function call Correct function call 6 Using Modules Cont l82009 gtgtgt iwgrtt math gtgtgt floor329 Traceback most recent call last File quotltpyshell33gtquot line 1 in ltmodnlegt floor329 NameError name floor39 gtgtgt mathfloor329 320 is not defined gtgtgt 13m math mp1t floor gtgtgt floor329 320 gtgtgt sqrt4 Traceback most recent call last File quotltpyshell37gtquot line 1 in ltmodnlegt sqrt4 NameErrol name 39sqrt39 is not defined gtgtgt mathsqrt4 20 Using Programs So far we used the interactive interpreter we write statements and get the results To write a program we need to create a script file To do so from Python IDLE select FilegtNew Windows and write your code The extension for python script file is py You can save your script file see next slides A script module could be executed from the from the IDLE or using a windows command see next slides l82009 71 Create a module mmquot My File Edu She l Debug Options Wmduws Help 5mm FMS OpenMadu em A bM C ass mwser ARC Bath Browser 2 0 5m cms Sim255 Omsmms SaveCcpgAs Amsmms h mm mm cum C 5e 70th t recent call last File quotltpyshell33gtquot line 1 in ltmodulegt floor329 NameError name floor39 is not defined gtgtgt mathfloor329 320 182009 17 72 Save a Module 71 mm SheH M 2m mm Wm Am Ha 8 gtgtgt Xabs 710 gtgtgt X 10 gtgtgt round 1 O 2 O 71 thlrlpyrCTeahmg5pring 2009C8210m50urzeCudekhLpr El 3 wm 1 P CM quotwhat is your namequot 5 name quot quot penMndu e muM 7 0355mm AM ter to endgtquot W a 3 Save Cnpy A mum Pvmngdow QM Ease man Em ma 182009 391 73 Run a module Word Program iinput what is your namequot quothello quot name quot quot iinputquotltenter to endgtquot 162005 Conclusion I The chaptercovered 0 Python installation 0 Scripting 0 Use of modules 0 Creating programs 162005 Chapter39iB Abstraction V Lotfi Ben Othmane Department of Computer Science Western Michigan University 2i02009 i Roadmap Overview Creating Functions Using Parameters Using Function Scope Using Recursion 21 02009 2 1 Overview I Abstraction is a mechanism to hide details ie hide HOW an action is performed A function is an abstraction that you can call When a function is called it performs an action and returns a value gtgtgt m i mat 3 math39 Sqrt 16 We call sqrtwith different parameters gtgtgt ymath sqrt6 and we do not know how it works gtgtgt y 24494997427831779 gtgtgt fibs o 1 f2 1 1 rar e8 fibsappendfibs 72fibs 11 We have to write the code gtgtgt fibs for FibonaCI numbers each 0 1 I 2 3 5 8 13 21 34 time we need It 2102000 39 We know its details a 2 Creating a Function I A function definition is a definition of HOW an action on parameters is performed ie define the steps to perform on parameters I A function definition has the following structure xample of def functionname parameters mm deflmtlon statements block as a set of actions end function 2102000 2 Creating a Function Cont Function definition Function name Function parameter gtgtgt aer f1bsnum result ro1 f 1 1n rangemumez resultappendre3ult e2 result 71 quotT result Return statement gtgtgt fibs10 0 1 1 2 3 5 8 13 21 34 gtgtgt fibsist Calls forthe function fibs 0 391 1 2 3 5 e 13 2102000 2 Creating a Function Cont I Documenting a function Add documentation to the function gtgtgt ef f1bsnum 39e 1e Aula ES thE FleD CCl numb ls f5 arameter mum 1 e numez resultappendresult e2 resu1t 71 7 result gtgtgt fibsidoci 39Calculates the Flbonaccl numbers for parameter num39 gtgtgt maths rtidoci 39sqrtxnnReturn the square root of x Method doc returns the documentation of a function 2102000 2 Creating a Function Cont I Documenting a function gtgtgt helpmathsqrt Help on builtein functlon Sqrt in module math Sqrt Function help returns the Sqrt X documentation of a function Return the Square root of x gtgtgt helpfibs Help on function flbs in module imaini f1bsnum Calculates the Fibonacci numbers for parameter num 2102000 2 Creating a Function Cont I Define a procedure A procedure is a function that does not have a return statement Define a procedure gtgtgt aer helloname print quothello squot name gtgtgt hello39ohn39 hello JO n This function outputs a text gtgtgt x hilloi39bhnquot This function does not return anything n hello Jo gtgtgt x The variable x here IS empty 2102000 3 Using Parameters I Simple parameters overview I Simple exercise I Keyword parameters I Default parameters I Collecting parameters I Parameters practice 2102000 0 31 Simple Parameters Overview I Parameters are arguments for a function They are values supplied when you call a function Variable name is a parameterfor function hello gtgtgt def helloname print quothello quot name gtgtgt hello 39 Johh39 name parameter takes value John hello John in these function calls gtgtgt x hello39Jchn hello John gtgtgt X 2102000 10 31 Simple Parameters Overview Cont Change of an immutable variable inside a function does not change the value of the variable outside the function gt gt def changevariablename 1 The parameter name is changed inside the function gtgtgt name 0 But the value of the variable outside the gtgtgt changevarlable malfunction is the same the value is 0 gtgtgt name 0 gtgtgt name quotJohnquot The parameter name is changed gtgtgt 39 Changevarablelnamel inside the function from John to name 39Tlm39 Tim But the value of the variable outside gtgtgt changevarlable name the function is the same the value is gtgtgt na lJohnl 39John39 H 2102009 31 Simple Parameters Overview Cont I Change of a mutable variable such as list and dictionary inside a function does not change the value of the variable outside the function gtgtgt e 39Jchn3939T1m3939Jie39 I I gtgtgt changevarlable name The parameter name which is a quotCecilquot list is changed inside local the function and also the corresponding gtgtgt changevamablemme variable outside global the gtgtgt name function is changed 39cecll39 39Tim39 Joe39 gtgtgt contactsl Cfohn39 1234 Cecll39 345 The parameterm gtgtgt clef ChangevarlableContacts keyvr which is a dictionary is contactslkeY vr changed inside the function local and also gtgtgt changevarlablecontacts quotCecilquot502 the corresponding gtgtgt contacts variable outside the l39Jo39hn39 1234 39Cecll39 502 function global is 202009 Changed 32 Simple Exercise I Example Dictionary of Names final code in file Ch61py def lookupwata label name Define function lookupto search for return datalabelgetname a ame def initdata data first39 data middle39 data last39 Define function E to initialize the dictionary 2102009 13 32 Simple Exercise Cont def storewata fuanames Define function store to store the names fuanamesplit dictionary if lennames 2 namesinsert1 quot labels 39first39 39middle39 39last39 for label name in ziplabels names people lookupdata label name if people peopleappendfull7name e se datalabelname fulliname 2102009 14 32 Simple Exercise Cont I Example of calls to the functions init store and lookup gtgtgt dicl gtgtgt 1nitdic gtgtgt storedicquotLotf1 Beneommanequot gtgtgt storedicquotMagnus Lie Eetlandquot gtgtgt l39mlddle39 lquot 39Lotfl Beneothmane39i 39Lle39 39Magnus Lie Hetland39 39last39 39Beneothmane39 39Lotfi Beneothmane39 39Hetland39 39Magnu 5 Lie Hetland391 39flrst39 39Magnus39 39Magnus Lie Hetland39 39Lotfi gtgtgt lookupd1c39Iirst3939Lot 139 39Lotfl Beneothmane39 2102000 15 33 Keyword Parameters Simple parameters are positional parameters which depends on the position in the function parameters ist Keyword parameters do not depend on the position but parameters names are specified in the function gtgtgt def hello greeting name r t a 1 7 1n e greeting name gtgtgt helloilWEsi lc39 39wcrl39 39 The parameters values depend on Hello World their positions gtgtgt helloil 39wcrld 391 world Hello gtgtgt helloil name39wcrld39 greeting39iellc 39 H 11 ldl e 0 wor The parameters values do not depend on their positions The parameters values are specified using the parameters keywords 211039 2102000 34 Default Parameters When a function is called all its parameters must be provided unless a default values are specified in the definition of the function Define function with regular gtgtgt de 39 helloilgreeting name parameters print 39ts sl greeting name Define function with default parameters gtgtgt 12f he11072greetingquothellequot namequotWIjquot pri it sl39 greeting name gtgtgt hello 1 Calloffunction hellojwith regular parameters without providing values for the parameters Traceback most eaent call last File quotltpysnelltl4agtquot line 1 in ltmodulegt helloil Ty eError helloil takes exactly 2 arguments a given gtgtgt hello 2 hello W031 Call of function he072Wth default parameters WZ W without providing values for the parameters 34 Default Parameters Cont Call of function helI072without providing all gtgtgt hellcgt72 hello Word values forthe parameters gtgtgt he11072namequotJGhnquot hello39 JOhnl Call of function fie071 without providing all gtgtgt hello 1name uohnquot values for the parameters Traceback most recent call last File quotltpy5helll49gtquot line 1 in ltmodulegt hello 1namequotJohnquot TypeEzrorT helloil takes exactly 2 nonekeywora arguments 0 given gtgtgt helloiz quotElquot quotCamp1lquot Hl39 Cami Call of function helI072with providing all values forthe parameters 2102000 35 Collecting Parameters Collecting Parameters allows the user of the function to supply any number of parameters use a tugle for the parameters gtgtgt je printiparams title params print title Collecting parameters are prefixed with the Print Farms symbol 1 in the definition of the function gtgtgt print param5quotaramsquot2l5l 6 I I params We specified 4 parameters In the function call 2 5 6 including 3 collecting parameters gtgtgt print params quotparams quot Timmy We specified 1 parameter in the function call No collecting parameters gtgtgt printiparams paramsquotquotcs2lQOquotquotSCr1pt programmingquot We specified 3 parameters in the function call Including 2 collecting 2102000 parameters 19 params 39cs210039 39Script pregrammmg39 35 Collecting Parameters Cont I Collecting Parameters allows the user of the function to supply an unknown parameters use a dictionary for the parameters gtgtgt tei39 printiparamstitle params Punt title The call ofthe function print params punt para throw an error as the function does not have foo parameter gtgtgt printiparams quotparams quot fool Traceback most eeent call last File ltpyshelll 7gtquot line 1 in ltmodulegt printiparams quotparams fool TypeEr print paams got an unexpected keyword argument 39foo 2102000 20 35 Collecting Parameters Cont gtgtgt we printiparam572 title paramskeypar Collecting unknown parameters are prefixed print keypar with the symbol 2 in the definition of the function gtgtgt printiparam572 quotpalms quot fool params fOO 1 The call of the function prinfjaram572 39 assigned value 1 to the item with key foo in the dictionary keypar The collection params is empty 2102000 36 Parameters Practice I Use of example of Slide 13 and change method store to support collecting parameters code in file Ch6 1py def storedata fullinames Lname in fullinames names full namesplit if lennames labels 39first39 39 namesinsert1 quot ddle39 39last for label name in ziplabels nam P eople lookupdata label name if people peopleappendfull7name els datalabelname fulliname 2102000 36 Parameters Practice Cont I Use of the Example gtgtgt 3117 Call function store and provide only one name gtgtgt gtgtgt store dic gtgtgt Se eCtnmeuequot all function store and provide only two names i 39middle l 39 39 39Lotfi Beneotma s39 tfi Beneothmane39 l 39Beneothmane39 i ev39 w i 39Luke Skywalker39 Anakin Skywalker39 gtgtgt lookupdic quotf15tquotquotLukequot 39Luke Skywalker39 2102000 23 39Beneothmane39 39Lo 4 Using Function Scope I A scope is the namespace where a variable has a value A scope is an invisible dictionary where variables names and their values are stored function vars returns the scope dictionary The scope includes variable x gtgtgt vars l39ibulltlnsi39 ltmodule 39ibulltini39 bulltelnp 39ipackagei39 None so 1 39inamei imalni39 39idoci39 None gtgtgt y1 gtgtgt vars 0 The scope Includes variable x and y l39ibulltlnsi39 ltmodule 39ibulltlni39 bulltelnp 39ipackagei39 None 39x39 1 39 39 39 name 39 39 mam 39 39idoci39 None 2102009 24 4 Using Function Scope Cont I There is a global scope and each function call has its own scope I Function globals allows the access to global variables from a function gtgtgt def 1ncy gtgtgt inc3 gtgtgt def incx gtgtgt inc 5 The function incremented the local variable 6 and the global variable is not changed gtgtgt x 1 gtgtgt globals The global scope l39ibulltlnsi ltmodule 39ibulltlni39 bulltilngt 397 ackagei39 None 39x39 1 39y39 1 39inamei39 39imalni39 39idoc 39 None 39in c39 ltfunctlon inc at 0x024517FOgt ztuxzuus 25 5 Using Recursion I A recursive function is a function that calls itself Base function definition Recursive function definition def regfactorialn def factorialn 39regular Factorial39 39recursive factorial39 result n if n 1 fori in range1n return 1 result i else return result return n factorialn1 gtgtgt regfactorial 4 A Both functions produce the same result gtgtgt factor1a14 24 21 02000 20 5 Using Recursion Cont Binary Search Binary search implementation using recursive function def searchsequence number lower0 upperNone it upper is None upper lensequence1 39Binary search39 if lower upper assert number sequenceupper return upper else middle lower upper 2 it number gt sequencemiddle return searchsequence number middle1 upper else return searchsequence number lower middle 2102009 27 Conclusion We covered 0 Why we use function and how to create and use it Why we use parameters and the different types of parameters Function Scope Function recursion O 00 2102009 23 Chapter 1 0 Batteries Included Lotfi Ben Othmane Department of Computer Science Western Michigan University 3262009 1 Roadmap I Modules I Packages I Standard Library 3262009 2 1 Modules I Developing Modules I Using Modules I Exploring Modules 3262009 11 Develop Modules I Modules are python programs They could be imported and used in other modules I Usually modules de ne functions and classes I Example of a module containing a function he02py def heo print quotHello worldquot 3262009 11 Develop Modules Cont 71 Python Shell 5 Eiv Eltzll Diruy Upucu tumquot Help Python 26 1C26gt l1 quot a 1 E 7111mm Type quotcopyrightquot Save a module w fl ffffffffffff ef hellol Personal fir print quotHello worldquot 71 Save A v39l interface an csnnu Semen l Name mammal Type IDLE 26 JBERW gtgtgt UBluemolemvsry 3m FtlEnamE 39 amawa Allmem vl News 3262009 12 Using of Modules I Use the method syspathappend to add the location of your modules to the list of folders that Python uses gtgtgt lmpmv sys gtgtgt sys path 39CPython26Libidlelib39 CPython26python26zip39 39C Python26DLLs39 39CPython26lib39 39CPython26libplatiwin 39 39CPython26liblibitk39 39CPython2639 39CPython26lib siteipackage539 39CPython261ibsite7packageswx7287msw7un icode39 gtgtgt syspathappendrquotCTeachingSpring 2009CS2100SourceCodequot gtgtgt syspath 39CPython26Libidlelib39 39CPython26Python26zip39 39C Python26DLL539 CPython26lib39 39CPython26libplat win 39 39CPyth0n26liblib tk39 39CPython2639 39CPython26lib site packages39 39CPythonZ6libsite packageswx 2B msw un icode39 39CTeachingSpring 2009C32100SourceCode391 3262009 12 Using of Modules Cont I To use a module we need to import it then use it gtgtgt 11n 21110701 a5 mymodule gtgtgt mymodulehello Hello world Save a module gtgtgt ma 51111 08414709848078965 3262009 12 Using of Modules Cont I A module may include code to be executed eg call of a function Chmiog39py The module includes 3 def hello3 call to a function print quotHello worldquot hello Such module when imported execute specified code see call to method hello gtgtgt Jm1 cthio Hello world 3262009 12 Using of Modules Cont I Python uses a variable name In an imported module it is set to the name of the module If the module is executed it set to main I The technique could be used to run executable code only when the module is executed and do not run the code when the module is imported cmoiog39py Example of code that def he03 tests it a method print quotHello worldquot should be executed or not not executed if the if nameigimainin helloo module Is Imported 3262009 9 12 Using of Modules Cont I A second method to make a modules available could be imported is to add the folder where the module is located in the environment variable PYTHONPATH I When a module is imported the first time Python compiles the program and generates a file with extension PYC I PYC files are machine independent compiled modules 3262009 1 0 13 Exploring Modules dir function could be used to explore the content of a module all functions and attributes Variable all returns available visible functions invisible functions does not appear with this variable UseodeOfunc on gtgtgt lllt7f copy gtgtgt dircopy 39Error39 39PyStrlngMap39 397EmptyClass39 39ialli39 397 u s7 3947 ocgi39 39Aifllegi39 39Ainamegi39 39Aipackagegi39 397Copy7dlspatch39 397Copyiimmutable39 7Copyiinst39 7Copy7w1th7constructor39 397cop iwlthicopyimethod39 397deepcopy7atomrc39 397deepcopyidlct39 39 deepc opyidlspatch39 397deepcopy71nst 397deepcopyillst39 7deepcopyitupl e39 ikeepiallve39 397reconstruct39 39 test39 39copy39 39deepcopy39 a ispatchitable39 39err r39 a 39t39 gtgtgt COPY 511 Use offallivariable Error 7ccpy7 39deepcopyw zuuy 13 Exploring Modules Cont Help function could be used to get information about the use of a function gtgtgt helpcopycopy Help on functron copy in module copy COPEX Shallow copy cperatren on arbrtrary Python objects See the module39s Aidecgf strlng for more 1nfo I file variable could be used to get the location of the file of a module gtgtgt copy file 39cpython26I bcopypyc39 3262009 13 Exploring Modules Cont I doc variable could be used to get the documentation about a function gtgtgt Copyidoci 39Generic shallow and deep Copying operatronsnn1nterface summa r 1m tort copynn x co yCOp y ma copydeepcopyy make a d recurslve objects compound 0 bjects that directly or indrrectlyn Ontain a reference to t 3262009 2 Packages Modules could be grouped in packages A package is a directory that includes a set of modules It must also include a module with the name initpy 3262009 2 Packages Exploring package email quot mammals We am View Insert For Uvi Pmmzs rm i pen v Ermail mwg Qquopnmime 39 mils package fur parsitgr mat Exploring iinit module for email package handiitgr a triad Bites Lizquot mfg 3262009 13sz gaiizmgneu l5 3 Standard Library I sys module I as module I fileinputmodule I set heaps and deques modules I time module I randommodule I shelvemodule I re module is 3262009 31 sys Module The module gives access to variables and functions related to I Python interpreter I Table below gives an example of variables and functions available in module sys Func onVa abh Desc p on argv The commandline arguments including the script exitarg Exits the current program optionally with a given return value or error message modules A dictionary mapping module names to loaded modwes path A list of directory names where modules can be found platform Contains a platform identifier such as sunos5 or win32 326 009 31 sys Module Example of use of the module gtgtgt mg 2 sys gtgtgt S S h 39CPython26L1b1dle11b39 39CPython2 PythOn26zlp39 39c P ython26DLLs39 39c Python26lib39 39c Pyt On26llb platewm39 39cPychon2611bllbetk39 39CPython2639 39CPython26llbsl teepackages39 39CPython26l1bslteipackageswx72Simswiunlcode gtgtgt sys platform 39w1n3239 gtgtgt sys modules i39heapq39 ltmodule 39heapq39 from 39CPython26llbheapqpyc39gt 39tk 1 eDlalog39 ltmodule 39thlleDlalog39 from 39CPythonZ6liblibrtkthil eDlalogp c39gt 39functools39 ltmodule 39functools39 from 39CPython26l yc39gt 39random39 ltmodule 39random39 from 39CPython26ll 7 t39 ltmodule 397blsect39 bullteingt 391dlellb ltmodule 391dlellbmacosxsupport from 39CPython26l 1b1dlell m 39gt 39 n Awn n a1quot 39 None 391dlel 3262009 iB 32 03 Module I Gives access to several operating system services I Table below gives an example of variables and functions available in module os FunctionVariable Description environ Mapping with environment variables systemcommand Executes an OS command in a subshell sep Separator used in paths linesep Line separator 39n39 39r39 or 39rn39 urandomn Returns n bytes of cryptographically strong random data 3262009 32 as ModuleCont I Example of use of the module Variable ariab gt MVJKOS PCBRAND gt osenv1ron M 39TMP39 39CUsershpAppDataLoCalTemp39 39PCBRAND39 39PRESARI o39 39COMPUTERNAME39 39LOTFIeLAPTOP39 39USERDOMAIN39 39LOTFIeLAPTOP39 39VSSOCOM NTOOLS 39c Program F11esM1crosoft Vlsual Studlo 90 Common7Tools39 39COM MONPROGRAMFILES39 39CProgram F11esCommo 139 Files39 39PROCESSORilDENTIFIER 39x86 Family 5 Model 15 Stepplng 13 Genuinelntel39 39PROGRAMFILES39 39CProgram Flles39 39PROCESSOR REVISION39 39Ofod39 39HOME 39CUsershp39 39PATH39 39CW1ndows Ysystem32 c W1ndowsC WindowsSystem32Wbem c Program File sComInOn File5ROx1o sharedDLLsharedcProgram FllesCOmm 3262009 32 05 ModuleCont I Example of use of the module Qt GooglErMazillaFivelux El was Elle gm view Haw nnkmavks mi Help l km wwwgaaglemm 1 a WWW o agntngsma Dimming 5 hawWWW Web images Mags News Videu Gmail murev iGuuglElSi nin Command to start Firefox from python l Gnugle Search l mFeelmg Lucky l Tuberculusis is a glubal West Get tested and treated Advertising Pragramc a lutmnc Abaut Gnaglc v 3262009 33 fileinput Module I Provides variable and functions that enables iterating over the lines of a teXt file I Table below gives an example of variables and functions available in module fileinput FunctionVariable Description inputfiles inplace Facilitates iteration over lines in multiple input back UP streams filenameO Returns name of current file lineno Returns current cumulative line number filelinenoO Returns line number within current file cl ose Closes the sequence ze2ooe 33 fieinput Module Cont I Example of use of the module numberlinespy import fileinput for line in fileinputinputquotch1004pyquotinplaceTrue line inerstrip0 rstipr method eliminates all the white num leinput nenoo spaces at the right of the line print 39 40s 2i39 line num Replace the line with new line that includes the number of the line 3262009 23 33 fieinput Module Cont I Result of the running module ch1004py numberlinespy 1 import fileinput for line in fileinputinputquotch1004pyquotinplaceTrue 3 line inerstrip 4 num fileinputlineno 5 print 39 40s 2i39 line num 6 3262009 24 34 set heaps and deques Modules Python integrate some data structures such as dictionary lists and string It includes some modules for author data structure such as sets heaps and deques Sets constructed from sequence and their main use is to check membership Heap kind of priority queue Let add objects in arbitrary order It does some operations with efficiency Deqeue double ended queue Useful when you need to remove element in the order they were add 3262009 34 set heaps and deques Modules Cont I Example of use of the s 4 6 gtgtgt setrange10 2 3 Fe 39 gtgtgt aset fee 39f1 39 gtgtgt bsetrange10 gtgtgt a set39foe39 39fee39 39fle39 set0 1 2 39fee39 4 5 e 7 a 9 39foe39 3 39fle39 39foe39 3 39fle39 set39foe39 39fee39 39fle39 gtgtgt c1ssubseta 62009 gtgtgt a1ssubset c Tru 34 set Cont heaps and deques Modules Set of methods for heap operations FunctionNariable Description heappushheap x Pushes x onto the heap heappopheap Pops off the smallest element in the heap heapifyheap Enforces the heap property on an arbitrary list heapreplaceheapx Pops off the smallest element and pushes x nlargestn iter Returns the n largest elements of iter nsmallestn iter Returns the n smallest elements of iter 3262009 34 set heaps and deques Modules Cont 3262009 gtgtgt 13m heapq lKJZLi gtgtgt heapn gtgtgt dataranqe10 gtgtgt f1 11 1139 da ta Use of heap module heappushheapn gtgtgt heap I I 6I 7I heappushheap om heap 05 1 5 6 heappu5hheap 45 heap I 05 I I 1I gtgtgt heappopheap 0 vv vv ovvovv vv vv 1 as u as gtgtgt heappopheap 05 gtgtgt heap 1 3 2 5 4 45 6 7 a 9 gtgtgt heaprep1aceheap1m 1 gtgtgt heap 2 3 45 5 4 10 e 7 a 9 N 34 set heaps and deques Modules Cont Use of deque module gtgtgt Erin collections 13t deque gtgtgt q dequerange5 gtgt q39append5 Add an item to the deque deque0 1 2 3 4 5 gtgtgt qappendleft7 gtgtgt q Add an Item at the left of the deque deque7 o 1 2 3 4 5 gtgtgt qpopll remove item from the right ofthe deque 5 gtgtgt q deque7 0 1 2 3 4 gtgtgt qpopleft 7 gtgtgt q deque0 1 2 3 4 239 mate 1 Move one element from the right to dequel 2 3 4 0 the leftofthedeque 3262009 29 35 time Module Time module contains function for among other things getting the current time manipulating times and dates and formatting dates ln Python a date could be represented as real value or a tuple of nine integers year month day hour minute second weekday Julian day daylight savings Example of the use of dates as tuple 2008121122560210 is Monday January 21 2008 at 120256 3262009 30 35 time Module Cont I Example of the use of the module tlme m1 1me 12379218275840001 gtgtgt asctimeu 39Tue Mar 24 151032 200939 gtgtgt localtime timeStructitimetmiyear2009 tmimon3 tmimday24 tmihour15 t mimln10 tmisec36 tmiwdayl tmiyday83 tmilsdstl gtgtgt gmtime timestruct timetmiyear2009 tmimon3 tmimday24 tmihour19 t miminlO tmisec40 tmiwdayl tmiyday83 tmilsdst0 size2009 36 random Module I Random module contains functions that return random numbers which can be useful for simulations for example FunctionVariable Description random Returns a random real number n such that O S 7 lt1 uniforma b Returns a random real number n such that a S n lt b randrangestart stop Returns a random numberfrom rangestart step stopstep choiceseq Returns a random element from the sequence seq shuffleseq random Shuffles the sequence seq in place sampleseq n Chooses n random unique elements from the sequence seq 36 random Module Cont Example of the use of module random to generate a random date ch102py 3202009 from random import from time import date1 2008 121 0 0 0 1 1 0 time1 mktimedate1 date2 2009 1 11 0 0 0 1 1 0 time2 mktimedate2 randomtime uniformtime1time2 asctimelocaltimerandomtime 36 random Module Cont I Example of the use of module random to generate a random numbers ch103py 3202009 from random import randrange num input How many dice 39 sides input How many sides per die 39 sum 0 for i in rangenum sum randrangesides 1 print 39The result is39 sum How many dice 6 Output of ch103py How many Sides per die a The result 15 36 random Module Cont fm random 1mt gtgtgt random 096747330470186743 gtgtgt random get random number 019148364426079978 gtgtgt st2 58 9 gtgtgt choicest i choice 5t Select randomly an item from the list st 9 gtgtgt choice st gtgtgt samplest2 939 5 Select randomly 2 items from the list st gtgtgt samplest2 2 3 3262009 37 shelve Module It offers a simplified module to manage data storage gtgtgt s close 3262009 37 shelve Module Cont I Simple database application using shelve ch104py import sys shelve def store jersondb Query user for data and store it in the shelf object pid rawiinput39Enter unique ID number 39 person person39name39 rawiinput39Enter name 39 person39age39 rawiinput39Enter a e 39 person39phone39 rawiinput39Enter phone number 39 dbpid person 3262009 37 37 shelve Module Cont def IookupJaersondb QIfJery user for ID and desired field and fetch the corresponding data rom the shelf object pid rawiinput39Enter ID number 39 rawiinput39What would you like to know name age phone 39 field fieldstriplower print fieldcapitalize 3939 dbpidfield i 0 def printihelpO print 39The available commands are39 print 39store Stores information about a person print 39Iookup L00 5 up a person from ID number39 print 39quit Save changes and exit39 print 39 Prints this message 3262009 as 37 shelve Module Cont def entericommando cmd rawiinput39Enter command for help 39 cmd cmdstripower return cm def main database shelveopen39databasedat39 lvhile True cmd entericommando if cmd 39store39 storeipersondatabase elifcmd39oo 39 ookup7persondatabase elif d 0 u finally 3262009 databaseclose 37 shelve Module Cont Enter Command for help The avallable commands are ion about a person store stores informat lookup Looks up a person from ID number it Save Changes and exlt v P ts this messa Store Ente name Lotfi ben Othmane 23 Example of the use of Ch1074py Enter phone number 456345 Enter Command for help store 65 er Enter age Enter phone number E ter Command for help iookup D what would you like ame Lotfi ben oth e Command 2 for help exit er Command for help quit to know name age phone name mane nt 3262009 Ent 0 20 38 re Module I A regular expression is a pattern that can match piece of text I Example of regular expression operators 0 pattern pattern may exist 0 pattern pattern is replaced 0 or more times 0 patternpattern is repeated one or more times I Example or regular expression 0 r httpwwwpythonorg 0 Strings that are valid with respect to the above regular expressionquot httpwwwpythonorg pythonorg wwwpythonorg httppythonorg 3262009 Al 38 re Module Cont FunctionVariable Description compilepattern Creates a pattern object from a string with a regexp flags searchpattern stringL Searches for pattern in string flags matchpattern stringL Matches pattern at the beginning of string flags splitpattern string Splits a string by occurrences of pattern maxsplit0 findapattern string Returns a list of all occurrences of pattern in string 3262009 42 21 38 re Module Cont FunctionVariable Description subpat repl stringL Substitutes occurrences of pat in string with repl count0 escapestring Escapes all special regexp characters in string Splits a text using pattern as separator Splitpat stringmaxsplit 3262009 38 re Module Cont Use of compile function http www python yt ab 5 39 y 39 orgquot gtgtgt re 1 gtgtgt pat compile39 gtgtgt a searchpatquot gtgtgt a ltfsreSRE7Match object at 0X02496020gt gtgt group Search function searches for the occurrence of vmrwpyihonorg the matchpatquotpyihon web site 15 wwwpylhonorg httppytho web site 15 wwwpylh rg 15 pyt gtgtgt nj gtgtgt a ltfsre SRE7Match object at 0x02496068gt gtgtgt agroup httppythonorgv match function searches forthe occurrence of the pattern at the beginning of the text a amatchpatquothttpPython K v 3262009 22 38 re Module Cont Example code available in file CH105py gtgtgt Someitext39alpha betagamma delta39 gtgtgt splitl39 39 someitext Splitthe text using pattern 3951 ha39 39 beta39 39gamma delta39 as separator gtgtgt split39 39 someitext maxsplit2 alpha39 39 beta39 gamma delta39 gtgtgt split39 39 someitext maxsplitl 39alpha39 39 betagamma delta 1 Regular expression for any sequence gtgtgt pat39 aeerz 39 of characters and digits gtgtgt text39quotimEIr W are you surequot he said sounding insecure 39 Find all occurrence of the pattern gtgtgt findallpattext rr39 39are39 39Hm39 39E 39you39 39sure39 39he39 39said39 39soundlng39 in secure39 gtgtgt p Fr y v Regularexpression for a sequence of gtgtgt findall pattext the characters quot7 i il Find all occurrence of the pattern 3262009 45 38 re Module Cont Methods for the Match object FunctionVariable Description groupgroup1 Retrieves the occurrences of the given subpatterns groups startgroup Returns the starting position of the occurrence of a given group endgroup Returns the ending position an exclusive limit as in slices of the occurrence of a given group spangroup Returns both the beginning and ending positions of a group 3262009 46 23 38 re Module Cont gtgtgt pat inamei 39 Use of substitute function gtgtgt text 39Dear namet39 gtgtgt subpat 39 Gumby39 text 39Dear Mr Gumby gtgtgt emphasisipattern r39 39 gtgtgt pat CompileemphasisipatternVEREOSE gtgtgt pat isreSRE7Pattern object at 0x0248F500gt gtgtgt subemphasisipattern r39ltemgtllt3mgt39 39Hello ltemgtworldltemgti39 gtgtgt subemphasisipattern L gtlltemgt39 39Thls l5 nt 39 39ltemgtThlsltemgt 15 ltemgtitltemgti39 3262009 47 38 re Module Cont gtgtgt escape39mw 39thonorg39 wwwpythonorg39 gtgtgt escape39But where 15 the amblgulty39 39But where lS the amblgultY Use of escape function gtgtgt m matcmr39mm ini3i39 39mmpythc p gtgtgt mgroupili Use of group function t On39 0 14 gtgtgt mstartl 4 gtgtgt mstart0 gtgtgt mendl 10 gtgtgt mend0 14 3262009 AB 38 re Module Cont 3262009 This code is in file CH106py findisenderpy import fileinput re pat recompiler39From ltgt39 try fopen r39CTeachingSpring 2009 82100SourceCodeemailemltxt3939r39 linefreadline while line print line m rematchpatline if m print mgroup0 linefreadline except Exception e print 39Error 39 e finally fclose Code to parse the email in the next slide and return the sender of the email 38 re Module Cont Email to be parsed 3262009 From foobarbaz Thu Dec 20 012250 2004 ReturnPath ltfoobarbazgt Received from xyzzy42barcom xyzzybarbaz 12345678942 by frozzbozzfloop 893893 with ESMTP id BAA25436 for ltmagnusbozzfloopgt Thu 20 Dec 2004 012250 0100 MET Received from 4325312423 by barbaz lnterMail VM4010327 20122912112720010626 with ESMTP H 1 Thu 20 Dec 2004 002242 0000 UserAgent MicrosoftOutlookExpressMacintoshEdition5022022 Date Wed 19 Dec 2004 172242 0700 Subject Re From Foo Fie ltfoobarbazgt To Magnus Lie Hetland ltmagnusbozzfloopgt CC lt r umbybarbazgt MessageID ltBS467D6284Ffoobazcomgt lnReplyTo lt20041219013308A2655bozzfloopgt Mimevers39on 10 Contenttype textplain charsetquotUSASCIquot Contenttransferencoding 7bit Status RO ContentLength 55 L So long and thanks for all the spam Yours 25 38 re Module Cont 3262009 This code is in file CH107py importfileinput re pat recompiler39a zaz39 relGNORECASE addresses set fopenr39CTeachingSpring 2009 082100SourceCodeemaileml3939r39 i0 while True line freadline Code to parse the email in the if not line break previous slide and return the list of email address for address in patfindallline addressesaddaddress for address in sortedaddresses print address 38 re Module Cont From List of email address generated using Ch1076py Foo Fle ltfoobar bazgt Mr 39 6 bybar39baz List of email address generated using fooQbarbaz foobaz co Ch1077Py m magnusebozz floop 3262009 26 Conclusion I We covered in this chapter 0 O 0 3262009 Modules A python program Packages Directory that includes a set of modules Stadard Library sys module as module fileinput module set heaps and deques modules time module random module shelve module re module 27


Buy Material

Are you sure you want to buy this material for

25 Karma

Buy Material

BOOM! Enjoy Your Free Notes!

We've added these Notes to your profile, click here to view them now.


You're already Subscribed!

Looks like you've already subscribed to StudySoup, you won't need to purchase another subscription to get this material. To access this material simply click 'View Full Document'

Why people love StudySoup

Steve Martinelli UC Los Angeles

"There's no way I would have passed my Organic Chemistry class this semester without the notes and study guides I got from StudySoup."

Jennifer McGill UCSF Med School

"Selling my MCAT study guides and notes has been a great source of side revenue while I'm in school. Some months I'm making over $500! Plus, it makes me happy knowing that I'm helping future med students with their MCAT."

Jim McGreen Ohio University

"Knowing I can count on the Elite Notetaker in my class allows me to focus on what the professor is saying instead of just scribbling notes the whole time and falling behind."


"Their 'Elite Notetakers' are making over $1,200/month in sales by creating high quality content that helps their classmates in a time of need."

Become an Elite Notetaker and start selling your notes online!

Refund Policy


All subscriptions to StudySoup are paid in full at the time of subscribing. To change your credit card information or to cancel your subscription, go to "Edit Settings". All credit card information will be available there. If you should decide to cancel your subscription, it will continue to be valid until the next payment period, as all payments for the current period were made in advance. For special circumstances, please email


StudySoup has more than 1 million course-specific study resources to help students study smarter. If you’re having trouble finding what you’re looking for, our customer support team can help you find what you need! Feel free to contact them here:

Recurring Subscriptions: If you have canceled your recurring subscription on the day of renewal and have not downloaded any documents, you may request a refund by submitting an email to

Satisfaction Guarantee: If you’re not satisfied with your subscription, you can contact us for further help. Contact must be made within 3 business days of your subscription purchase and your refund request will be subject for review.

Please Note: Refunds can never be provided more than 30 days after the initial purchase date regardless of your activity on the site.