流程控制之 if 判斷

流程控制之if

if 條件語句

if 條件:
    代碼1
    代碼2
    ...
# 代碼塊:同一縮進級別的代碼,例如代碼1和代碼2是相同縮的代碼,相同縮進的代碼會自上而下的運行.
# if + 條件的語句,只有在條件成立時纔會執行代碼塊
gender = 'female'
age = 21
is_beautiful = True
if gender == 'female' and age == 21 and is_beautiful:
    print('開始表白!')
    
# 開始表白

if...else 條件語句

if 條件:
    代碼1
    代碼2
    ...
else 條件:
    代碼1
    代碼2
    ...
# 當 if 判斷的條件不成立的時候,會執行 else 當中的代碼塊.
gender = 'female'
age = 30
is_beautiful = False
if gender == 'female' and age == 21 and is_beautiful:
    print('開始表白!')
else:
    print('沒有感受!')

# 沒有感受

if...elif...else 條件語句

if 條件:
    代碼1
    代碼2
    ...
elif 條件:
    代碼1
    代碼2
    ...
else:
    代碼1
    代碼2
    ...
# 當 if/elif/else 中有一條成立時只會執行這一條當中的代碼塊,另外兩條都不會執行
gender = 'female'
age = 30
is_beautiful = True
if gender == 'female' and age == 21 and is_beautiful:
    print('開始表白!')
elif gender == 'female' and is_beautiful:
    print('考慮下!')
else:
    print('沒有感受!')

if 的嵌套

gender = 'female'
age = 30
is_beautiful = False
if gender == 'female' and age == 21:
    print('開始表白!')
    if is_beautiful:
        print('加微信!')
    else:
        print('很差意思,打擾了!')
else:
    print('沒有感受!')
相關文章
相關標籤/搜索