ࡱ> z|y "bjbjcTcT 06>>E00sssss8$,!%%%V!X!X!X!X!X!X!#O&VX!sX!ss%%m!Ps%s%V!V!:r , %jP B!!0! R&H& &s HX!X!!&0 9: Python Exercises May 5, 2010 The following exercises were written by John Reiser in May 2008 and updated in April 2010. Exercise #1 Manipulating Strings Lets play with some string methods. Open IDLE. Create a new string object by typing in the following at the interactive prompt. >>> string = "This is my string of text." The string method .upper() returns your string of text in all-caps. >>> string.upper() 'THIS IS MY STRING OF TEXT.' The method modifies the returned value of the text, but not the actual text in the object itself. Type the objects name (in this case, string) into the Python Shell to see that the object was not changed. >>> string 'This is my string of text.' If we wanted to reassign string to have the modified value, we would need to reassign the object the new value. Lets use another string method, .title() to change string to title case. >>> string = string.title() >>> string 'This Is My String Of Text.' In addition to modifying the contents of a string object, string methods can provide information about the string. The .isupper() method returns a value of True or False depending on whether or not the string is composed entirely of upper case letters. >>> string.isupper() False >>> string = string.upper() >>> string.isupper() True The len(object) function will return the length of the object passed to it as an argument. For strings, len() will return the number of characters in the string. >>> len(string) 26 Exercise #2 Manipulating Lists Lets start with an empty list. Create an empty list in IDLE. The len() function can be used on lists as well as strings. >>> list = [] >>> len(list) 0 Lets now try and add some items to the list. >>> list[0] = 'my item Traceback (most recent call last): File "", line 1, in list[0] = 'my item' IndexError: list assignment index out of range Python will not allow us to add an item by setting a value to a new index. We need to explicitly append a new item to the end of the list. >>> list.append('my item') >>> list[0] 'my item' Once the space in the list has been added, we can modify what is in that space. >>> list[0] ='something else' >>> list[0] 'something else' Lets add another item. >>> list.append("item 2") >>> list ['something else', 'item 2'] Lets add an item at a specific location. To insert a new value in the second space, well use the insert function. >>> list.insert(1, 'inserted item') >>> list ['something else', 'inserted item', 'item 2'] Remember, Python (and most programming languages) uses 0 as the start of the list, so second place would be index value 1. Python allows us to quickly find if a value exists within the list. We can use in to determine if something is in a list or not. Once we know it exists, we can determine the index number of the item, using the index function. Requesting an index for an item that does not exist in the list causes a hard error, which is Pythons way of forcing you to keep tabs on your data. >>> list.index('item 2') 2 >>> list.index('foo') Traceback (most recent call last): File "", line 1, in list.index('foo') ValueError: list.index(x): x not in list Exercise #3 For Loops and Conditional Branching For this exercise, we should move from the Python Shell window and into a python .py file that we will have IDLE run for us. Create a new window from the File menu, and save it as C:\student\loop.py We will create a list, iterate over the items within and check each for a certain value. If the item has a matching value, well print one message to the output and print a different message if the item does not match. The len() function can be used to determine the length of a string (or list); we will use it to find the length of each item in our list. list = ['apple', 'banana', 'orange', 'grape', 'tangerine', 'kiwi'] for item in list: if len(item) > 5: print item, "is 6 characters or more!" else: print item, "is only", len(item), "long!" Note that IDLE will indent the next line for you when it sees that you end a line with a colon. The indentation is nested; the if and else blocks are double indented as they are part of the for loop. Pythons print command is used to explicitly print a line of text to the output. You can print multiple strings as one line by separating the strings with commas. Lets change the loop to check for two specific fruits, apple and grape, and print a generic message for all other values. for item in list: if item == apple: print Apples are great! elif item == orange: print Oranges are another great fruit. else: print item.title(), ? I dont care for them. Exercise #4 Manipulating Files and Directories using the os Module You will create a Python script that will search a predetermined directory and list the items within, separating the files and directories into two lists that will be printed to the screen. Save this script as C:\student\listing.py Load the os module. Youll need to acquaint yourself with a few of the functions the os module provides. The os.path.join(directory, file) function returns a string that properly joins the directory with the filename to create a complete path. This is necessary because the path separator is different on different operating systems (\ on Windows, / on Mac, Linux, etc.) The os.listdir() function takes one argument, a directory on the hard disk, and returns a list of files that reside in the directory. os.path.isfile(file) tests to see if the file passed to it is actually a file. If the file either does not exist or is a directory, os.path.isfile() returns False. Using what you learned in the previous examples, create a for loop that will iterate over the directory contents list created by os.listdir() and print only the items in the directory that are files. Use C:\Students as the directory for os.listdir(). Exercise #5 Rock Paper Scissors You will create a Python script to play Rock, Paper, Scissors against. The simple script will randomly return one of the following results when run; Rock, Paper or Scissors. You will need to import the random module to generate the random choice. After importing the random module, you will use the randint function to return a value between 0 and 2. random.randint(0, 2) Before you start writing, consider: How will you store the Rock, Paper, and Scissor values to print? How will you use the results from random.randint(0, 2) to determine which value to print? Why do you think your random range should be between 0 and 2? What is the significance of starting at 0?     Python Exercises, May 2010 Page  PAGE 1 x  E F Y a  H P s / 9       b o t ԴԭŢԢԴԴuԃn hBD h:hlh:6CJOJQJhlh:CJOJQJhlh:OJQJ hQ]h:hyZh:OJQJ hyZh:h)zh:CJOJQJh: hEoh:hmOJQJh:OJQJhEoh:5OJQJhWhWOJQJhWh:5OJQJ'x F G s    gd:gd: $gd: $Wdetv  QR _h6?wy(jqQV>ȽȽȲ|u h&dh:hh5OJQJhOJQJht h:5OJQJ h(h:h!LOJQJ h)h:h_qh:OJQJh@9h:OJQJh: h@9h:hah:CJOJQJh:OJQJhBD h:5CJOJQJh:5OJQJ. Wesuv "QR_}hgd:gd:hA9Oxyr,>gncgd:`gd:gd:>Mn!%Y\lqBCDFfpz|mn˽표휇h:CJOJQJh^h:OJQJh)zh:CJOJQJh)h)5OJQJh)OJQJht h:5CJOJQJht h:5OJQJh:5OJQJht h:CJOJQJh:OJQJ h&dh:h:0 BCqn0 !l!!! & Fgd:gd: & Fgd:`gd:gd: 039l u !!!!!!!!!!"" """"""""ɺh*v0JmHnHujh:0JU h:0Jh:hjhUh{Qh:OJQJ h)zh:h:OJQJh: h:OJQJht h:5OJQJhQ]h:OJQJh:CJOJQJhph:OJQJ!!!!!!!!!!!!!!""""""""" & Fgd:gd:.:p:/ =!"#$% j 666666666vvvvvvvvv66666>666666666666666666666666666666666666666666666666hH6666666666666666666666666666666666666666666666666666666666666666666866666662 0@P`p2( 0@P`p 0@P`p 0@P`p 0@P`p 0@P`p(8HX`~ OJPJQJ_HmH nH sH tH D`D [NormalCJ_HaJmH sH tH DA`D Default Paragraph FontRiR Table Normal4 l4a (k ( No List T@T {Q Colorful List - Accent 1 ^m$8O8 @9Code m$ CJOJQJ8@8 Eo0Header!6!6 Eo0 Header CharCJaJ8 @28 EoFooter!6A6 Eo Footer CharCJaJ.)@Q. #l Page NumberPK![Content_Types].xmlj0Eжr(΢Iw},-j4 wP-t#b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%M07%<ҍPK! ѐ'theme/theme/_rels/themeManager.xml.relsM 0wooӺ&݈Э5 6?$Q ,.aic21h:qm@RN;d`o7gK(M&$R(.1r'JЊT8V"AȻHu}|$b{P8g/]QAsم(#L[PK-![Content_Types].xmlPK-!֧6 +_rels/.relsPK-!kytheme/theme/themeManager.xmlPK-!Ptheme/theme/theme1.xmlPK-! ѐ' theme/theme/_rels/themeManager.xml.relsPK] 6 @BDG >" h!"3:<G!8@0(  B S  ?07 or"il",l w = G I L O Y [ e QT/2#z|n| cj4B &Z`IOw}wy os#[_imchl x = H QU,.@Ehlpu n} em4C33333333333333333333333333333333333333333333333333333333x 6 < ? ? ( q Fp&5HJ,K{-gV:X ^`OJQJo( ^`OJQJo(o p^p`OJQJo( @ ^@ `OJQJo( ^`OJQJo(o ^`OJQJo( ^`OJQJo( ^`OJQJo(o P^P`OJQJo( ^`OJQJo( ^`OJQJo(o p^p`OJQJo( @ ^@ `OJQJo( ^`OJQJo(o ^`OJQJo( ^`OJQJo( ^`OJQJo(o P^P`OJQJo(&5K{-g                    : g;tK,b)m!LW*vkj@p@UnknownG* Times New Roman5Symbol3. * ArialMMonacoCourier New7K@Cambria?= * Courier New;WingdingsA BCambria Math 1h(%Fw%F  . .4J#H?'[P 2 John Reiser John Reiser  Oh+'0T   , 8 D P\dlt| John Reiser Normal.dotm John Reiser12Microsoft Office Word@@r_@pV)Y@/G~VT$m- X?&" WMFCbp L9LYlVT$m EMFLYreU"   % %  Rp@CambriadH"P`20O`2 yu.1 u.17X$7K@Cambrib'.1TX6'100y%1Xdv% % %  TTX,U@@XLP j;!"  TX&U@@XLPython Exercises, May 201092"758:01),+1+R127788TT_ &U@@LP ([TT` N&U@@` LP dTlO0&U@@OLXPage 9111TT1g&U@@1LP1e7TTh&U@@hLP n;!"  TTX'U@@XLP g;!"  Rp@Times New Romand H"P`2 0O`2 yu.1 u.17XG* Times ew Roman6'100y%1X dv% % % TXY2U@@XLlPython Exercises<2!828C2,-,',(TT3YU@@3LP tZ TYU@@ LdMay 5, 2010.^2222222TTYU@@LP n6!"  Rp@Times New Romand H"P`2 0O`2 yu.1 !u.17XG* Times ew Roman6'100y%1X!dv% % % ThXU@@XyZLThe following exercises were written by John Reiser in May 2008 and updated in April 2010.=2,!22H21,3,!,','H,!,H!,240(222C,',!2Y.02222,22223,,22H2!2222TT#U@@yLP - % % % TXUWU@@XB LdExercise #1 C2,,,',22TTUWU@@VBLP 2TTWU@@BLP T3WU@@BLtManipulating Strings^28882!828!,82&TT4iWU@@4BLP e6 % % % T,X:U@@X%LLet s play with some string methods. p<,!'2.0H2'2N,'!21N,222'T;B U@@; LdOpen IDLE. H3,2 I<=TC  U@@C L|Create a new string obj C!,,,,3,H'!3122T` VU@@ LTectt-,TTWoU@@WLP eTpU@@pLpby typing in the g30023122, T$XU@@Xy$Lfollowing at the interactive prompt.!22H21,2,2-!,,2,2!2N2TTU@@yLP - Rp@1Courier NewdH"P`20O`2 yu.1 "u.17X?=* Courie NewTX6'100y%1X"dv% % % TDXY AU@@X+)L>>> string = "This is my string of text."a22222222222222222222222222222222222222222TTZ  AU@@Z +LP )2 Rp@Times New Romand H"P`2 0O`2 yu.1 #u.17XG* Times ew Roman6'100y%1X#dv% % % TTXD|U@@XLP \% % % % TXLU@@XLpThe string method =2,'!21N,222% % % T|MU@@ML\.upper()22223222% % % TTU@@LP aT U@@"Lreturns your string of text in all!,2!2'022!'!312",32,TT  U@@ LP-'!Tl  U@@ LXcaps. ,,2'TT  U@@ LP t- % % &" WMFC LLY% TXrwU@@XLl>>> string.upper2222222222222222TXxrU@@xLP()22TTr U@@LP e2 TX(U@@XL'THIS IS MY STRING OF TEXT.'2222222222222222222222222222TT(U@@LP a2 TTX/U@@XpLP e2 % % % TXU@@XaLThe method modifies the returned value of the text, but not the actual text in the object itself.l=2,N,222N22!,'2-!,2!2,23,2,2!2,,322222,,,2,,322,22,,',!TTU@@LP  TXk U@@XT eLType the object s name (in this case,  string ) into the Python Shell to see that the object was not e>02,3,22,,!'3,N,!22',,',!'!31!!222,9022282,2',,2,2,22,,H,'22 T|Xn  U@@X L\changed.,2,31,2TTn  U@@ LP s- % % % TX: K U@@X{ L`>>> string2222222222TTL: } U@@L{ LP s2 TdX  U@@X LT'Thi2222T   U@@  L|s is my string of text.'222222222222222222222222TT  U@@ LP h2 TTX N U@@X8 LP 2 % % % TtXO  U@@X \LIf we wanted to reassign  string to have the modified value, we would need to reassign the "H,I,2,22!-,''12!'!21!23,2,2,N22",22,2,H,H2222,,32!,,''122, % % % TX 7 U@@X 7Lobject the new value. Let s use another string method, w22,,2,2,H3,2,<,!'2',,222,!'!31N,222% % % T| v 6 U@@ L\.title()22222222% % % TTw 7 U@@w LP T J7 U@@ !Lto change  string to title case.s2,2,31-!'!21!2,-,',TTK w7 U@@K LP i- % % % TX  U@@X L>>> string = string.title()o222222222222222222222222222TT  U@@ LP 2 TX KG U@@X1 L`>>> string2222222222TTL }G U@@L1 LP 2 % % % TTXN  U@@X LP'2TN  U@@ LThis Is My String Of Text.'222222222222222222222222222% % % TTE  U@@ LP 2% % % % TTX U@@XLP IK TX\U@@XtaLIn addition to modifying the contents of a string object, string methods can provide information I 2,22222N22"0312,,22,2'2!,'!3132,,'!21N,222'-,32!222,2!2!N,22 % % % TXU@@XLxabout the string. The ,2222,'!21=3,% % % TU@@ L`.isupper()2232222222% % % TTU@@LP lTU@@=Lmethod returns a value of True or False depending on whether 3N,222!,2!2',2,2,2!>!2,2!7,',2,2,223122H2,2-! T$XuU@@X^$Lor not the string is composed entire2!222,'!21', &nWMFCLLY2N32',2,2!,T} uU@@^Lly of upper case letters.02!222-!--',,,!'TT~  uU@@~ ^LP - % % % TX?'U@@XLt>>> string.isupper()22222222222222222222TT@q'U@@@LP 2 TlX.QU@@XoLXFalse22222TTR.U@@RoLP 2 TXU@@XL>>> string = string.upper()222222222222222222222222222TTU@@LP 2 TX?BU@@X,Lt>>> string.isupper()22222222222222222222TT@qBU@@@,LP 2 TdXIU@@XLTTrue2222TT IQU@@ LP 2 TTXU@@XLP 2 % % % TdX uU@@X^LTThe =2,% % % Td tU@@ ^LTlen(2222Rp@1Courier NewdH"P`20O`2 yu.1 $u.17X?=* Courie Newg26'100y%1X$dv% % % TpsU@@^LXobject222222% % % TT1tU@@^LP)2% % % TT2JuU@@2^LP TKuU@@K^KLfunction will return the length of the object passed to it as an argument. !22,22H!,2!22,,3122!2,22,,2,'',22,',2,"12O,2Td/uU@@^LTFor 72! % % % TXzU@@X L`strings, '!21'% % % TlU@@LXlen()22222% % % TTzU@@LP T0zw U@@&Lwill return the number of characters iH!,2!32,22N2,!2!,3,!-,,!(Tx zR U@@x  Lhn the string.22,'!21TTS z U@@S LP - % % % TXFEU@@XLl>>> len(string)222222222222222TTFFwU@@FLP 2 % % % TXXU@@XLP2622% % 666666666666666666666666666666666666 6 66 6  6 66 6  6 66 6  6 66 6  6 66 6 66666666666666666666  -."System--@Cambria---  2 ?`- u ,-'22 `-Python Exercises, May 2010      2 - u` 2 - u2 q-Page t  2 -1u 2 - u ,-' 2 `- u ,-'@Times New Roman---#2 o`-Python Exercises     2 o- u2 o{ -May 5, 2010 2 o- u,-'@Times New Roman---2 `Z-The following exercises were written by John Reiser in May 2008 and updated in April 2010.        2 - u---2 ` -Exercise #1  2 -u 2 - u)2 -Manipulating Strings      2 O- u---C2 `%-Lets play with some string methods. i    2 P -Open IDLE.  .2 -Create a new string obj    2 7-ect 2 I- u%2 M-by typing in the n A2 `$-following at the interactive prompt.   2 B- u@1Courier New---I2 `)->>> string = "This is my string of text." 2 - u@Times New Roman--- 2 `- u---&2 `-The string method  ---2 -.upper()--- 2 - u>2 "-returns your string of text in all 2 --u2 -caps.r 2  - u---#2 ;`->>> string.upper2 ;-() 2 ;- u52 J`-'THIS IS MY STRING OF TEXT.' 2 J?- u 2 Y`- u---2 k`a-The method modifies the returned value of the text, but not the actual text in the object itself.    2 k- u2 ~`e-Type the objects name (in this case, string) into the Python Shell to see that the object was not     2 `-changed. 2 - u---2 ` ->>> string 2 - u2 `-'Thi/2 -s is my string of text.' 2 ?- u 2 `- u---2 `\-If we wanted to reassign string to have the modified value, we would need to reassign the      ---^2 `7-object the new value. Lets use another string method,     ---2 -.title()--- 2 - u=2 !-to change string to title case. 2 - u---42 `->>> string = string.title()' 2 7- u2 ` ->>> string 2 - u--- 2 +`-'u42 +h-This Is My String Of Text.''--- 2 +?- u--- 2 =`- u 2 P`a-In addition to modifying the contents of a string object, string methods can provide information n   ---,2 c`-about the string. The  ---2 c -.isupper() --- 2 c7- ug2 c;=-method returns a value of True or False depending on whether    A2 u`$-or not the string is composed entire 12 uA-ly of upper case letters.. 2 u- u---)2 `->>> string.isupper() 2 - u2 `-Falsee 2 - u42 `->>> string = string.upper()' 2 7- u)2 `->>> string.isupper() 2 - u2 `-True 2 - u 2 `- u---2 `-The ---2 |-len(@1Courier New---2 -object--- 2 -)u--- 2 - u|2 K-function will return the length of the object passed to it as an argument.   2 -For ---2 ` -strings, ---2 -len()t--- 2 - uD2 &-will return the number of characters i  2  -n the string. 2 - u---"2 `->>> len(string) 2 - u---2 .`-26------------,,,,,,,,,,,,,,++++++++++++**՜.+,0 hp  Self.   Title  !"#$%&'()*+,-./123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnoprstuvwx{Root Entry FNo}1Table&WordDocument06SummaryInformation(0DocumentSummaryInformation8qCompObjy  F'Microsoft Office Word 97-2003 Document MSWordDocWord.Document.89q