$30 off During Our Annual Pro Sale. View Details »

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. 1
    Programming with Python
    Basic Topics
    Mosky

    View Slide

  2. 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

    View Slide

  3. 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

    View Slide

  4. 4
    Advertisement
    โ—
    COSCUP 2013
    โ€“ coscup.org
    โ€“ 8/3-4 @ TICC
    โ€“ [email protected]
    m
    โ—
    PyCon Taiwan 2013
    โ€“ pycon.tw
    โ€“ 5/25-26 @ Sinica
    โ€“ [email protected]

    View Slide

  5. 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

    View Slide

  6. 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

    View Slide

  7. 7
    Python 2 or 3?
    in short.

    View Slide

  8. 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

    View Slide

  9. 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.

    View Slide

  10. 10
    Environment
    Is a python in your computer?

    View Slide

  11. 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.
    >>>

    View Slide

  12. 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"

    View Slide

  13. 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

    View Slide

  14. 14
    The Python Shell
    โ—
    Type "python" in terminal.
    โ€“ >>>
    โ€“ ...
    โ—
    Leaving a shell:
    โ€“ exit()
    โ€“ Linux or Mac: Ctrl+D
    โ€“ Windows: Ctrl+Z

    View Slide

  15. 15
    The python Command
    โ—
    Enter Python shell without arguments.
    โ—
    python hello.py
    โ—
    python -c 'print "Hello, World!"'
    โ—
    python -m SimpleHTTPServer

    View Slide

  16. 16
    hello.py
    Say hello to Python.

    View Slide

  17. 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.

    View Slide

  18. 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

    View Slide

  19. 19

    View Slide

  20. 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

    View Slide

  21. 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=',')

    View Slide

  22. 22
    Common Types
    Without it we can do noting

    View Slide

  23. 23
    Common Types
    โ—
    Numeric
    โ€“ Integer 100
    โ€“ Float 10.0
    โ€“ Long 100L
    โ€“ Complex 1+1j
    โ€“ Boolean True, False
    โ—
    Sequence
    โ€“ String ""
    โ€“ Unicode u""
    โ€“ List [,]
    โ€“ Tuple (,)

    View Slide

  24. 24
    Common Types (cont.)
    โ—
    Mapping
    โ€“ Dictionary {:}
    โ—
    Set
    โ€“ Set {,}
    โ€“ Frozen Set
    forzenset(...)

    View Slide

  25. 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)

    View Slide

  26. 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)

    View Slide

  27. 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'

    View Slide

  28. 28
    A Trap of the Integer
    โ—
    weight = 49
    โ—
    height = 163
    โ—
    bmi = weight / (height / 100) ** 2
    โ—
    bmi
    โ†’ 49
    โ—
    (height / 100)
    โ†’ 1

    View Slide

  29. 29
    A Trap of the Integer (cont.)
    โ—
    weight = 49.0
    โ—
    height = 163.0
    โ—
    bmi = weight / (height / 100) ** 2
    โ—
    bmi
    โ†’ 18.442545824080696

    View Slide

  30. 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
    โ†’

    View Slide

  31. 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

    View Slide

  32. 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')

    View Slide

  33. 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')

    View Slide

  34. 34
    Unicode Does Matter!
    โ—
    b = ' ไธญๆ–‡ '
    โ—
    len(b)
    โ†’ 6
    โ—
    len(b.decode('utf-8'))
    โ†’ 2

    View Slide

  35. 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

    View Slide

  36. 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

    View Slide

  37. 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)

    View Slide

  38. 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()

    View Slide

  39. 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, )

    View Slide

  40. 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
    โ†’

    View Slide

  41. 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)

    View Slide

  42. 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])
    ...

    View Slide

  43. 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
    ...

    View Slide

  44. 44
    Flow Control
    in Python is grace and easy to learn.

    View Slide

  45. 45
    The if Statement
    if [condition 1]:
    โ€ฆ
    elif [condition 2]:
    โ€ฆ
    elif [condition 3]:
    โ€ฆ
    else:
    โ€ฆ
    [exp. if true] if [condition] else [exp. if false]

    View Slide

  46. 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

    View Slide

  47. 47
    Truth Value Testing (cont.)
    โ—
    if not None: ...
    โ—
    if not []: ...
    โ—
    if [0]: ...
    โ—
    if [[]]: ...
    โ—
    if "": ...
    โ—
    if {}: ...
    โ—
    if not {0: False}: โ€ฆ
    โ€ฆ

    View Slide

  48. 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

    View Slide

  49. 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

    View Slide

  50. 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

    View Slide

  51. 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, ...

    View Slide

  52. 52
    Challenge 1: A Pyramid
    โ—
    Use for loop to build a
    pyramid on right.
    โ€“ without limit.
    โ€“ limit: in two lines
    โ—
    hint: string formatting
    *
    ***
    *****
    *******

    View Slide

  53. 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, ...}

    View Slide

  54. 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'], ...}

    View Slide

  55. 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.

    View Slide

  56. 56
    The break, continue Statement
    loop โ€ฆ:
    if โ€ฆ: break
    loop โ€ฆ:
    if โ€ฆ: continue
    โ—
    It continues with the
    next iteration.
    โ—
    It terminates a loop.

    View Slide

  57. 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.

    View Slide

  58. 58
    The pass Statement
    โ—
    Do nothing.

    View Slide

  59. 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.

    View Slide

  60. 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]

    View Slide

  61. 61
    The try Statement
    try:
    โ€ฆ
    except LookupError, e:
    โ€ฆ
    except (IndexError, KeyError), e:
    โ€ฆ
    else:
    โ€ฆ
    finally:
    โ€ฆ

    View Slide

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

    View Slide

  63. 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

    View Slide

  64. 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})

    View Slide

  65. 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

    View Slide

  66. 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

    View Slide

  67. 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

    View Slide

  68. 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

    View Slide

  69. 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.

    View Slide

  70. 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
    $

    View Slide

  71. 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.

    View Slide

  72. 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

    View Slide

  73. 73
    File I/O
    Open anything with the open.

    View Slide

  74. 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()

    View Slide

  75. 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.

    View Slide

  76. 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.

    View Slide

  77. 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']

    View Slide

  78. 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

    View Slide

  79. 79
    Documentation
    The documentation is everywhere.

    View Slide

  80. 80
    The help Function
    โ—
    In Python shell:
    โ€“ help(open)
    โ€“ dir(open)
    โ€“ '\n'.join(dir(open))
    โ—
    In terminal:
    โ€“ $ pydoc SimpleHTTPServer
    โ€“ $ pydoc csv
    โ€“ $ pydoc os.path

    View Slide

  81. 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 ...

    View Slide

  82. 82
    Scope
    Where is the x?

    View Slide

  83. 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.

    View Slide

  84. 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

    View Slide

  85. 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]

    View Slide

  86. 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.

    View Slide

  87. 87
    Adv. Topics
    There is another slide.

    View Slide