条件语句
if condition:
#code list
[
elif condition_1:
#code list
]
...
[
elif condition_n:
#code list
]
[
else:
#code list
]
注1:[]表示optional
注2:elif不能拆分为else if
注3:不支持switch
score = 90
if score >= 90:
print 'excellent'
score = 80
if score >= 60:
print 'pass'
else:
print 'fail'
score = 70
if score >= 90:
print 'A'
elif score >= 80:
print 'B'
elif score >= 70:
print 'C'
elif score >= 60:
print 'D'
else:
print 'E'
循环语句
for...in
sum = 0
for i in range(11):
sum = sum + i
print sum
while
i = 0
sum = 0
while i < 11:
sum = sum + i
i = i + 1
print sum
注:不支持do while
空语句
pass
条件语句
salary = 15000
if salary >= 30000:
print 'very high income'
elif salary >= 20000:
print 'high income'
elif salary >= 10000:
print 'middle income'
else:
print 'low income'
注意:
- elif意义是else if,但不能写成else if
- elif分支optional
- else分支optional
def judgeCondition(x):
if x:
print True
else:
print False
x = 0
judgeCondition(x)
x = 1
judgeCondition(x)
x = ''
judgeCondition(x)
x = "abc"
judgeCondition(x)
x = ()
judgeCondition(x)
x = (1, 2)
judgeCondition(x)
x = None
judgeCondition(x)
output:
False
True
False
True
False
True
False
单独变量作为判断条件时,有以下情况:
- 整型&浮点型:0为False,非0为True
- 字符串:空串为False,非空串为True
- list&tuple&dict&set:空为False,非空为True
循环语句
for...in
namelist = ['tom', 'jack', 'martin']
for name in namelist:
print name
while
namelist = ['tom', 'jack', 'martin']
index = 0
while index < len(namelist):
print namelist[index]
index = index + 1