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