Python:if 流程控制语句

最近更新时间 2020-01-15 20:35:21

if 语句是大家熟悉的流程控制语句。

if...else

#!/usr/bin/env python3

x = -1
if x < 0:
  print('Negative')
else:
  print('More')
Negative

Elif

#!/usr/bin/env python3

a = 33
b = 33
if b > a:
  print("b is greater than a")
elif a == b:
  print("a and b are equal")
else:
  print("b is less than a")
a and b are equal

短 If 语句

如果只有一条执行语句,可以写到同一行,如下所示:

#!/usr/bin/env python3

if b > a: print("b")

 一条 if ... else 语句,如下所示:

#!/usr/bin/env python3

a = 2
b = 330
print("A") if a > b else print("B")

一条语句执行3个条件判断:

a = 330
b = 330
print("A") if a > b else print("=") if a == b else print("B")
rss_feed