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
other programming language โ Object-oriented โ Static Typing; Strong and Weak Typing โ Dynamic Typing โ Functor; Closure โ Functional Programming โ Web development
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
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.
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. >>>
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
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.
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
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=',')
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()
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)
'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 ...
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
โฆ 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, ...
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.
โฆ โข 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.
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
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.
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 $
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.
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
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
'''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 ...