Skip to content

2 、控制语句


一、条件语句🧀

1
2
3
4
5
6
if <condition_1>:
    <statement_block_1>
elif (condition_2):
    <statement_block_2>
else:
    <statement_block_3>

二、循环语句🧀

1、while🧀

while <condition>
    <statement(s)>

while后条件为false时,可以结合使用else

1
2
3
4
while <expr>:
    <statement(s)>
else:
    <additional_statement(s)>

2、for🧀

  • for 循环可以遍历任何可迭代对象,如一个列表或者一个字符串
1
2
3
4
for <variable> in <sequence>:
    <statement(s)>
else:
    <statement(s)>

range()

1
2
3
range(stop)          # 从 0 开始,到 stop(不包括 stop)
range(start, stop)   # 从 start 开始,到 stop(不包括 stop)
range(start, stop, step)  # 从 start 开始,到 stop(不包括 stop),步长为 step