-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandout_3b.txt
93 lines (81 loc) · 2.66 KB
/
handout_3b.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
CS 35L Software Construction Laboratory (Lab3-B)
Wed, April 18, 2012, Ver 1.2
Python Reading:
http://docs.python.org/release/2.4.1/tut/tut.html
Ch1 ~ Ch7: must read, read the rest if you want more powerful tools
http://learnpythonthehardway.org
Lots of small exercises, very helpful
Python in Interactive mode
Simply type "python" in the command line
-- It is a good calculator
e.g. >>> import math
>>> math.sqrt ((3 + 4.5) ** 2)
7.5
-- It is a good helper for pyhton
e.g. >>> help(open)
Revisit: Run a (Python) script
Option 1: python myscript.py
Option 2: #! line and chomd +x
Indent is important in Python
something is wrong with the following code
----------------------------------------
def test():
x = 0
for i in range(0, 10):
x += i
print x
test()
----------------------------------------
Python variables
Strong typed
Dynamically, implicitly typed
----------------------------------------
>>> a = '1'
>>> type(a)
<type 'str'>
>>> 2 + a
type error!
----------------------------------------
>>> a = 1
>>> type(a)
<type 'int'>
----------------------------------------
Every variable is an instace of object.
>>> a = dict #type object
>>> a = dict() #a new instance of dict()
>>> a = len #function objec
----------------------------------------
Build-in Data Structure in Python
-- Basic type: int, float
-- Tuple: immutable, (generally) sequences of different kinds of stuff
-- List: mutable, (generally) sequences of the same kind of stuff
Ref: http://news.e-scribe.com/397
-- String: 'string', "string", """string"""
Acutally, there is no character type in Python
>>> type('a')
<type 'str'>
-- Access tuple, list and string using subscriptions
a[1], a[1:], c[2:4], a[-1], a[:-1]
-- Dict: key, value pairs
e.g. d = {}
d["tom"] = 20
d["jerry"] = 19
d.values(), d.keys(), d.items()
The main function in Python
----------------------------------------
#! /usr/bin/env python
def main():
print 'hello world'
if __name__ == "__main__":
main()
----------------------------------------
This line indicates the entry point of the program. If we don't specify
this line, it will execute from the first "module-level" statement.
Best practice:
Always enclose your code in a function, use a main function if you want
to execute from the script directly.
-- Arguments --
The command line arguments can be accessed
using sys.argv. sys.argv is a list, the arguments
will be listed in their original order starting
from sys.argv[1] (sys.argv[0] is the script name).