流程控制Control Flow

if 语句if Statements

在 python 中,没有 switch 语句,只有 if 语句

基本款

跟一般语言的 if 语句一样

1 2 3 4
price = 230if price > 200: price -= 10print(price)

else 款

可以有最多一个 else 分支

1 2 3 4 5 6
price = 230if price > 200: price -= 10else: price += 10print(price)

else if 款

可以有多个 else if 分支

1 2 3 4 5 6 7 8
price = 230if price > 200: price -= 10elif price > 100: price += 2else: price += 10print(price)
广告

for 语句for Statements

基本款

for 只能用于遍历一个序列(Sequence)中的元素

1 2 3 <
numbers = [6, 7, 3, 8, 4]for number in numbers: price(number, end="")67384

循环序列

如果想达到 C 或 Java 语言中 如下效果

1 2 3
for (int i = 0; i < 10; i++) { System.out.println(i);}

在 python 中,需要使用 range 生成 区间 作为 序列

1 2
for i in range(10): print(i)
广告

while 语句while Statements

在 python 中没有 do while 语句,只有 while 语句

基本款

1 2 3 4 5 <
value = 67384while value > 0: digit = value % 10 print(digit, end="") value = value // 1048376

死循环款

1 2 3
while True: value = int(input()) print(value + 1)
广告

循环控制break, continue, and else

可以使用 break, continue 和 else 对 for 或者 while 循环进行细微的控制

使用 break

使用 break 可以打断循环

1 2 3 4 < < < <
for i in range(10): if i > 3: break print(i)0123

使用 continue

使用 continue 可以 立刻进入下次循环

1 2 3 4 < < <
for i in range(6): if i % 2 == 0: continue print(i)135

使用 else

在 python 中,for 和 while 语句可以叠加 else

如果在 循环中,没有被 break 打断过,就会执行 else,否则不会

1 2 3 4 5 6 7 8 <
numbers = [6, 7, 3, 8, 4]for number in numbers: if number == 0: existZero = True breakelse: existZero = Falseprint(existZero)False
广告

ZZAX 微信公众

文档一更新,立刻告诉你