一、变量、运算和表达式
首先看一下这个表格:
需要注意的是:5/2=2; 5.0/2=2.5;
compute
print 'Please input a number:'
number = int(raw_input)
number += 1
print number**2
print number and 1
print number or 1
print not number
二、数据类型
1、数字
通常的int、long、float等等都支持。而且会看你的具体数字来定义变量的类型。
如下:
### type of value #######
# int, long, float
# do not need to define the type of value, python will
# do this according to your value
num = 1 # stored as int type
num = 111111111 # stored as long int type
num = 1.0 # stored as float type
num = 12L # L stands for long type
num = 1 + 12j # j stands for complex type
num = '1' # string type
2、字符串
单引号,双引号和三引号都可以用来定义字符串。三引号可以定义特别格式的字符串。字符串作为一种序列类型,支持像Matlab一样的索引访问和切片访问。
num = "1" # string type
num = "Let's go" # string type
num = "He's \"old"" # string type
mail = """
xiaoyi:
hello
I am you!
""" # special string format
string = 'xiaoyi' # get value by index
copy = string[0] + string[1] + string[2:6] # note: [2:6] means [2 5] or[2 6)
copy = string[:4] # start from 1
copy = string[2:] # to end
copy = string[::1] # step is 1, from start to end
copy = string[::2] # start is 2
copy = string[-1] # means 'i', the last one
copy = string[-4:-2:-1] # means 'yoa', -1 step controls direction
memAddr = id(num) # id(num) get the memory address of num
type(num) # get the type of num
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
3、元祖
元祖tuple用()来定义。相当于一个可以存储不同类型数据的一个数组。可以用索引来访问,但需要注意的一点是,里边的元素不能被修改。
firstName = 'Zou'
lastName = 'Xiaoyi'
len(string)
name = firstName + lastName
firstName * 3
'Z' in firstName
string = '123'
max(string)
min(string)
cmp(firstName, lastName)
user = ("xiaoyi", 25, "male")
name = user[0]
age = user[1]
gender user[2]
t1 = ()
t2 = (2, )
user[1] = 26
name, age, gender = user
a, b, c = (1, 2, 3)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
4、列表
列表list用[]来定义,它和元祖的功能一样,不同的一点是,里边的元素可以修改。List是一个类,支持很多该类定义的方法,这些方法可以用来对list进行操作。
userList = ["xiaoyi", 25, "male"]
name = userList[0]
age = userList[1]
gender = userList[2]
userList[3] = 88888 # error! access out of range, this is different with Matlab
userList.append(8888) # add new elements
"male" in userList # search
userList[2] = 'female' # can modify the element (the memory address not change)
userList.remove(8888) #remove element
userList.remove(userList[2]) #remove element
del(userList[1]) # use system operation api
## help(list.append)
######## object and class ######
## object = property + method
## python treats anything as class, here the list type is a class,
## when we define a list "userList", so we got a object, and we use
## its method to operate the elements
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
5、字典
字典dictionary用{}来定义。它的优点是定义像key-value这种键值非的结构,就像struct结构体的功能一样。它也支持字典类型支持的方法进行创建和操作。
######## dictionary type ######
## define this type using {}
item = ['name', 'age', 'gender']
value = ['xiaoyi', '25', 'male']
zip(item, value) # zip() will produce a new list:
# [('name', 'xiaoyi'), ('age', '25'), ('gender', 'male')]
# but we can not define their corresponding relationship
# and we can define this relationship use dictionary type
# This can be defined as a key-value manner
# dic = {key1: value1, key2: value2, ...}, key and value can be any type
dic = {'name': 'xiaoyi', 'age': 25, 'gender': 'male'}
dic = {1: 'zou', 'age':25, 'gender': 'male'}
# and we access it like this: dic[key1], the key as a index
print dic['name']
print dic[1]
# another methods create dictionary
fdict = dict(['x', 1], ['y', 2]) # factory mode
ddict = {}.fromkeys(('x', 'y'), -1) # built-in mode, default value is the same which is none
# access by for circle
for key in dic
print key
print dic[key]
# add key or elements to dictionary, because dictionary is out of sequence,
# so we can directly and a key-value pair like this:
dic['tel'] = 88888
# update or delete the elements
del dic[1] # delete this key
dic.pop('tel') # show and delete this key
dic.clear() # clear the dictionary
del dic # delete the dictionary
dic.get(1) # get the value of key
dic.get(1, 'error') # return a user-define message if the dictionary do not contain the key
dic.keys()
dic.values()
dic.has_key(key)
# dictionary has many operations, please use help to check out
- 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
- 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
三、流程控制
在这块,Python与其它大多数语言有个非常不同的地方,Python语言使用缩进块来表示程序逻辑(其它大多数语言使用大括号等)。例如:
if age < 21:
print("你不能买酒。")
print("不过你能买口香糖。")
print("这句话处于if语句块的外面。")
这个代码相当于c语言的:
if (age < 21)
{
print("你不能买酒。")
print("不过你能买口香糖。")
}
print("这句话处于if语句块的外面。")
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
可以看到,Python语言利用缩进表示语句块的开始和退出(Off-side规则),而非使用花括号或者某种关键字。增加缩进表示语句块的开始(注意前面有个:号),而减少缩进则表示语句块的退出。根据PEP的规定,必须使用4个空格来表示每级缩进(不清楚4个空格的规定如何,在实际编写中可以自定义空格数,但是要满足每级缩进间空格数相等)。使用Tab字符和其它数目的空格虽然都可以编译通过,但不符合编码规范。
为了使我们自己编写的程序能很好的兼容别人的程序,我们最好还是按规范来,用四个空格来缩减(注意,要么都是空格,要是么都制表符,千万别混用)。
1、 if-else
if-else 用来判断一些条件,以执行满足某种条件的代码。
if expression:
statement(s)
if expression:
statement(s)
if 1<2:
print 'ok, '
print 'yeah'
if True:
print 'true'
def fun():
return 1
if fun():
print 'ok'
else:
print 'no'
con = int(raw_input('please input a number:'))
if con < 2:
print 'small'
elif con > 3:
print 'big'
else:
print 'middle'
if 1 < 2:
if 2 < 3:
print 'yeah'
else:
print 'no'
print 'out'
else:
print 'bad'
if 1<2 and 2<3 or 2 < 4 not 0:
print 'yeah'
- 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
- 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
2、 for
for的作用是循环执行某段代码。还可以用来遍历我们上面所提到的序列类型的变量。
for iterating_val in sequence:
statements(s)
for i in "abcd":
print i
for i in [1, 2, 3, 4]:
print i
range(5)
range(1, 5)
range(1, 10, 2)
for i in range(1, 100, 1):
print i
fruits = ['apple', 'banana', 'mango']
for fruit in range(len(fruits)):
print 'current fruit: ', fruits[fruit]
dic = {1: 111, 2: 222, 5: 555}
for x in dic:
print x, ': ', dic[x]
dic.items()
for key,value in dic.items():
print key, ': ', value
else:
print 'ending'
import time
for x in range(1, 11):
print x
time.sleep(1)
if x == 3:
pass
if x == 2:
continue
if x == 6:
break
if x == 7:
exit()
print '#'*50
- 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
- 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
3、while
while的用途也是循环。它首先检查在它后边的循环条件,若条件表达式为真,它就执行冒号后面的语句块,然后再次测试循环条件,直至为假。冒号后面的缩近语句块为循环体。
######## procedure control #####
## while
while expression:
statement(s)
while True:
print 'hello'
x = raw_input('please input something, q for quit:')
if x == 'q':
break
else:
print 'ending'
4、switch
其实Python并没有提供switch结构,但我们可以通过字典和函数轻松的进行构造。例如:
from __future__ import division
def add(x, y):
return x + y
def sub(x, y):
return x - y
def mul(x, y):
return x * y
def div(x, y):
return x / y
operator = {"+": add, "-": sub, "*": mul, "/": div}
operator["+"](1, 2)
operator["%"](1, 2)
operator.get("+")(1, 2)
def cal(x, o, y):
print operator.get(o)(x, y)
cal(2, "+", 3)
- 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
- 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
四、函数
1、自定义函数
在Python中,使用def语句来创建函数:
def functionName(parameters):
bodyOfFunction
def add(a, b):
return a+b
a = 100
b = 200
sum = add(a, b)
def add(a = 1, b = 2):
return a+b
add()
add(2)
add(y = 1)
add(3, 4)
val = 100
def fun():
print val
print val
def fun():
a = 100
print a
print a
def fun():
global a = 100
print a
print a
fun()
print a
def fun(x):
print x
fun(10)
fun('hello')
fun(('x', 2, 3))
fun([1, 2, 3])
fun({1: 1, 2: 2})
def fun(x, y):
print "%s : %s" % (x,y)
fun('Zou', 'xiaoyi')
tu = ('Zou', 'xiaoyi')
fun(*tu)
def fun(name = "name", age = 0):
print "name: %s" % name
print "age: " % age
dic = {name: "xiaoyi", age: 25}
fun(**dic)
fun(age = 25, name = 'xiaoyi')
def fun(x, *args):
print x
print args
fun(10)
fun(10, 12, 24)
def fun(x, **args):
print x
print args
fun(10)
fun(x = 10, y = 12, z = 15)
def fun(x, *args, **kwargs):
print x
print args
print kwargs
fun(1, 2, 3, 4, y = 10, z = 12)
- 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
- 94
- 95
- 96
- 97
- 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
- 94
- 95
- 96
- 97
2、Lambda函数
Lambda函数用来定义一个单行的函数,其便利在于:
fun = lambda x,y : x*y
fun(2, 3)
def fun(x, y):
return x*y
def recursion(n):
if n > 0:
return n * recursion(n-1)
def mul(x, y):
return x * y
numList = range(1, 5)
reduce(mul, numList)
reduce(lambda x,y : x*y, numList)
numList = [1, 2, 6, 7]
filter(lambda x : x % 2 == 0, numList)
print [x for x in numList if x % 2 == 0]
map(lambda x : x * 2 + 10, numList)
print [x * 2 + 10 for x in numList]
- 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
- 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
3、Python内置函数
Python内置了很多函数,他们都是一个个的.py文件,在python的安装目录可以找到。弄清它有那些函数,对我们的高效编程非常有用。这样就可以避免重复的劳动了。下面也只是列出一些常用的:
## built-in function of python ####
## if do not how to use, please use help()
abs, max, min, len, divmod, pow, round, callable,
isinstance, cmp, range, xrange, type, id, int()
list(), tuple(), hex(), oct(), chr(), ord(), long()
callable # test a function whether can be called or not, if can, return true
# or test a function is exit or not
isinstance # test type
numList = [1, 2]
if type(numList) == type([]):
print "It is a list"
if isinstance(numList, list): # the same as above, return true
print "It is a list"
for i in range(1, 10001) # will create a 10000 list, and cost memory
for i in xrange(1, 10001)# do not create such a list, no memory is cost
## some basic functions about string
str = 'hello world'
str.capitalize() # 'Hello World', first letter transfer to big
str.replace("hello", "good") # 'good world'
ip = "192.168.1.123"
ip.split('.') # return ['192', '168', '1', '123']
help(str.split)
import string
str = 'hello world'
string.replace(str, "hello", "good") # 'good world'
## some basic functions about sequence
len, max, min
# filter(function or none, sequence)
def fun(x):
if x > 5:
return True
numList = [1, 2, 6, 7]
filter(fun, numList) # get [6, 7], if fun return True, retain the element, otherwise delete it
filter(lambda x : x % 2 == 0, numList)
# zip()
name = ["me", "you"]
age = [25, 26]
tel = ["123", "234"]
zip(name, age, tel) # return a list: [('me', 25, '123'), ('you', 26, '234')]
# map()
map(None, name, age, tel) # also return a list: [('me', 25, '123'), ('you', 26, '234')]
test = ["hello1", "hello2", "hello3"]
zip(name, age, tel, test) # return [('me', 25, '123', 'hello1'), ('you', 26, '234', 'hello2')]
map(None, name, age, tel, test) # return [('me', 25, '123', 'hello1'), ('you', 26, '234', 'hello2'), (None, None, None, 'hello3')]
a = [1, 3, 5]
b = [2, 4, 6]
def mul(x, y):
return x*y
map(mul, a, b) # return [2, 12, 30]
# reduce()
reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) # return ((((1+2)+3)+4)+5)