Python first day:
1. var
no $, just i, j, a, user_name, _name ...
2. ;
one physical line as a logic line
print "My age is:", age //concat a string and a expression
3. space
indent must be ok, or you will get a error report
4. calculate operator
**: 3**2 == 9
//: 4//3 == 1, 4//3.0 == 1.0
~: ~5 == -6
and: &&
or: ||
not: !
in, not in:
is, is not:
i = i + 1, no ++, --, += ...
5. key word
True, False
6. if, elif, else (no switch)
if a == 1:
...
elif a == 2:
...
else:
...
7. while
isRun = True
while isRun:
...
isRun = False
else:
...
8. for
for i in range(1,5):
print i
else:
print "Done"
// output 1,2,3,4 no 5
9. break, continue //same with c/c++
10. function //like javascript
def max(a, b):
if a > b:
print a
else:
print b
max(4, 9)
11. global
//locale is defaulted
global x, y, z
12. default parameters
def max(a, b=1, c=2) //ok
def max(a=1, b, c) //no
13. key parameters //do not care the position of parameters
def max(a,b=1,c=3)
max(5, c=6)
max(c=2, a=4)
14. DocString
what: the first logic line string of function, module, class
usage:
'''This function named: max
It will return the max number between a and b.'''
example:
def max(a, b):
'''This function named: max
It will return the max number between a and b.'''
print max.__doc__ //print max function's DocString
15. use module
import sys
from sys import argv
from sys import *
16. __name__
if __name__ == '__main__' //write it in every code to aviod run when import
17. define module self
every code just be a module
18. data struct
18.1 list
list = [1,3,5] list.append(4) list.sort()
18.2 tuple
tuple = (1,3,5) //can not be changed
print "My name is: %s, my age is: %d" % ("jakc", 30)
18.3 sequence (list, tuple and string)
sequ[0]
sequ[-1]
sequ[1:3]
sequ[:3]
sequ[1:]
sequ[:]
18.4 dictionary
dic = {'name':'jack', 'age':30}
dic['age']
if dic.has_key('name'):
18.5 copy
list1 = [2,3,4]
list2 = list1 //just alias, list1 and list2 are same memory
list2 = list1[:] //copy list1 elements to list2
19. class
19.1 basic
example:
----------------------------------
class Person:
className = "Person"
__revison = "3.2" //private var
_test = "B" //hope it is private, normal usage, _name
def __init__(self, name):
self.name = name
def sayHi(self):
print 'Hello, my name is', self.name
def __del__(self):
print "Delete some resource"
p = Person('Swaroop')
p.sayHi()
print Person.className
----------------------------------
19.2 inherit
----------------------------------
class Male(Person):
def __init__(self):
...
def __del__(self):
...
class Student(Person,Male):
def __init__(self):
...
def __del__(self):
...
----------------------------------
阅读(418) | 评论(0) | 转发(0) |