简明Python教程(A byte of Python) 1.20 中文版

winecat

贡献于2014-09-09

字数:0 关键词: Python开发 Python

简明 Python 教程 Swaroop, C. H. 著 沈洁元 译 www.byteofpython.info © © ® 注释 ® python -V $ python -V Python 2.3.4 注释 $$ $ python -V bash: python: command not found ® ® ® ® 提示 在Windows命令行中使用Python ® print 'Hello World' Hello World $ python Python 2.3.4 (#1, Oct 26 2004, 16:42:40) [GCC 3.4.2 20041017 (Red Hat 3.4.2-6.fc3)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> print 'hello world' hello world >>> print Hello World 如何退出Python提示符 [1] helloworld.py。 #!/usr/bin/python # Filename : helloworld.py print'Hello World' $ python helloworld.py Hello World printPrintpP 重要 print [1] $ chmod a+x helloworld.py $ ./helloworld.py Hello World helloworld $ echo $PATH /opt/mono/bin/:/usr/local/bin:/usr/bin:/bin:/usr/X11R6/bin:/home/swaroop/bin $ cp helloworld.py /home/swaroop/bin/helloworld $ helloworld Hello World /home/swaroop/bin /home/swaroop/mydir 提示 help help(str)str 注释 q help()help print $ env PYTHONDOCS=/usr/share/doc/python-docs-2.3.4/html/ python Python 2.3.4 (#1, Oct 26 2004, 16:42:40) [GCC 3.4.2 20041017 (Red Hat 3.4.2-6.fc3)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> help('print') print 51.239.25e-3'This is a string'"It's a string!" 2 2 3.2352.3E-452.3E-452.3 * 10 (-5+4j)(2.3-4.6j) 'Quote me on this' "What's your name?" '''This is a multi-line string. This is the first line. This is the second line. "What's your name?," I asked. He said "Bond, James Bond." ''' What's your name?'What's your name?' \' 'What\'s your name?' "What's your name?" \\ "This is the first sentence.\ This is the second sentence." "This is the first sentence. This is the second sentence." rRr"Newlines are indicated by \n" uUu"This is a Unicode string." 'What\'s' 'your name?'"What's your name?" 给C/C++程序员的注释 char 给Perl/PHP程序员的注释 给正则表达式用户的注释 '\\1'r'\1' mynamemyName i__my_namename_23a1b2_c3 2thingsthis is spaced outmy-name 给面向对象编程用户的注释 如何编写Python程序 .py # Filename : var.py i = 5 print i i = i + 1 print i s = '''This is a multi-line string. This is the second line.''' print s $ python var.py 5 6 This is a multi-line string. This is the second line. =5 ii5 printi i1i6 s 给C/C++程序员的注释 print 'Hello World' i = 5 print i i = 5; print i; i = 5; print i; i = 5; print i s = 'This is a string. \ This continues the string.' print s This is a string. This continues the string. print \ i print i i = 5 print 'Value is', i # Error! Notice a single space at the start of the line print 'I repeat, the value is', i File "whitespace.py", line 4 print 'Value is', i # Error! Notice a single space at the start of the line ^ SyntaxError: invalid syntax 如何缩进 2 + 3 + 23 2 + 3 >>> 2 + 3 5 >>> 3 * 5 15 >>> + - * ** / // % << >> & | ^ ~ < > <= >= == != 2 + 3 * 4 2 + (3 * 4)2 + 3 * 42 + (3 + 4) lambda | ^ & ** +- (2 + 3) * 4 2 + 3 + 4 (2 + 3) + 4a = b = ca = (b = c) #!/usr/bin/python # Filename: expression.py length = 5 breadth = 2 area = length * breadth print 'Area is', area print 'Perimeter is', 2 * (length + breadth) $ python expression.py Area is 10 Perimeter is 14 length * breadthareaprint 2 * (length + breadth) 'Area is'area ——ifforwhile if else #!/usr/bin/python # Filename: if.py number = 23 guess = int(raw_input('Enter an integer : ')) if guess == number: print 'Congratulations, you guessed it.' # New block starts here print "(but you do not win any prizes!)" # New block ends here elif guess < number: print 'No, it is a little higher than that' # Another block # You can do whatever you want in a block ... else: print 'No, it is a little lower than that' # you must have guess > number to reach here print 'Done' # This last statement is always executed, after the if statement is executed $ python if.py Enter an integer : 50 No, it is a little lower than that Done $ python if.py Enter an integer : 22 No, it is a little higher than that Done $ python if.py Enter an integer : 23 Congratulations, you guessed it. (but you do not win any prizes!) Done number23raw_input() raw_input raw_input intguessint if elifif else-if elseif-elif-else elifelse ifif elifelseif if True: print 'Yes, it is true' ifelifelseif print 'Done' 给C/C++程序员的注释 switchif..elif..else whilewhile whileelse #!/usr/bin/python # Filename: while.py number = 23 running = True while running: guess = int(raw_input('Enter an integer : ')) if guess == number: print 'Congratulations, you guessed it.' running = False # this causes the while loop to stop elif guess < number: print 'No, it is a little higher than that' else: print 'No, it is a little lower than that' else: print 'The while loop is over.' # Do anything else you want to do here print 'Done' $ python while.py Enter an integer : 50 No, it is a little lower than that. Enter an integer : 22 No, it is a little higher than that. Enter an integer : 23 Congratulations, you guessed it. The while loop is over. Done while raw_inputifwhilerunning TruerunningTrue running whileFalseelse whileelsewhile TrueFalse10 1 whilewhile 给C/C++程序员的注释 whileelse for..in #!/usr/bin/python # Filename: for.py for i in range(1, 5): print i else: print 'The for loop is over' $ python for.py 1 2 3 4 The for loop is over range range range(1,5)[1, 2, 3, 4]rangerange range(1,5,2)[1,3] forfor i in range(1,5)for i in [1, 2, 3, 4] i elsefor for..inrange 给C/C++/Java/C#程序员的注释 forfor forforeach for (int i : IntArray) for (int i = 0; i < 5; i++) for i in range(0,5)for break False forwhileelse #!/usr/bin/python # Filename: break.py while True: s = raw_input('Enter something : ') if s == 'quit': break print 'Length of the string is', len(s) print 'Done' $ python break.py Enter something : Programming is fun Length of the string is 18 Enter something : When the work is done Length of the string is 21 Enter something : if you wanna make your work also fun: Length of the string is 37 Enter something : use Python! Length of the string is 12 Enter something : quit Done 'quit' len breakfor Programming is fun When the work is done if you wanna make your work also fun: use Python! continue #!/usr/bin/python # Filename: continue.py while True: s = raw_input('Enter something : ') if s == 'quit': break if len(s) < 3: continue print 'Input is of sufficient length' # Do other kinds of processing here... $ python continue.py Enter something : a Enter something : 12 Enter something : abc Input is of sufficient length Enter something : quit lencontinue continuefor ifwhilefor breakcontinue lenrange def #!/usr/bin/python # Filename: function1.py def sayHello(): print 'Hello World!' # block belonging to the function sayHello() # call the function $ python function1.py Hello World! sayHello #!/usr/bin/python # Filename: func_param.py def printMax(a, b): if a > b: print a, 'is maximum' else: print b, 'is maximum' printMax(3, 4) # directly give literal values x = 5 y = 7 printMax(x, y) # give variables as arguments $ python func_param.py 4 is maximum 7 is maximum printMaxab if..else printMax printMax(x, y)xayb #!/usr/bin/python # Filename: func_local.py def func(x): print 'x is', x x = 2 print 'Changed local x to', x x = 50 func(x) print 'x is still', x $ python func_local.py x is 50 Changed local x to 2 x is still 50 x 2xxx x printx globalglobal global #!/usr/bin/python # Filename: func_global.py def func(): global x print 'x is', x x = 2 print 'Changed local x to', x x = 50 func() print 'Value of x is', x $ python func_global.py x is 50 Changed global x to 2 Value of x is 2 globalxx x globalglobal x, y, z #!/usr/bin/python # Filename: func_default.py def say(message, times = 1): print message * times say('Hello') say('World', 5) $ python func_default.py Hello WorldWorldWorldWorldWorld say times1 saysay 5 重要 def func(a, b=5) def func(a=5, b) #!/usr/bin/python # Filename: func_key.py def func(a, b=5, c=10): print 'a is', a, 'and b is', b, 'and c is', c func(3, 7) func(25, c=24) func(c=50, a=100) $ python func_key.py a is 3 and b is 7 and c is 10 a is 25 and b is 5 and c is 24 a is 100 and b is 5 and c is 50 func func(3, 7)a3b7c10 func(25, c=24)a25 c24b5 func(c=50, a=100) acac return #!/usr/bin/python # Filename: func_return.py def maximum(x, y): if x > y: return x else: return y print maximum(2, 3) $ python func_return.py 3 maximumif..else returnreturn NoneNone None returnreturn Noneprint someFunction()someFunctionreturn def someFunction(): pass pass #!/usr/bin/python # Filename: func_doc.py def printMax(x, y): '''Prints the maximum of two numbers. The two values must be integers.''' x = int(x) # convert to integers, if possible y = int(y) if x > y: print x, 'is maximum' else: print y, 'is maximum' printMax(3, 5) print printMax.__doc__ __doc__printMax help() __doc__ help(printMax)qhelp help() .py #!/usr/bin/python # Filename: using_sys.py import sys print 'The command line arguments are:' for i in sys.argv: print i print '\n\nThe PYTHONPATH is', sys.path, '\n' $ python using_sys.py we are arguments The command line arguments are: using_sys.py we are arguments The PYTHONPATH is ['/home/swaroop/byte/code', '/usr/lib/python23.zip', '/usr/lib/python2.3', '/usr/lib/python2.3/plat-linux2', '/usr/lib/python2.3/lib-tk', '/usr/lib/python2.3/lib- dynload', '/usr/lib/python2.3/site-packages', '/usr/lib/python2.3/site-packages/gtk-2.0'] import sys sys import syssys.pathsys.py sysargvsys.argv argvsys sys.argvsys.argv python using_sys.py we are arguments using_sys.py sys.argv sys.argv 'using_sys.py'sys.argv[0]'we'sys.argv[1]'are'sys.argv[2] 'arguments'sys.argv[3] sys.pathsys.path sys.pathPYTHONPATH sys.path .pyc .pyc .pyc argvsys.from sys import argvsysfrom sys import *from..importimport #!/usr/bin/python # Filename: using_name.py if __name__ == '__main__': print 'This program is being run by itself' else: print 'I am being imported from another module' $ python using_name.py This program is being run by itself $ python >>> import using_name I am being imported from another module >>> __name__'__main__' .py #!/usr/bin/python # Filename: mymodule.py def sayhi(): print 'Hi, this is mymodule speaking.' version = '0.1' # End of mymodule.py sys.path #!/usr/bin/python # Filename: mymodule_demo.py import mymodule mymodule.sayhi() print 'Version', mymodule.version $ python mymodule_demo.py Hi, this is mymodule speaking. Version 0.1 from..import #!/usr/bin/python # Filename: mymodule_demo2.py from mymodule import sayhi, version # Alternative: # from mymodule import * sayhi() print 'Version', version mymodule_demo2.pymymodule_demo.py dir dir() $ python >>> import sys >>> dir(sys) # get list of attributes for sys module ['__displayhook__', '__doc__', '__excepthook__', '__name__', '__stderr__', '__stdin__', '__stdout__', '_getframe', 'api_version', 'argv', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'exc_clear', 'exc_info', 'exc_type', 'excepthook', 'exec_prefix', 'executable', 'exit', 'getcheckinterval', 'getdefaultencoding', 'getdlopenflags', 'getfilesystemencoding', 'getrecursionlimit', 'getrefcount', 'hexversion', 'maxint', 'maxunicode', 'meta_path','modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', 'setcheckinterval', 'setdlopenflags', 'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'version', 'version_info', 'warnoptions'] >>> dir() # get list of attributes for current module ['__builtins__', '__doc__', '__name__', 'sys'] >>> >>> a = 5 # create a new variable 'a' >>> dir() ['__builtins__', '__doc__', '__name__', 'a', 'sys'] >>> >>> del a # delete/remove a name >>> >>> dir() ['__builtins__', '__doc__', '__name__', 'sys'] >>> sysdir dir diradir deldir deldel a a list i5 intihelp(int) listappend mylist.append('an item')mylist mylist.field #!/usr/bin/python # Filename: using_list.py # This is my shopping list shoplist = ['apple', 'mango', 'carrot', 'banana'] print 'I have', len(shoplist),'items to purchase.' print 'These items are:', # Notice the comma at end of the line for item in shoplist: print item, print '\nI also have to buy rice.' shoplist.append('rice') print 'My shopping list is now', shoplist print 'I will sort my list now' shoplist.sort() print 'Sorted shopping list is', shoplist print 'The first item I will buy is', shoplist[0] olditem = shoplist[0] del shoplist[0] print 'I bought the', olditem print 'My shopping list is now', shoplist $ python using_list.py I have 4 items to purchase. These items are: apple mango carrot banana I also have to buy rice. My shopping list is now ['apple', 'mango', 'carrot', 'banana', 'rice'] I will sort my list now Sorted shopping list is ['apple', 'banana', 'carrot', 'mango', 'rice'] The first item I will buy is apple I bought the apple My shopping list is now ['banana', 'carrot', 'mango', 'rice'] shoplistshoplist for..in print print append print sort del del del shoplist[0] help(list) #!/usr/bin/python # Filename: using_tuple.py zoo = ('wolf', 'elephant', 'penguin') print 'Number of animals in the zoo is', len(zoo) new_zoo = ('monkey', 'dolphin', zoo) print 'Number of animals in the new zoo is', len(new_zoo) print 'All animals in new zoo are', new_zoo print 'Animals brought from old zoo are', new_zoo[2] print 'Last animal brought from old zoo is', new_zoo[2][2] $ python using_tuple.py Number of animals in the zoo is 3 Number of animals in the new zoo is 3 All animals in new zoo are ('monkey', 'dolphin', ('wolf', 'elephant', 'penguin')) Animals brought from old zoo are ('wolf', 'elephant', 'penguin') Last animal brought from old zoo is penguin zoolen new_zoo new_zoo[2]new_zoo new_zoo[2][2]new_zoo myempty = () 2 singleton = (2 , ) 给Perl程序员的注释 #!/usr/bin/python # Filename: print_tuple.py age = 22 name = 'Swaroop' print '%s is %d years old' % (name, age) print 'Why is %s playing with that python?' % name $ python print_tuple.py Swaroop is 22 years old Why is Swaroop playing with that python? print% %s%d %sname %dage %s name print %s print% d = {key1 : value1, key2 : value2 } dict #!/usr/bin/python # Filename: using_dict.py # 'ab' is short for 'a'ddress'b'ook ab = { 'Swaroop' : 'swaroopch@byteofpython.info', 'Larry' : 'larry@wall.org', 'Matsumoto' : 'matz@ruby-lang.org', 'Spammer' : 'spammer@hotmail.com' } print "Swaroop's address is %s" % ab['Swaroop'] # Adding a key/value pair ab['Guido'] = 'guido@python.org' # Deleting a key/value pair del ab['Spammer'] print '\nThere are %d contacts in the address-book\n' % len(ab) for name, address in ab.items(): print 'Contact %s at %s' % (name, address) if 'Guido' in ab: # OR ab.has_key('Guido') print "\nGuido's address is %s" % ab['Guido'] $ python using_dict.py Swaroop's address is swaroopch@byteofpython.info There are 4 contacts in the address-book Contact Swaroop at swaroopch@byteofpython.info Contact Matsumoto at matz@ruby-lang.org Contact Larry at larry@wall.org Contact Guido at guido@python.org Guido's address is guido@python.org ab del del items for..in nameaddress indicthas_key help(dict)dict #!/usr/bin/python # Filename: seq.py shoplist = ['apple', 'mango', 'carrot', 'banana'] # Indexing or 'Subscription' operation print 'Item 0 is', shoplist[0] print 'Item 1 is', shoplist[1] print 'Item 2 is', shoplist[2] print 'Item 3 is', shoplist[3] print 'Item -1 is', shoplist[-1] print 'Item -2 is', shoplist[-2] # Slicing on a list print 'Item 1 to 3 is', shoplist[1:3] print 'Item 2 to end is', shoplist[2:] print 'Item 1 to -1 is', shoplist[1:-1] print 'Item start to end is', shoplist[:] # Slicing on a string name = 'swaroop' print 'characters 1 to 3 is', name[1:3] print 'characters 2 to end is', name[2:] print 'characters 1 to -1 is', name[1:-1] print 'characters start to end is', name[:] $ python seq.py Item 0 is apple Item 1 is mango Item 2 is carrot Item 3 is banana Item -1 is banana Item -2 is carrot Item 1 to 3 is ['mango', 'carrot'] Item 2 to end is ['carrot', 'banana'] Item 1 to -1 is ['mango', 'carrot'] Item start to end is ['apple', 'mango', 'carrot', 'banana'] characters 1 to 3 is wa characters 2 to end is aroop characters 1 to -1 is waroo characters start to end is swaroop shoplist[0]shoplist[3]shoplist shoplist[-1] shoplist[-2] shoplist[1:3] shoplist[:] shoplist[:-1] #!/usr/bin/python # Filename: reference.py print 'Simple Assignment' shoplist = ['apple', 'mango', 'carrot', 'banana'] mylist = shoplist # mylist is just another name pointing to the same object! del shoplist[0] print 'shoplist is', shoplist print 'mylist is', mylist # notice that both shoplist and mylist both print the same list without # the 'apple' confirming that they point to the same object print 'Copy by making a full slice' mylist = shoplist[:] # make a copy by doing a full slice del mylist[0] # remove first item print 'shoplist is', shoplist print 'mylist is', mylist # notice that now the two lists are different $ python reference.py Simple Assignment shoplist is ['mango', 'carrot', 'banana'] mylist is ['mango', 'carrot', 'banana'] Copy by making a full slice shoplist is ['mango', 'carrot', 'banana'] mylist is ['carrot', 'banana'] 给Perl程序员的注释 str help(str) #!/usr/bin/python # Filename: str_methods.py name = 'Swaroop' # This is a string object if name.startswith('Swa'): print 'Yes, the string starts with "Swa"' if 'a' in name: print 'Yes, it contains the string "a"' if name.find('war') != -1: print 'Yes, it contains the string "war"' delimiter = '_*_' mylist = ['Brazil', 'Russia', 'India', 'China'] print delimiter.join(mylist) $ python str_methods.py Yes, the string starts with "Swa" Yes, it contains the string "a" Yes, it contains the string "war" Brazil_*_Russia_*_India_*_China startwith in findstr join 2 3 4 5 #!/usr/bin/python # Filename: backup_ver1.py import os import time # 1. The files and directories to be backed up are specified in a list. source = ['/home/swaroop/byte', '/home/swaroop/bin'] # If you are using Windows, use source = [r'C:\Documents', r'D:\Work'] or something like that # 2. The backup must be stored in a main backup directory target_dir = '/mnt/e/backup/' # Remember to change this to what you will be using # 3. The files are backed up into a zip file. # 4. The name of the zip archive is the current date and time target = target_dir + time.strftime('%Y%m%d%H%M%S') + '.zip' # 5. We use the zip command (in Unix/Linux) to put the files in a zip archive zip_command = "zip -qr '%s' %s" % (target, ' '.join(source)) # Run the backup if os.system(zip_command) == 0: print 'Successful backup to', target else: print 'Backup FAILED' $ python backup_ver1.py Successful backup to /mnt/e/backup/20041208073244.zip ostimesource target_dir time.strftime().zip target_dir time.strftime()%Y %m print % zip_command -q-r -qr joinsource os.system 给Windows用户的注释 sourcetarget 'C:\\Documents'r'C:\Documents''C:\Documents' \D #!/usr/bin/python # Filename: backup_ver2.py import os import time # 1. The files and directories to be backed up are specified in a list. source = ['/home/swaroop/byte', '/home/swaroop/bin'] # If you are using Windows, use source = [r'C:\Documents', r'D:\Work'] or something like that # 2. The backup must be stored in a main backup directory target_dir = '/mnt/e/backup/' # Remember to change this to what you will be using # 3. The files are backed up into a zip file. # 4. The current day is the name of the subdirectory in the main directory today = target_dir + time.strftime('%Y%m%d') # The current time is the name of the zip archive now = time.strftime('%H%M%S') # Create the subdirectory if it isn't already there if not os.path.exists(today): os.mkdir(today) # make directory print 'Successfully created directory', today # The name of the zip file target = today + os.sep + now + '.zip' # 5. We use the zip command (in Unix/Linux) to put the files in a zip archive zip_command = "zip -qr '%s' %s" % (target, ' '.join(source)) # Run the backup if os.system(zip_command) == 0: print 'Successful backup to', target else: print 'Backup FAILED' $ python backup_ver2.py Successfully created directory /mnt/e/backup/20041208 Successful backup to /mnt/e/backup/20041208/080020.zip $ python backup_ver2.py Successful backup to /mnt/e/backup/20041208/080428.zip os.exists os.mkdir os.sep'/' '\\' ':'os.sep #!/usr/bin/python # Filename: backup_ver3.py import os import time # 1. The files and directories to be backed up are specified in a list. source = ['/home/swaroop/byte', '/home/swaroop/bin'] # If you are using Windows, use source = [r'C:\Documents', r'D:\Work'] or something like that # 2. The backup must be stored in a main backup directory target_dir = '/mnt/e/backup/' # Remember to change this to what you will be using # 3. The files are backed up into a zip file. # 4. The current day is the name of the subdirectory in the main directory today = target_dir + time.strftime('%Y%m%d') # The current time is the name of the zip archive now = time.strftime('%H%M%S') # Take a comment from the user to create the name of the zip file comment = raw_input('Enter a comment --> ') if len(comment) == 0: # check if a comment was entered target = today + os.sep + now + '.zip' else: target = today + os.sep + now + '_' + comment.replace(' ', '_') + '.zip' # Create the subdirectory if it isn't already there if not os.path.exists(today): os.mkdir(today) # make directory print 'Successfully created directory', today # 5. We use the zip command (in Unix/Linux) to put the files in a zip archive zip_command = "zip -qr '%s' %s" % (target, ' '.join(source)) # Run the backup if os.system(zip_command) == 0: print 'Successful backup to', target else: print 'Backup FAILED' $ python backup_ver3.py File "backup_ver3.py", line 25 target = today + os.sep + now + '_' + ^ SyntaxError: invalid syntax #!/usr/bin/python # Filename: backup_ver4.py import os import time # 1. The files and directories to be backed up are specified in a list. source = ['/home/swaroop/byte', '/home/swaroop/bin'] # If you are using Windows, use source = [r'C:\Documents', r'D:\Work'] or something like that # 2. The backup must be stored in a main backup directory target_dir = '/mnt/e/backup/' # Remember to change this to what you will be using # 3. The files are backed up into a zip file. # 4. The current day is the name of the subdirectory in the main directory today = target_dir + time.strftime('%Y%m%d') # The current time is the name of the zip archive now = time.strftime('%H%M%S') # Take a comment from the user to create the name of the zip file comment = raw_input('Enter a comment --> ') if len(comment) == 0: # check if a comment was entered target = today + os.sep + now + '.zip' else: target = today + os.sep + now + '_' + \ comment.replace(' ', '_') + '.zip' # Notice the backslash! # Create the subdirectory if it isn't already there if not os.path.exists(today): os.mkdir(today) # make directory print 'Successfully created directory', today # 5. We use the zip command (in Unix/Linux) to put the files in a zip archive zip_command = "zip -qr '%s' %s" % (target, ' '.join(source)) # Run the backup if os.system(zip_command) == 0: print 'Successful backup to', target else: print 'Backup FAILED' $ python backup_ver4.py Enter a comment --> added new examples Successful backup to /mnt/e/backup/20041208/082156_added_new_examples.zip $ python backup_ver4.py Enter a comment --> Successful backup to /mnt/e/backup/20041208/082316.zip raw_input len .zip -v sys.argv listextendsource .tar.gz tar = 'tar -cvzf %s %s -X /home/swaroop/excludes.txt' % (target, ' '.join(srcdir)) -c -v -z -f -X*~ ~ 重要 zipfiletarfile os.system os.system 2 3 4 5 6 重要 self intint 给C/C++/Java/C#程序员的注释 int help(int) class self self self self self self 给C++/Java/C#程序员的注释 selfselfthis self MyClassMyObject MyObject.method(arg1, arg2) MyClass.method(MyObject, arg1, arg2)self self #!/usr/bin/python # Filename: simplestclass.py class Person: pass # An empty block p = Person() print p $ python simplestclass.py <__main__.Person instance at 0xf6fcb18c> class pass __main__ Person self #!/usr/bin/python # Filename: method.py class Person: def sayHi(self): print 'Hello, how are you?' p = Person() p.sayHi() # This short example can also be written as Person().sayHi() $ python method.py Hello, how are you? selfsayHiself __init__ __init__ #!/usr/bin/python # Filename: class_init.py class Person: def __init__(self, name): self.name = name def sayHi(self): print 'Hello, my name is', self.name p = Person('Swaroop') p.sayHi() # This short example can also be written as Person('Swaroop').sayHi() $ python class_init.py Hello, my name is Swaroop __init__nameself __init__name __init__ __init__ self.namesayHi 给C++/Java/C#程序员的注释 __init__ #!/usr/bin/python # Filename: objvar.py class Person: '''Represents a person.''' population = 0 def __init__(self, name): '''Initializes the person's data.''' self.name = name print '(Initializing %s)' % self.name # When this person is created, he/she # adds to the population Person.population += 1 def __del__(self): '''I am dying.''' print '%s says bye.' % self.name Person.population -= 1 if Person.population == 0: print 'I am the last one.' else: print 'There are still %d people left.' % Person.population def sayHi(self): '''Greeting by the person. Really, that's all it does.''' print 'Hi, my name is %s.' % self.name def howMany(self): '''Prints the current population.''' if Person.population == 1: print 'I am the only person here.' else: print 'We have %d persons here.' % Person.population swaroop = Person('Swaroop') swaroop.sayHi() swaroop.howMany() kalam = Person('Abdul Kalam') kalam.sayHi() kalam.howMany() swaroop.sayHi() swaroop.howMany() $ python objvar.py (Initializing Swaroop) Hi, my name is Swaroop. I am the only person here. (Initializing Abdul Kalam) Hi, my name is Abdul Kalam. We have 2 persons here. Hi, my name is Swaroop. We have 2 persons here. Abdul Kalam says bye. There are still 1 people left. Swaroop says bye. I am the last one. populationPerson nameself __init__Person population1self.name self Person.__doc__Person.sayHi.__doc__ __init____del__ Person.population1 __del__ del 给C++/Java/C#程序员的注释 __privatevar __del__ SchoolMember SchoolMember SchoolMember SchoolMember SchoolMember TeacherStudent #!/usr/bin/python # Filename: inherit.py class SchoolMember: '''Represents any school member.''' def __init__(self, name, age): self.name = name self.age = age print '(Initialized SchoolMember: %s)' % self.name def tell(self): '''Tell my details.''' print 'Name:"%s" Age:"%s"' % (self.name, self.age), class Teacher(SchoolMember): '''Represents a teacher.''' def __init__(self, name, age, salary): SchoolMember.__init__(self, name, age) self.salary = salary print '(Initialized Teacher: %s)' % self.name def tell(self): SchoolMember.tell(self) print 'Salary: "%d"' % self.salary class Student(SchoolMember): '''Represents a student.''' def __init__(self, name, age, marks): SchoolMember.__init__(self, name, age) self.marks = marks print '(Initialized Student: %s)' % self.name def tell(self): SchoolMember.tell(self) print 'Marks: "%d"' % self.marks t = Teacher('Mrs. Shrividya', 40, 30000) s = Student('Swaroop', 22, 75) print # prints a blank line members = [t, s] for member in members: member.tell() # works for both Teachers and Students $ python inherit.py (Initialized SchoolMember: Mrs. Shrividya) (Initialized Teacher: Mrs. Shrividya) (Initialized SchoolMember: Swaroop) (Initialized Student: Swaroop) Name:"Mrs. Shrividya" Age:"40" Salary: "30000" Name:"Swaroop" Age:"22" Marks: "75" __init__self self SchoolMembertellTeacherStudent SchoolMember tellSchoolMembertell raw_inputprint strrjust help(str) filefile readreadlinewrite close #!/usr/bin/python # Filename: using_file.py poem = '''\ Programming is fun When the work is done if you wanna make your work also fun: use Python! ''' f = file('poem.txt', 'w') # open for 'w'riting f.write(poem) # write text to file f.close() # close the file f = file('poem.txt') # if no mode is specified, 'r'ead mode is assumed by default while True: line = f.readline() if len(line) == 0: # Zero length indicates EOF break print line, # Notice comma to avoid automatic newline added by Python f.close() # close the file $ python using_file.py Programming is fun When the work is done if you wanna make your work also fun: use Python! file'r' 'w''a'help(file) filewriteclose readline print close poem.txt pickle cPicklepickle picklecPickle pickle #!/usr/bin/python # Filename: pickling.py import cPickle as p #import pickle as p shoplistfile = 'shoplist.data' # the name of the file where we will store the object shoplist = ['apple', 'mango', 'carrot'] # Write to the file f = file(shoplistfile, 'w') p.dump(shoplist, f) # dump the object to a file f.close() del shoplist # remove the shoplist # Read back from the storage f = file(shoplistfile) storedlist = p.load(f) print storedlist $ python pickling.py ['apple', 'mango', 'carrot'] import..as cPicklepickle p filedump pickleload printprintPrint >>> Print 'Hello World' File "", line 1 Print 'Hello World' ^ SyntaxError: invalid syntax >>> print 'Hello World' Hello World SyntaxError >>> s = raw_input('Enter something --> ') Enter something --> Traceback (most recent call last): File "", line 1, in ? EOFError EOFError try..except #!/usr/bin/python # Filename: try_except.py import sys try: s = raw_input('Enter something --> ') except EOFError: print '\nWhy did you do an EOF on me?' sys.exit() # exit the program except: print '\nSome error/exception occurred.' # here, we are not exiting the program print 'Done' $ python try_except.py Enter something --> Why did you do an EOF on me? $ python try_except.py Enter something --> Python is exceptional! Done tryexcept except tryexcept try..catchelseelse raise ErrorException #!/usr/bin/python # Filename: raising.py class ShortInputException(Exception): '''A user-defined exception class.''' def __init__(self, length, atleast): Exception.__init__(self) self.length = length self.atleast = atleast try: s = raw_input('Enter something --> ') if len(s) < 3: raise ShortInputException(len(s), 3) # Other work can continue as usual here except EOFError: print '\nWhy did you do an EOF on me?' except ShortInputException, x: print 'ShortInputException: The input was of length %d, \ was expecting at least %d' % (x.length, x.atleast) else: print 'No exception was raised.' $ python raising.py Enter something --> Why did you do an EOF on me? $ python raising.py Enter something --> ab ShortInputException: The input was of length 2, was expecting at least 3 $ python raising.py Enter something --> abc No exception was raised. ShortInputExceptionlengthatleast except exceptlengthatleast finallytryexceptfinally #!/usr/bin/python # Filename: finally.py import time try: f = file('poem.txt') while True: # our usual file-reading idiom line = f.readline() if len(line) == 0: break time.sleep(2) print line, finally: f.close() print 'Cleaning up...closed the file' $ python finally.py Programming is fun When the work is done Cleaning up...closed the file Traceback (most recent call last): File "finally.py", line 12, in ? time.sleep(2) KeyboardInterrupt time.sleep KeyboardInterrupt try..excepttry..finally syssys.argv #!/usr/bin/python # Filename: cat.py import sys def readfile(filename): '''Print a file to the standard output.''' f = file(filename) while True: line = f.readline() if len(line) == 0: break print line, # notice comma f.close() # Script starts from here if len(sys.argv) < 2: print 'No action specified.' sys.exit() if sys.argv[1].startswith('--'): option = sys.argv[1][2:] # fetch sys.argv[1] but without the first two characters if option == 'version': print 'Version 1.2' elif option == 'help': print '''\ This program prints files to the standard output. Any number of files can be specified. Options include: --version : Prints the version number --help : Display this help''' else: print 'Unknown option.' sys.exit() else: for filename in sys.argv[1:]: readfile(filename) $ python cat.py No action specified. $ python cat.py --help This program prints files to the standard output. Any number of files can be specified. Options include: --version : Prints the version number --help : Display this help $ python cat.py --version Version 1.2 $ python cat.py --nonsense Unknown option. $ python cat.py poem.txt Programming is fun When the work is done if you wanna make your work also fun: use Python! sys.argv sys.argv[0]0 --version --helpsys.exit help(sys.exit) sys.versionsys.version_info [swaroop@localhost code]$ python >>> import sys >>> sys.version '2.3.4 (#1, Oct 26 2004, 16:42:40) \n[GCC 3.4.2 20041017 (Red Hat 3.4.2-6.fc3)]' >>> sys.version_info (2, 3, 4, 'final', 0) sys sys.stdinsys.stdoutsys.stderr os.sep os os.name'nt' 'posix' os.getcwd() os.getenv()os.putenv() os.listdir() os.remove() os.system() os.linesep'\r\n' '\n''\r' os.path.split() >>> os.path.split('/home/swaroop/byte/code/poem.txt') ('/home/swaroop/byte/code', 'poem.txt') os.path.isfile()os.path.isdir() os.path.existe() help(sys) sysos __init____del__ x[key] __getitem__() list printstr() x[key] len() >>> flag = True >>> if flag: print 'Yes' ... Yes if... #!/usr/bin/python # Filename: list_comprehension.py listone = [2, 3, 4] listtwo = [2*i for i in listone if i > 2] print listtwo $ python list_comprehension.py [6, 8] if i > 22*i *** >>> def powersum(power, *args): ... '''Return the sum of each argument raised to specified power.''' ... total = 0 ... for i in args: ... total += pow(i, power) ... return total ... >>> powersum(2, 3, 4) 25 >>> powersum(2, 10) 100 args*args** lambda #!/usr/bin/python # Filename: lambda.py def make_repeater(n): return lambda s: s*n twice = make_repeater(2) print twice('word') print twice(5) $ python lambda.py wordword 10 make_repeaterlambda lambda print exec exec >>> exec 'print "Hello World"' Hello World eval >>> eval('2*3') 6 assert assert AssertionError >>> mylist = ['item'] >>> assert len(mylist) >= 1 >>> mylist.pop() 'item' >>> assert len(mylist) >= 1 Traceback (most recent call last): File "", line 1, in ? AssertionError repr eval(repr(object)) == object >>> i = [] >>> i.append('item') >>> `i` "['item']" >>> repr(i) "['item']" repr__repr__ repr GUI 未来的章节 ® #!/usr/bin/env python # Filename : helloworld.py print 'Hello World' # Filename : var.py i=5 print i i=i+1 print i s='''This is a multi-line string. This is the second line.''' print s #!/usr/bin/env python # Filename: expression.py length=5 breadth=2 area=length*breadth print 'Area is',area print 'Perimeter is',2*(length+breadth) #!/usr/bin/env python # Filename: if.py number=23 guess=int(raw_input('Enter an integer : ')) if guess==number: print 'Congratulations, you guessed it.' # New block starts here print "(but you do not win any prizes!)" # New block ends here elif guess number to reach here print 'Done' # This last statement is always executed, after the if statement is executed #!/usr/bin/env python # Filename: while.py number=23 running=True while running: guess=int(raw_input('Enter an integer : ')) if guess==number: print 'Congratulations, you guessed it.' running=False # this causes the while loop to stop elif guessb: print a,'is maximum' else: print b,'is maximum' printMax(3,4) # directly give literal values x=5 y=7 printMax(x,y) # give variables as arguments #!/usr/bin/env python # Filename: func_local.py def func(x): print 'x is',x x=2 print 'Changed local x to',x x=50 func(x) print 'x is still',x #!/usr/bin/env python # Filename: func_global.py def func(): global x print 'x is',x x=2 print 'Changed local x to',x x=50 func() print 'Value of x is',x #!/usr/bin/env python # Filename: func_default.py def say(message,times=1): print message*times say('Hello') say('World',5) #!/usr/bin/env python # Filename: func_key.py def func(a,b=5,c=10): print 'a is',a,'and b is',b,'and c is',c func(3,7) func(25,c=24) func(c=50,a=100) #!/usr/bin/env python # Filename: func_return.py def maximum(x,y): if x>y: return x else: return y print maximum(2,3) #!/usr/bin/env python # Filename: func_doc.py def printMax(x,y): '''Prints the maximum of two numbers. The two values must be integers.''' x=int(x) # convert to integers, if possible y=int(y) if x>y: print x,'is maximum' else: print y,'is maximum' printMax(3,5) print printMax.__doc__ #!/usr/bin/env python # Filename: using_sys.py import sys print 'The command line arguments are:' for i in sys.argv: print i print '\n\nThe PYTHONPATH is',sys.path,'\n' #!/usr/bin/env python # Filename: using_name.py if __name__=='__main__': print 'This program is being run by itself' else: print 'I am being imported from another module' #!/usr/bin/env python # Filename: mymodule.py def sayhi(): print 'Hi, this is mymodule speaking.' version='0.1' # End of mymodule.py #!/usr/bin/env python # Filename: mymodule_demo.py import mymodule mymodule.sayhi() print 'Version', mymodule.version #!/usr/bin/env python # Filename: mymodule_demo2.py from mymodule import sayhi,version # Alternative: # from mymodule import * sayhi() print 'Version',version #!/usr/bin/env python # Filename: using_list.py # This is my shopping list shoplist=['apple','mango','carrot','banana'] print 'I have',len(shoplist),'items to purchase.' print 'These items are:', # Notice the comma at end of the line for item in shoplist: print item, print '\nI also have to buy rice.' shoplist.append('rice') print 'My shopping list is now',shoplist print 'I will sort my list now' shoplist.sort() print 'Sorted shopping list is',shoplist print 'The first item I will buy is',shoplist[0] olditem=shoplist[0] del shoplist[0] print 'I bought the',olditem print 'My shopping list is now',shoplist #!/usr/bin/env python # Filename: using_tuple.py zoo=('wolf','elephant','penguin') print 'Number of animals in the zoo is',len(zoo) new_zoo=('monkey','dolphin',zoo) print 'Number of animals in the new zoo is',len(new_zoo) print 'All animals in new zoo are',new_zoo print 'Animals brought from old zoo are',new_zoo[2] print 'Last animal brought from old zoo is',new_zoo[2][2] #!/usr/bin/env python # Filename: print_tuple.py age=22 name='Swaroop' print '%s is %d years old' %(name,age) print 'Why is %s playing with that python?' %name #!/usr/bin/env python # Filename: using_dict.py # 'ab' is short for 'a'ddress'b'ook ab={ 'Swaroop' : 'swaroopch@byteofpython.info', 'Larry' : 'larry@wall.org', 'Matsumoto' : 'matz@ruby-lang.org', 'Spammer' : 'spammer@hotmail.com' } print "Swaroop's address is %s" %ab['Swaroop'] # Adding a key/value pair ab['Guido']='guido@python.org' # Deleting a key/value pair del ab['Spammer'] print '\nThere are %d contacts in the address-book\n' %len(ab) for name,address in ab.items(): print 'Contact %s at %s' %(name,address) if 'Guido' in ab: # OR ab.has_key('Guido') print "\nGuido's address is %s" %ab['Guido'] #!/usr/bin/env python # Filename: seq.py shoplist=['apple','mango','carrot','banana'] # Indexing or 'Subscription' operation print 'Item 0 is', shoplist[0] print 'Item 1 is', shoplist[1] print 'Item 2 is', shoplist[2] print 'Item 3 is', shoplist[3] print 'Item -1 is', shoplist[-1] print 'Item -2 is', shoplist[-2] # Slicing on a list print 'Item 1 to 3 is', shoplist[1:3] print 'Item 2 to end is', shoplist[2:] print 'Item 1 to -1 is', shoplist[1:-1] print 'Item start to end is', shoplist[:] # Slicing on a string name='swaroop' print 'characters 1 to 3 is', name[1:3] print 'characters 2 to end is', name[2:] print 'characters 1 to -1 is', name[1:-1] print 'characters start to end is', name[:] #!/usr/bin/env python # Filename: reference.py print 'Simple Assignment' shoplist=['apple','mango','carrot','banana'] mylist=shoplist # mylist is just another name pointing to the same object! del shoplist[0] print 'shoplist is',shoplist print 'mylist is',mylist # notice that both shoplist and mylist both print the same list without # the 'apple' confirming that they point to the same object print 'Copy by making a full slice' mylist=shoplist[:] # make a copy by doing a full slice del mylist[0] # remove first item print 'shoplist is', shoplist print 'mylist is', mylist # notice that now the two lists are different #!/usr/bin/env python # Filename: str_methods.py name='Swaroop' # This is a string object if name.startswith('Swa'): print 'Yes, the string starts with "Swa"' if 'a' in name: print 'Yes, it contains the string "a"' if name.find('war')!=-1: print 'Yes, it contains the string "war"' delimiter=' * ' mylist=['Brazil','Russia','India','China'] print delimiter.join(mylist) #!/usr/bin/env python # Filename: backup_ver1.py import os import time # 1. The files and directories to be backed up are specified in a list. source=['/home/swaroop/byte','/home/swaroop/bin'] # If you are using Windows, use source=[r'C:\Documents',r'D:\Work'] or something like that # 2. The backup must be stored in a main backup directory target_dir='/mnt/e/backup/' #Remember to change this to what you will be using # 3. The files are backed up into a zip file # 4. The name of the zip archive is the current date and time target=target_dir+time.strftime('%Y%m%d%H%M%S')+'.zip' # 5. We use the zip command (in Unix/Linux) to put the files in a zip archive zip_command="zip -qr '%s' %s" %(target,' '.join(source)) # Run the backup if os.system(zip_command)==0: print 'Successful backup to',target else: print 'Backup FAILED' #!/usr/bin/env python # Filename: backup_ver2.py import os import time # 1. The files and directories to be backed up are specified in a list. source=['/home/swaroop/byte','/home/swaroop/bin'] # If you are using Windows, use source=[r'C:\Documents',r'D:\Work'] or something like that # 2. The backup must be stored in a main backup directory target_dir='/mnt/e/backup/' #Remember to change this to what you will be using # 3. The files are backed up into a zip file # 4. The current day is the name of the subdirectory in the main directory today=target_dir+time.strftime('%Y%m%d') # The current time is the name of the zip archive now=time.strftime('%H%M%S') # Create the subdirectory if it isn't already there if not os.path.exists(today): os.mkdir(today) # make directory print 'Successfully created directory',today # The name of the zip file target=today+os.sep+now+'.zip' # 5. We use the zip command (in Unix/Linux) to put the files in a zip archive zip_command="zip -qr '%s' %s" %(target,' '.join(source)) # Run the backup if os.system(zip_command)==0: print 'Successful backup to',target else: print 'Backup FAILED' #!/usr/bin/env python # Filename: backup_ver3.py import os import time # 1. The files and directories to be backed up are specified in a list. source=['/home/swaroop/byte','/home/swaroop/bin'] # If you are using Windows, use source=[r'C:\Documents',r'D:\Work'] or something like that # 2. The backup must be stored in a main backup directory target_dir='/mnt/e/backup/' #Remember to change this to what you will be using # 3. The files are backed up into a zip file # 4. The current day is the name of the subdirectory in the main directory today=target_dir+time.strftime('%Y%m%d') # The current time is the name of the zip archive now=time.strftime('%H%M%S') # Take a comment from the user to create the name of the zip file comment=raw_input('Enter a comment --> ') if len(comment)==0: # check if a comment was entered target=today+os.sep+now+'.zip' else: target=today+os.sep+now+'_'+ comment.replace(' ','_')+'.zip' # Create the subdirectory if it isn't already there if not os.path.exists(today): os.mkdir(today) # make directory print 'Successfully created directory',today # 5. We use the zip command (in Unix/Linux) to put the files in a zip archive zip_command="zip -qr '%s' %s" %(target,' '.join(source)) # Run the backup if os.system(zip_command)==0: print 'Successful backup to',target else: print 'Backup FAILED' #!/usr/bin/env python # Filename: backup_ver4.py import os import time # 1. The files and directories to be backed up are specified in a list. source=['/home/swaroop/byte','/home/swaroop/bin'] # If you are using Windows, use source=[r'C:\Documents',r'D:\Work'] or something like that # 2. The backup must be stored in a main backup directory target_dir='/mnt/e/backup/' #Remember to change this to what you will be using # 3. The files are backed up into a zip file # 4. The current day is the name of the subdirectory in the main directory today=target_dir+time.strftime('%Y%m%d') # The current time is the name of the zip archive now=time.strftime('%H%M%S') # Take a comment from the user to create the name of the zip file comment=raw_input('Enter a comment --> ') if len(comment)==0: # check if a comment was entered target=today+os.sep+now+'.zip' else: target=today+os.sep+now+'_'+\ comment.replace(' ','_')+'.zip' # Notice the backslash! # Create the subdirectory if it isn't already there if not os.path.exists(today): os.mkdir(today) # make directory print 'Successfully created directory',today # 5. We use the zip command (in Unix/Linux) to put the files in a zip archive zip_command="zip -qr '%s' %s" %(target,' '.join(source)) # Run the backup if os.system(zip_command)==0: print 'Successful backup to',target else: print 'Backup FAILED' #!/usr/bin/env python # Filename: simplestclass.py class Person: pass # An empty block p=Person() print p #!/usr/bin/env python # Filename: method.py class Person: def sayHi(self): print 'Hello, how are you?' p=Person() p.sayHi() # This short example can also be written as Person().sayHi() #!/usr/bin/env python # Filename: class_init.py class Person: def __init__(self,name): self.name=name def sayHi(self): print 'Hello, my name is',self.name p=Person('Swaroop') p.sayHi() # This short example can also be written as Person('Swaroop').sayHi() #!/usr/bin/env python # Filename: objvar.py class Person: '''Represents a person.''' population=0 def __init__(self,name): '''Initializes the person's data.''' self.name=name print '(Initializing %s)' %self.name #When this person is created, he/she adds to the population Person.population+=1 def __del__(self): '''I am dying.''' print '%s says bye.' %self.name Person.population-=1 if Person.population==0: print 'I am the last one.' else: print 'There are still %d people left.' %Person.population def sayHi(self): '''Greeting by the person. Really, that's all it does.''' print 'Hi, my name is %s.' %self.name def howMany(self): '''Prints the current population.''' if Person.population==1: print 'I am the only person here.' else: print 'We have %d persons here.' %Person.population swaroop=Person('Swaroop') swaroop.sayHi() swaroop.howMany() kalam=Person('Abdul Kalam') kalam.sayHi() kalam.howMany() swaroop.sayHi() swaroop.howMany() #!/usr/bin/env python # Filename: inherit.py class SchoolMember: '''Represents any school member.''' def __init__(self,name,age): self.name=name self.age=age print '(Initialized SchoolMember: %s)' %self.name def tell(self): '''Tell my details.''' print 'Name:"%s" Age:"%s"' %(self.name,self.age), class Teacher(SchoolMember): '''Represents a teacher.''' def __init__(self,name,age,salary): SchoolMember.__init__(self,name,age) self.salary=salary print '(Initialized Teacher: %s)' %self.name def tell(self): SchoolMember.tell(self) print 'Salary: "%d"' %self.salary class Student(SchoolMember): '''Represents a student.''' def __init__(self,name,age,marks): SchoolMember.__init__(self,name,age) self.marks=marks print '(Initialized Student: %s)' %self.name def tell(self): SchoolMember.tell(self) print 'Marks: "%d"' %self.marks t=Teacher('Mrs. Shrividya',40,30000) s=Student('Swaroop',22,75) print # prints a blank line members=[t,s] for member in members: member.tell() # works for both Teachers and Students #!/usr/bin/env python # Filename: using_file.py poem='''\ Programming is fun When the work is done if you wanna make your work also fun: use Python! ''' f=file('poem.txt','w') # open for 'w'riting f.write(poem) # write text to file f.close() # close the file f=file('poem.txt') # if no mode is specified, 'r'ead mode is assumed by default while True: line=f.readline() if len(line)==0: # Zero length indicates EOF break print line, # Notice comma to avoid automatic newline added by Python f.close() # close the file #!/usr/bin/env python # Filename: pickling.py import cPickle as p #import pickle as p shoplistfile='shoplist.data' # the name of the file where we will store the object shoplist=['apple','mango','carrot'] # Write to the file f=file(shoplistfile,'w') p.dump(shoplist,f) # dump the object to a file f.close() del shoplist # remove the shoplist # Read back from the storage f=file(shoplistfile) storedlist=p.load(f) print storedlist #!/usr/bin/env python # Filename: try_except.py import sys try: s=raw_input('Enter something --> ') except EOFError: print '\nWhy did you do an EOF on me?' sys.exit() # exit the program except: print '\nSome error/exception occurred.' # here, we are not exiting the program print 'Done' #!/usr/bin/env python # Filename: raising.py class ShortInputException(Exception): '''A user-defined exception class.''' def __init__(self,length,atleast): Exception.__init__(self) self.length=length self.atleast=atleast try: s=raw_input('Enter something --> ') if len(s)<3: raise ShortInputException(len(s),3) # Other work can continue as usual here except EOFError: print '\nWhy did you do an EOF on me?' except ShortInputException,x: print 'ShortInputException: The input was of length %d, \ was expecting at least %d' %(x.length,x.atleast) else: print 'No exception was raised.' #!/usr/bin/env python # Filename: finally.py import time try: f=file('poem.txt') while True: # our usual file-reading idiom line=f.readline() if len(line)==0: break time.sleep(2) print line, finally: f.close() print 'Cleaning up...closed the file' #!/usr/bin/env python # Filename: cat.py import sys def readfile(filename): '''Print a file to the standard output.''' f=file(filename) while True: line=f.readline() if len(line)==0: break print line, # notice comma f.close() # Script starts from here if len(sys.argv)<2: print 'No action specified.' sys.exit() if sys.argv[1].startswith('--'): option=sys.argv[1][2:] # fetch sys.argv[1] but without the first two characters if option=='version': print 'Version 1.2' elif option=='help': print '''\ This program prints files to the standard output. Any number of files can be specified. Options include: --version : Prints the version number --help : Display this help''' else: print 'Unknown option.' sys.exit() else: for filename in sys.argv[1:]: readfile(filename) #!/usr/bin/env python # Filename: list_comprehension.py listone=[2,3,4] listtwo=[2*i for i in listone if i>2] print listtwo #!/usr/bin/env python # Filename: lambda.py def make_repeater(n): return lambda s: s*n twice=make_repeater(2) print twice('word') print twice(5)

下载文档,方便阅读与编辑

文档的实际排版效果,会与网站的显示效果略有不同!!

需要 8 金币 [ 分享文档获得金币 ] 0 人已下载

下载文档

相关文档