Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Programming with Python - Basic

Programming with Python -ย Basic

Python is a great programming language. It is a complete tutorial of using this programming language.

This slides is split into two parts, and it is the first part. Another part is at: https://speakerdeck.com/mosky/programming-with-python-adv.

Mosky Liu

May 20, 2013
Tweet

More Decks by Mosky Liu

Other Decks in Programming

Transcript

  1. 2 Mosky: โ€ข The examples and the PDF version are

    available at: โ€“ j.mp/mosky-programming-with-python. โ€ข It is welcome to give me any advice of this slide or ask me the answers of the challenges. โ€“ mosky.tw
  2. 3 Mosky โ€ข Projects โ€“ MoSQL mosql.mosky.tw โ€“ Clime clime.mosky.tw

    โ€“ Apt-Pool Apt-Add โ€ฆ โ€ข Pinkoi staff pinkoi.com โ€ข PyCon JP '12 Speaker pycon.jp โ€ข PyCon TW '12 Speaker pycon.tw
  3. 4 Advertisement โ€ข COSCUP 2013 โ€“ coscup.org โ€“ 8/3-4 @

    TICC โ€“ [email protected] m โ€ข PyCon Taiwan 2013 โ€“ pycon.tw โ€“ 5/25-26 @ Sinica โ€“ [email protected]
  4. 5 Topics โ€ข Basic Topics โ€“ Python 2 or 3?

    โ€“ Environment โ€“ hello.py โ€“ Common Types โ€“ Flow Control โ€“ File I/O โ€“ Documentation โ€“ Scope โ€ข Adv. Topics โ€“ Module and Package โ€“ Typing โ€“ Comprehension โ€“ Functional Technique โ€“ Object-oriented Prog. โ€“ Useful Libraries โ€ข Final Project โ€“ A Blog System
  5. 6 An Investigation Do you know _________ ? โ€“ any

    other programming language โ€“ Object-oriented โ€“ Static Typing; Strong and Weak Typing โ€“ Dynamic Typing โ€“ Functor; Closure โ€“ Functional Programming โ€“ Web development
  6. 8 Python 2 or 3? โ€ข Python 2.x โ€“ status

    quo โ€“ 2.7 is end-of-life release โ€“ harder for newcomers โ€“ more third-party lib. โ€“ 2to3.py โ€“ backported features: โ€ข What's News in Python 2.6 docs.python.org/release/2.6.4/whatsnew/2.6.html โ€ข What's News in Python 2.7 docs.python.org/dev/whatsnew/2.7.html โ€ข Python 3.x โ€“ present & future โ€“ under active development โ€“ easier for newcomers โ€“ less third-party lib. โ€“ 3to2.py โ€“ new features: โ€ข What's News in Python 3.0 docs.python.org/py3k/whatsnew/3.0.html
  7. 9 Python 2 or 3? (cont.) โ€ข Use Python 3

    if you can. โ€ข Decide Python 2 or 3 by the libraries you will use. โ€ข Today, we will go ahead with Python 2. And introduce you to the changes in Python3.
  8. 11 On Linux or Mac โ€ข Python is built-in on

    Linux or Mac. โ€ข All you have to do is check the version. Type "python" in any terminal. Python 2.7.3 (default, Sep 26 2012, 21:51:14) [GCC 4.7.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>>
  9. 12 On Windows โ€ข Download the installer from: "http://python.org/download" โ€ข

    Install it. โ€ข Add the Python's PATH. โ€“ Computer โ†’ System Properties โ†’ Advanced system settings โ†’ Advanced tab โ†’ Environment Variables โ†’ System Variables โ†’ find PATH. โ€“ "...;C:\Python27"
  10. 13 Editor / IDE โ€ข The Editors โ€“ Sublime Text

    2 www.sublimetext.com โ€“ VIM wiki.python.org/moin/Vim โ€“ Gnome Text Editor (gedit) โ€“ Notepad++ notepad-plus-plus.org โ€“ ... โ€ข The IDE โ€“ IDLE โ€ข Debian-base: sudo apt-get install idle โ€ข Windows: Use the Start Menu to search "IDLE" โ€ข The others: โ€“ wiki.python.org/moin/PythonEditors
  11. 14 The Python Shell โ€ข Type "python" in terminal. โ€“

    >>> โ€“ ... โ€ข Leaving a shell: โ€“ exit() โ€“ Linux or Mac: Ctrl+D โ€“ Windows: Ctrl+Z<Enter>
  12. 15 The python Command โ€ข Enter Python shell without arguments.

    โ€ข python hello.py โ€ข python -c 'print "Hello, World!"' โ€ข python -m SimpleHTTPServer
  13. 17 hello.py #!/usr/bin/env python # -*- coding: utf-8 -*- #

    file: hello.py def hello(name=None): if name:\n return 'Hello, %s!' % name else: return 'Hello, Python!' โ€ข #! the shebang. โ€ข # -*- defines the encoding of this file. โ€ข # means the comments. โ€ข : starts a block. โ€ข A block uses 4-space indent. โ€ข A statement ends with \n.
  14. 18 hello.py (cont.) if __name__ == '__main__': import sys if

    len(sys.argv) >= 2: print hello(sys.argv[1]) else: print hello() โ€ข __name__, the name of module. โ€ข import is important. The usage: โ€ข import sys โ€ข from sys import argv โ€ข โ€ฆ as alias
  15. 19

  16. 20 The print Statement print 'End with a new line

    char.' print 'Print', 'multiple', 'strings.' print 'End with a space.', print # print a new line char
  17. 21 The print function in Python 3 print('End with a

    new line char.') print('Print', 'multiple', 'strings.') print('End with a space.', end=' ') print() # print a new line char print('End with a space.', end='') print('a', 'b', 'c', seq=',')
  18. 23 Common Types โ€ข Numeric โ€“ Integer 100 โ€“ Float

    10.0 โ€“ Long 100L โ€“ Complex 1+1j โ€“ Boolean True, False โ€ข Sequence โ€“ String "" โ€“ Unicode u"" โ€“ List [,] โ€“ Tuple (,)
  19. 24 Common Types (cont.) โ€ข Mapping โ€“ Dictionary {:} โ€ข

    Set โ€“ Set {,} โ€“ Frozen Set forzenset(...)
  20. 25 Integer, Float and Long โ€ข 3+3 โ€ข 3-3 โ€ข

    3*3 โ€ข 3/3 โ€ข 6/2*(1+2) โ†’ int (as long in C) โ€ข divmod(5, 2) โ†’ tuple (not numeric) โ€ข 5/2 โ†’ int (truncated) โ€ข 5.0/2 โ†’ float (as double in C) โ€ข 5.0//2 โ†’ float (floored) โ€ข 2**1000 โ†’ long (โˆž precision)
  21. 26 Integer and Float in Python 3 โ€ข 3+3 โ€ข

    3-3 โ€ข 3*3 โ€ข 3/3 โ€ข 6/2*(1+2) โ†’ int (โˆž precision) โ€ข divmod(5, 2) โ†’ tuple (not numeric) โ€ข 5/2 โ†’ float โ€ข 5.0/2 โ†’ float (as double in C) โ€ข 5.0//2 โ†’ float (floored) โ€ข 2**1000 โ†’ int (โˆž precision)
  22. 27 Note: The Variables โ€ข x = 1 โ€ข x

    + 1 โ†’ 2 โ€ข y = 2 โ€ข x + y โ†’ 3 โ€ข y += 3 โ†’ 5 โ€ข x < y True โ†’ โ€ข bin(y) โ†’ '0b101' โ€ข bin(y | 0b011) โ†’ '0b111'
  23. 28 A Trap of the Integer โ€ข weight = 49

    โ€ข height = 163 โ€ข bmi = weight / (height / 100) ** 2 โ€ข bmi โ†’ 49 โ€ข (height / 100) โ†’ 1
  24. 29 A Trap of the Integer (cont.) โ€ข weight =

    49.0 โ€ข height = 163.0 โ€ข bmi = weight / (height / 100) ** 2 โ€ข bmi โ†’ 18.442545824080696
  25. 30 Complex โ€ข 1j * 1J โ€ข 1j * complex(0,1)

    โ€ข 3 + 1j*3 โ€ข (3+1j)*3 โ€ข (1+2j)/(1+1j) โ†’ complex โ€ข a = 3.0+4.0j โ€ข float(a) โ†’ TypeError โ€ข a.real โ†’ 3.0 โ€ข a.imag โ†’ 4.0 โ€ข abs(a) # = sqrt(a.real**2 + a.imag**2) 5 โ†’
  26. 31 Boolean โ€ข not False โ€ข True and True โ€ข

    False or True โ€ข False +1 1 โ†’ โ€ข True +1 2 โ†’ Comparison: โ€“ 10 < 100 โ€“ 10 < 10.0 โ€“ 10 <= 10.0 โ€“ 10 == 10.0 โ€“ 10 != 10.0 โ€“ x is y
  27. 32 String and Unicode '...' is equal to "..." String

    (immutable seq.) โ€“ ' ไธญๆ–‡ ' โ€“ ' ๅ—จ๏ผŒ \nPython ๏ผ ' โ€“ r' ๅ—จ๏ผŒ \nPython ๏ผ ' โ€“ ''' ... ''' Unicode (immutable seq.) โ€“ u' ๅ—จ๏ผŒ \nPython ๏ผ ' โ€“ ur' ๅ—จ๏ผŒ \nPython ๏ผ ' โ€“ u''' ... ''' Functions โ€“ ord( 'A') โ€“ chr(65) โ€“ ord(u'ไธญ ') โ€“ unichr(20013); chr(20013) Decoding (String โ†’ Unicode) โ€“ 'ไธญๆ–‡ '.decode('utf-8') โ€“ unicode( 'ไธญๆ–‡ ', 'utf-8') Encoding (Unicode โ†’ String) โ€“ u'ไธญๆ–‡ '.encode('utf-8') โ€“ str(u'ไธญๆ–‡ ') โ€“ str(u'ไธญๆ–‡ ', 'utf-8')
  28. 33 Bytes and String in Python 3 '...' is equal

    to "..." Bytes (immutable seq.) โ€“ b' ไธญๆ–‡ ' โ€“ b' ๅ—จ๏ผŒ \nPython ๏ผ ' โ€“ br' ๅ—จ๏ผŒ \nPython ๏ผ ' โ€“ b''' ... ''' String (immutable seq.) โ€“ ' ๅ—จ๏ผŒ \nPython ๏ผ ' โ€“ r' ๅ—จ๏ผŒ \nPython ๏ผ ' โ€“ ''' ... ''' Functions โ€“ ord(b'A') โ€“ chr(65) โ€“ ord( 'ไธญ ') โ€“ unichr(20013); chr(20013) Decoding (Bytes โ†’ String) โ€“ b'ไธญๆ–‡ '.decode('utf-8') โ€“ str(b'ไธญๆ–‡ ', 'utf-8') Encoding (String โ†’ Bytes) โ€“ 'ไธญๆ–‡ '.encode('utf-8') โ€“ bytes( 'ไธญๆ–‡ ') โ€“ bytes( 'ไธญๆ–‡ ', 'utf-8')
  29. 34 Unicode Does Matter! โ€ข b = ' ไธญๆ–‡ '

    โ€ข len(b) โ†’ 6 โ€ข len(b.decode('utf-8')) โ†’ 2
  30. 35 String and Unicode (cont.) โ€ข They have a lot

    of methods: capitalize center count decode encode endswith expandtabs find rfind format index rindex isalnum isalpha isdigit islower isspace istitle isupper join ljust rjust lower partition rpartition replace split rsplit splitlines startswith rstrip strip lstrip swapcase title translate upper zfill โ€ข ref: docs.python.org/2/library/stdtypes.html#string-methods
  31. 36 String and Unicode (cont.) String formatting: โ€“ % (modulo)

    โ€ข ref: docs.python.org/2/library/stdtypes.html#string-formatting-operations โ€“ str.format โ€ข ref: docs.python.org/2/library/string.html#formatstrings
  32. 37 List and Tuple List (mutable seq.) โ€“ [] โ€“

    ['item'] โ€“ ['s', 100, u'unicode'] โ€“ list('abc') โ€“ 'a b c'.split(' ') โ€“ '\n'.join(['spam', 'eggs']) โ€“ x, y = [1, 2] โ€“ x, y = [y, x] Tuple (seq.) โ€“ tuple() โ€“ ('item', ) โ€“ ('s', 100, u'unicode') โ€“ tuple('abc') โ€“ '\n'.join(('spam', 'eggs')) โ€“ x, y = (1, 2) โ€“ x, y = (y, x)
  33. 38 Sequence Sequence โ€“ x in s # performance? โ€“

    x not in s โ€“ s + t โ€“ s * n, n * s โ€“ s[i] โ€“ s[i:j] โ€“ s[i:j:k] โ€“ len(s) โ€“ s.index(x) โ€“ s.count(x) Mutable Seq. โ€“ s[i] = x โ€“ s[i:j] = t โ€“ del s[i:j] โ€“ s[i:j:k] = t โ€“ s.append(x) โ€“ s.insert(i, x) โ€“ s.pop([i]) โ€“ s.remove(x) # performance? โ€“ s.extend(t) in-place โ€“ s.sort([cmp[, key[, reverse]]]) โ€“ s.sort([key[, reverse]]) # Py 3 โ€“ s.reverse()
  34. 39 Sequence Comparison โ€ข (0, 0, 0) < (0, 0,

    1) โ€ข [0, 0, 0] < [0, 0, 1] โ€ข (0, ) < (0, 0) โ€ข 'ABC' < 'C' < 'Pascal' < 'Python' โ€ข (1, 2, 3) == (1.0, 2.0, 3.0) โ€ข 'A' == 'A' โ€ข 'A' > 65 โ€ข 'A' > 66 โ€ข ('A', ) > (66, )
  35. 40 Sequence Comparison in Python 3 โ€ข (0, 0, 0)

    < (0, 0, 1) โ€ข [0, 0, 0] < [0, 0, 1] โ€ข (0, ) < (0, 0) โ€ข 'ABC' < 'C' < 'Pascal' < 'Python' โ€ข (1, 2, 3) == (1.0, 2.0, 3.0) โ€ข 'A' == 'A' โ€ข 'A' > 65 TypeError โ†’ โ€ข 'A' > 66 TypeError โ†’ โ€ข ('A', ) > (66, ) TypeError โ†’
  36. 41 Sequence (cont.) Slicing and Slice object: โ€“ s =

    range(10) โ€“ t = s โ€“ t[0] = 'A' โ€“ print s โ€“ t is s โ€“ t = s[:] โ€“ t is s โ€“ s = 'I am a str.' โ€“ s[:-3] โ€“ s.reverse() โ†’ TypeError โ€“ s[::-1] โ€“ ''.join(reversed(s)) โ€“ slice(None, None, -1)
  37. 42 Mapping Dict. (mutable map.) โ€“ {} โ€“ {'A ':

    1, 'B': 2, 'C': 3} โ€“ dict({...}) โ€“ dict(A=1, B=2, C=3) โ€“ k = 'ABC' โ€“ v = [1, 2, 3] โ€“ pairs = zip(k, v) โ€“ dict(pairs) โ€“ len(d) โ€“ d[k] โ€“ d[k] = v โ€“ del d[k] โ€“ k in d, k not in d โ€“ d.copy() โ€“ d.get(key[, default]) โ€“ d.setdefault(key[, default]) โ€“ d.items(), d.keys(), d.values() โ€“ d.pop(key[, default) โ€“ d.update([other]) ...
  38. 43 Set Set (mutable set) โ€“ set() โ€“ {'A', 'B',

    'C'} # Py3 โ€“ set('ABC') โ€“ set(['A','B','C']) โ€“ len(s) โ€“ x in s, x not in s โ€“ s.copy() โ€“ s.add(elem) โ€“ s.discard(elem) โ€“ s.pop() โ€“ s |= other โ€“ s &= other โ€“ s | other | ... โ€“ s & other & ... โ€“ s < | <= | == | > = | > other ...
  39. 45 The if Statement if [condition 1]: โ€ฆ elif [condition

    2]: โ€ฆ elif [condition 3]: โ€ฆ else: โ€ฆ [exp. if true] if [condition] else [exp. if false]
  40. 46 Truth Value Testing They are same as False in

    a boolean context: โ€“ None โ€“ False โ€“ Zeros (ex. 0, 0.0, 0L, 0j) โ€“ Empty containers (ex. '', [], {}) โ€“ __nonzero__() or __len__() returns 0 or False
  41. 47 Truth Value Testing (cont.) โ€ข if not None: ...

    โ€ข if not []: ... โ€ข if [0]: ... โ€ข if [[]]: ... โ€ข if "": ... โ€ข if {}: ... โ€ข if not {0: False}: โ€ฆ โ€ฆ
  42. 48 The for Statement for [item] in [iterable]: โ€ฆ for

    i in [0, 1, 2]: print i for i in xrange(3): print i for i in range(3): print i
  43. 49 The for Statement in Python 3 for [item] in

    [iterable]: โ€ฆ for i in [0, 1, 2]: print i for i in xrange(3): print i for i in range(3): print i
  44. 50 The for Statement (cont.) for i in range(1, 3):

    print i for i in range(3, -1, -1): print i s = [...] for i, item in enumerate(s): print i, item s = [1, 2, 3] t = 'xyz' for i, j in zip(s, t): print i, j
  45. 51 The for Statement (cont.) โ€ข It is like for

    โ€ฆ each in other language. โ€“ Note: Python hasn't other for loop. โ€ข It can iterate all of iterable object. โ€“ In other words, the object which defined __iter__. โ€“ ex. sequence, mapping, set, ...
  46. 52 Challenge 1: A Pyramid โ€ข Use for loop to

    build a pyramid on right. โ€“ without limit. โ€“ limit: in two lines โ€ข hint: string formatting * *** ***** *******
  47. 53 Challenge 2-1: Count the Chars โ€ข Use for loop

    to count the sentence on right. โ€“ without limit. โ€“ limit: without if โ€ข hint: use get "Please count the characters here." {'P': 1, ...}
  48. 54 Challenge 2-2: Collect the Chars โ€ข Use for loop

    to collect the chars. โ€“ limit: use setdefault "Here are UPPERCASE and lowercase chars." {'c': ['C', 'c', 'c'], ...}
  49. 55 The while Statement tasks = [...] while tasks: โ€ฆ

    while 1: โ€ฆ โ€ข A infinite loop. โ€ข It is better to use block mechanism in a loop. โ€“ ex. I/O block โ€ข It leaves the loop once the tasks is empty.
  50. 56 The break, continue Statement loop โ€ฆ: if โ€ฆ: break

    loop โ€ฆ: if โ€ฆ: continue โ€ข It continues with the next iteration. โ€ข It terminates a loop.
  51. 57 The break, continue Statement (cont.) โ€ข They do the

    same thing in both C and Python. โ€ข Using break or continue is encouraged. โ€“ take the place of the complicated condition in a while. โ€“ faster, because Python is interpreted. โ€ข Just use them.
  52. 59 The else Clause on Loops loop โ€ฆ: โ€ฆ else:

    โ€ฆ โ€ข No a clause on the if statement! โ€ข If the loop isn't broken by any break statement, the else block is executed. โ€ข It replaces the flags we usually used.
  53. 60 Challenge 3-1: The Primes โ€ข Try to filter the

    primes from [2, 100). โ€“ without limit. โ€“ limit: use loop's else [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
  54. 61 The try Statement try: โ€ฆ except LookupError, e: โ€ฆ

    except (IndexError, KeyError), e: โ€ฆ else: โ€ฆ finally: โ€ฆ
  55. 62 The try Statement in Python 3 try: โ€ฆ except

    LookupError as e: โ€ฆ except (IndexError, KeyError) as e: โ€ฆ else: โ€ฆ finally: โ€ฆ
  56. 63 The try Statement (cont.) โ€ข For avoiding to catch

    the exception we don't expect, you should: โ€“ reduce your code in try block. โ€ข move them to else block. โ€“ make the exception precise in except statement. โ€ข Avoid using Exception. โ€ข ref: docs.python.org/2/library/exceptions.html#exception-hierarchy โ€ข Release the resource in finally block. โ€“ or use context manager โ€“ ex. file, socket, โ€ฆ โ€ข raise SomeError
  57. 64 The def Statement def f(x, y): return (x, y)

    def f(x, y=2): return (x, y) f(1) f(x=1) f(*(1, )) f(**{'x': 1}) f(1, 2) f(y=2, x=1) f(*(1, 2)) f(**{'y': 2, 'x': 1})
  58. 65 The def Statement (cont.) def f(*args): return args def

    f(**kargs): return kargs # f(1, 2) # โ†’ TypeError f(x=1, y=2, z=3) # f(*(1, 2)) # โ†’ TypeError f(**{'x': 1, 'y': 2, 'z': 3}) f(1, 2, 3) # f(y=2, x=1) # โ†’ TypeError f(*(1, 2, 3, 4)) # f(**{'y': 2 ,'x': 1}) # โ†’ TypeError
  59. 66 The def Statement (cont.) def f(x, *args): return x,

    args def f(x, **kargs): return kargs # f(1, 2) # โ†’ TypeError f(x=1, y=2, z=3) # f(*(1, 2)) # โ†’ TypeError f(**{'x': 1, 'y': 2, 'z': 3}) f(1, 2, 3) # f(y=2, x=1) # โ†’ TypeError f(*(1, 2, 3, 4)) # f(**{'y': 2, 'x': 1}) # โ†’ TypeError
  60. 67 The def Statement (cont.) def f(*args, y): return kargs

    def f(*args, **kargs): return args, kargs f(1, 2, 3) f(y=2, x=1) f(*(1, 2, 3, 4)) f(**{'y': 2, 'x': 1}) โ†’ SyntaxError
  61. 68 The def Statement in Python 3 def f(*args, k):

    return kargs def f(*args, k, **kargs): return args, kargs f(1, 2, 3) f(x=1, k=2) f(*(1, 2, 3, 4)) f(**{'x': 1, 'k': 2}) F(1, 2, 3) # f(x=1, k=2) # โ†’ TypeError f(*(1, 2, 3, 4)) # f(**{'x': 1, 'k': 2}) # โ†’ TypeError
  62. 69 The def Statement (cont.) def f(): pass def g():

    pass d = {'x': f, 'y': g} d['x']() โ€ข Python functions are first-class functions. โ€“ It means you can pass functions as arguments, and assign functions to variables. โ€“ It is like the function pointers in C.
  63. 70 An Example of Using while, try and def. #

    file: ex_try.py def take_int(prompt='Give me a int: '): while 1: try: user_input = int(raw_input(prompt)) except ValueError, e: print 'It is not a int!' else: return user_input if __name__ == '__main__': x = take_int() print 'I got a int from user: %d' % x $ python ex_try.py Give me a int: str It is not a int! Give me a int: abc It is not a int! Give me a int: 100 I got a int from user: 100 $
  64. 71 A Trap of the Default Value # file: ex_defval_trap.py

    def f(items=[]): items.append(1) return items if __name__ == '__main__': print f() # -> [1] print f() # -> [1, 1] print f() # -> [1, 1, 1] โ€ข Because the list is created when the function is defined. โ€ข Avoid to use the mutable types as the default value.
  65. 72 Challenge 4: A BMI Calculator โ€ข BMI: Body Mass

    Index โ€“ BMI = weight (KG) รท height (M)2 โ€“ < 18.5 โ†’ Underweight โ€“ [18.5, 25) โ†’ Normal weight โ€“ [25, 30) โ†’ Overweight โ€“ >= 30 โ†’ Obesity โ€ข Write a BMI calculator. โ€“ without limit. โ€“ limit: only one if โ€ข hint: use loop Enter your height (M): 1.63 Enter your weight (KG): 49 --- Your BMI is: 18.44 (Underweight) Ideal weight is between: 49.15 ~ 66.42
  66. 74 The file Object f = open('input.txt') print f.read() f.seek(0)

    for line in f: print line, f.close() f = open('output.txt', 'w') f.write('a line.\n') f.close()
  67. 75 The Context Manager with open('input.txt') as f: for line

    in f: print line, f.close() โ€ข Python 2.5โ†‘ โ€“ Python 2.5.x: from __future__ import with_statement โ€“ Python 2.6โ†‘: It is mandatory.
  68. 76 Challenge 2: Count the Chars (cont.) โ€“ limit 3:

    with the files The path of input: input.txt The path of output: output.txt --- The result was written.
  69. 77 The csv Moudle #!/usr/bin/env python # -*- coding: utf-8

    -*- # file: ex_csv.py import csv with open('ex_csv.csv') as f: for row in csv.reader(f): print row 1, apple 2, orange 3, watermelon ['1', ' apple'] ['2', ' orange'] ['3', ' watermelon']
  70. 78 The os.path Moudle # file: ex_os_path.py from os import

    walk from os.path import join def list_files(path): paths = [] for root, dir_names, file_names in walk(path): for file_name in file_names: paths.append(join(root, file_name)) return paths if __name__ == '__main__': import sys from os.path import abspath, dirname if len(sys.argv) == 2: path = abspath(dirname(sys.argv[1])) for path in list_files(path): print path else: print 'It requires a path as argument.' $ python ex_os_path.py It requires a path as argument. $ python ex_os_path.py . โ€ฆ/1 โ€ฆ/b/4 โ€ฆ/a/2 โ€ฆ/a/3
  71. 80 The help Function โ€ข In Python shell: โ€“ help(open)

    โ€“ dir(open) โ€“ '\n'.join(dir(open)) โ€ข In terminal: โ€“ $ pydoc SimpleHTTPServer โ€“ $ pydoc csv โ€“ $ pydoc os.path
  72. 81 Your Documentation # file: ex_doc.py '''module-level doc.''' def f(x):

    '''A short sentence describes this function. About the parameters, return value or any other detail ... ''' pass $ pydoc ex_doc Help on module ex_doc: NAME ex_doc - module-level doc. FILE /home/mosky/programming-with-python/ex_doc.py FUNCTIONS f(x) A short sentence describes this function. About the parameters, return value or any other detail ...
  73. 83 Scope # file: ex_scope.py x = 'global' def f():

    if 1: x = 'local' return x if __name__ == '__main__': print x print f() $ python ex_scope.py global local $ โ€ข Scopes are decided by functions.
  74. 84 The LEGB Rule # file: ex_LEGB.py global_var = 100

    def f(): enclosed_var = 10 def g(): local_var = 1 return sum([local_var, enclosed_var, global_var]) return g() if __name__ == '__main__': print f() # -> 111 โ€ข return โ€ฆ โ€“ Local (in function) โ€“ Enclosed โ€“ Global โ€“ Built-in
  75. 85 Challenge 3-2: The Primes (cont.) โ€“ limit 1: Sieve

    of Eratosthenes. โ€“ limit 2: use set. [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
  76. 86 Challenge 5: Mix All โ€ข You have many functions

    now. Try to write a CLI program to trigger your functions. โ€“ without limit โ€“ limit: without if. $ python mix.py pyramid 10 โ€ฆ $ python mix.py primes 100 โ€ฆ $ python mix.py bmi 1.63 49 โ€ฆ $ python mix.py blah blah Please check your args.