赋值语句
普通赋值:
>>> x,y,z = 1,2,3
>>> print x,y,z
1 2 3
>>> x,y = y,x
>>> print x,y
2 1
元组(序列)解包赋值:
>>> a = (1,2,3)
>>> x,y,z = a
>>> x
1
字典赋值:
>>> people = {"name":"cq","age":"20"}
>>> key,value = people.popitem()
>>> key
‘age‘
>>> value
‘20‘
增量赋值:
>>> x = 5
>>> x += 2 #x = x + 2
>>> x
7
>>> x *= 3 #x = x * 3
>>> x
21
条件语句:
记住语句块
if something:
do
elif anothing:
do
else:
do
了解下 布尔运算符,基本的Ture,False
while 循环:(就是给出一个条件,但符合条件时,不断运行程序)
>>> x = 1
>>> while x < 10:
... print x
... x += 1
...
1
2
3
4
5
6
7
8
9
for 循环:(给出一个范围,在范围内循环)
>>> for x in range(10):
... print x
...
0
1
2
3
4
5
6
7
8
9
如果能用for循环,尽量不要用while循环(while容易造成死循环)
跳出循环:
break
>>> for i in range(99,0,-1):
... if i%2 == 0:
... print i
... break
...
98 #从99 倒数到 0 步长为1,遇到第一个符合条件的就跳出循环了,而不会把所有的打印出来,要是没break的话会打印所有的
while True/break
>>> while True:
... word = raw_input(‘enter a word:‘)
... if not word:
... break
... else:
... print ‘the word is‘ + word #当输入一个值时,会打印值,并继续循环要求enter a word 若不输入,则跳出循环
列表推导式---轻量循环:
>>> [x * x for x in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> [x * x for x in range(10) if x%2 == 0]
[0, 4, 16, 36, 64]