1. if 语句
1) if语句
if expresion:
if_suite
当expresion 非0 或者为布尔值true时执行子代码块if_suite(是缩进相同的一条或者多条语句,不需要大括号)
2)if else语句
if expresion :
else:if_suite
else_suite
else:3)elif 语句
if expresion1:
elif expresion2:if_suite
elif_suite
else_suite
2.while语句
while expresion :
while_suite
while_suite会被循环执行,直到expresion 为0 或者为布尔值false
count = 0
a=raw_input("输入a的值:")
while count < 3 :
if int(a) > 0:
print "%d >0 "%(int(a))
elif int(a) == 0:
print "%d == 0 "%(int(a))
else:
print "%d < 0 "%(int(a))
count +=1
a=raw_input("输入a的值:")
输入a的值:0
0 == 0
输入a的值:1
1 >0
输入a的值:-1
-1 < 0
3.for循环
1) python中的for循环与传统的for循环(计数器循环)不同,更像shell中的foreach迭代,可以把序列和迭代器作为参数,每次迭代一个对象
alist = ['name','felix','age',25]
for item in alist:
print item
for item in alist:
print item,
print
raw_input("pause!")
print会默认给没一行添加换行符,在后面添加逗号(,)会改变这种行为,没任何参数的print输出一个换行符
name
felix
age
25
name felix age 25
pause!
2)内建range()函数,根据提供的范围生成递增计数的列表
for eachnum in range(10):
print eachnum
0
1
2
3
4
5
6
7
8
9
3)迭代字符串,range()和len()常用于字符串索引,但只能要么循环索引,要么循环元素,enumerate()同时能做到
#迭代字符串
for c in 'abcdef':
print c
a
b
c
d
e
f
name = 'felix'
for i in range(len(name)):
print i,name[i]
0 f
1 e
2 l
3 i
4 x
day = 'monday'
for i,ch in enumerate(day):
print i,ch
0 m
1 o
2 n
3 d
4 a
5 y
4.列表解析
使用for循环在一行中把所有值放到一个列表中
square = [x**2 for x in range(4)]
print square
[0, 1, 4, 9]
使用for循环把符合条件的元素放入列表
specialsquare = [x**2 for x in range(8) if not x%2 ]
print specialsquare
[0, 4, 16, 36]