分支和循环branch and loop
分支结构
if
①判断一个条件,如果这个条件成立,就执行其包含的某条语句或某个代码块
if condition:
statement(s)
②判断一个条件:如果条件成立,就执行其包含的某条语句或某个代码块;如果条件不成立,就执行另外的某条语句或某个代码块
if condition:
statement(s)
else:
statement(s)
③判断多个条件,如果第1个条件不成立,则继续判断第2个条件,如果第2个条件还不成立,就接着判断第3个条件……
if condition1:
statement(s)
elif condition2:
statement(s)
elif conditions3:
statement(s)
···
④第4 种是在第3中的情况下添加一个else,表示上面所有的条件均不成立的情况下,执行某条语句或某个代码块
if condition1:
statement(s)
elif condition2:
statement(s)
elif conditions3:
statement(s)
···
else:
statement(s)
⑤条件表达式
条件成立时执行的语句 if condition else 条件不成立时执行的语句
分支结构的嵌套
nested branches
循环结构
①while
while condition:
statement(s)
死循环
break
continue
else
循环结构的嵌套nested loop
②for
for 变量 in 可迭代对象:
statement(s)