python基礎-11流程控制之if判斷

if

if表示if成立代碼成立會幹什麼。python

if 條件:
    代碼1
    代碼2
    代碼3
    ...
# 代碼塊(同一縮進級別的代碼,例如代碼一、代碼2和代碼3是相同縮進的代碼,這三個代碼組合在一塊兒就是一個代碼塊,相同縮進的代碼會自上而下的運行)

cls = 'human'
gender = 'female'
age = 18

if cls == 'human' and gender == 'female' and age > 16 and age < 22:
    print('開始表白')

print('end...')

# 輸出結果
# 開始表白
# end...


if...else

if 條件:
    代碼1
    代碼2
    代碼3
    ...
else:
    代碼1
    代碼2
    代碼3
    ...

if...else表示if成立代碼成立會幹什麼,else不成立會幹什麼。code

cls = 'human'
gender = 'female'
age = 38

if cls == 'human' and gender == 'female' and age > 16 and age < 22:
    print('開始表白')
else:
    print('阿姨好')
# 結果
# 阿姨好


if...elif...else

if 條件1:
    代碼1
    代碼2
    代碼3
    ...
elif 條件2:
    代碼1
    代碼2
    代碼3
    ...
elif 條件3:
    代碼1
    代碼2
    代碼3
    ...
...
else:
    代碼1
    代碼2
    代碼3
    ...

if...elif...else表示if條件1成立幹什麼,elif條件2成立幹什麼,elif條件3成立幹什麼,elif...不然幹什麼。class

cls = 'human'
gender = 'female'
age = 28

if cls == 'human' and gender == 'female' and age > 16 and age < 22:
    print('開始表白')
elif cls == 'human' and gender == 'female' and age > 22 and age < 30:
    print('考慮下')
else:
    print('阿姨好')


if的嵌套

if裏面放if ---> 遵循if中同等結構對應就好
列子co

# if的嵌套
cls = 'human'
gender = 'female'
age = 18
is_success = False

if cls == 'human' and gender == 'female' and age > 16 and age < 22:
    print('開始表白')
    if is_success:
        print('那咱們一塊兒走吧...')
    else:
        print('我逗你玩呢')
else:
    print('阿姨好')
相關文章
相關標籤/搜索