控制流分支与循环
1、分支结构
注意:Python 中没有 switch/case 语法
1 # 先定义一个变量 2 some_var = 5 3 # 这里用到了if语句 缩进是Python里的重要属性 4 # 打印 "some_var is smaller than 10" 5 if some_var > 10: 6 print ("some_var is totally bigger than 10.") 7 elif some_var < 10: # This elif clause is optional. 8 print ("some_var is smaller than 10.") 9 else: # This is optional too. 10 print ("some_var is indeed 10.")
2、循环结构
# For 循环用来遍历一个列表 for animal in ["dog", "cat", "mouse"]: # 使用{0}格式 插入字符串 print ("{0} is a mammal".format(animal)) # "range(number)" 返回一个包含数字的列表 for i in range(4): print (i) # "range(lower, upper)" 返回一个从lower数值到upper数值的列表 for i in range(4, 8): print (i) # "range(lower, upper, step)" 返回一个从lower数值到upper步长为step数值的列表 # step 的默认值为1 for i in range(4, 8, 2): print(i) # While 循环会一致执行下去,直到条件不满足 x=0 while x < 4: print(x) x+=1 #x=x+1的简写