python——语句

来源:互联网 发布:java 贴吧 编辑:程序博客网 时间:2024/06/06 18:41

条件语句

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 = 90if score >= 90:    print 'excellent'score = 80if score >= 60:    print 'pass'else:    print 'fail'score = 70if 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 = 0for i in range(11):    sum = sum + iprint sum

while

i = 0sum = 0while i < 11:    sum = sum + i    i = i + 1print sum
注:不支持do while

空语句

pass

条件语句

salary = 15000if 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 Falsex = 0judgeCondition(x)x = 1judgeCondition(x)x = ''judgeCondition(x)x = "abc"judgeCondition(x)x = ()judgeCondition(x)x = (1, 2)judgeCondition(x)x = NonejudgeCondition(x)
output:
FalseTrueFalseTrueFalseTrueFalse
单独变量作为判断条件时,有以下情况:
  • 整型&浮点型: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 = 0while index < len(namelist):    print namelist[index]    index = index + 1
0 0
原创粉丝点击