1. 程式人生 > >Python3基礎之(八)if else判斷

Python3基礎之(八)if else判斷

一、基本使用

if condition:
    true_expressions
else:
    false_expressions

當 if 判斷條件為 True,執行 true_expressions 語句; 如果為 False,將執行 else 的內部的 false_expressions

二、例項

x = 1
y = 2
z = 3
if x > y:
    print('x is greater than y')
else:
    print('x is less or equal to y')

在這個例子中,因為 x > y

將會返回 False, 那麼將執行 else 的分支內容。輸出 x is less or equal to y

x = 4
y = 2
z = 3
if x > y:
    print('x is greater than y')
else:
    print('x is less or equal y')

在這裡,因為 condition 條件為 True, 那麼將會輸出 x is greater than y

三、高階主題

對於從其他程式語言轉過來的同學一定非常想知道 python 語言中的三目操作符怎麼使用,很遺憾的是 python 中並沒有類似 condition ? value1 : value2

三目操作符。然後現實中很多情況下我們只需要簡單的判斷 來確定返回值,但是冗長的 if-else 語句似乎與簡單的 python 哲學不一致。別擔心,python 可以通過if-else的行內表示式完成類似的功能。

var = var1 if condition else var2

可以這麼理解上面這段語句,如果 condition 的值為 True, 那麼將 var1 的值賦給 var;如果為 False 則將 var2 的值賦給 var

worked = True
result = 'done' if worked else 'not yet'
print(result)

首先判斷如果 workTrue,那麼將 done 字串賦給 result,否則將 not yet 賦給 result。 結果將輸出 done