Python嵌套IF語句
可能有這樣一種情況,當你想檢查其他條件後一個條件解析為真。在這種情況下,可以使用嵌套的if結構。
在嵌套的 if 語句結構,可以在一個 if... elif... else 結構裡麵可有另外一個 if... elif... else 結構。
語法:
嵌套 if...elif...else 結構的語法可以是:
if expression1: statement(s) if expression2: statement(s) elif expression3: statement(s) else statement(s) elif expression4: statement(s) else: statement(s)
例如:
#!/usr/bin/python var = 100 if var < 200: print "Expression value is less than 200" if var == 150: print "Which is 150" elif var == 100: print "Which is 100" elif var == 50: print "Which is 50" elif var < 50: print "Expression value is less than 50" else: print "Could not find true expression" print "Good bye!"
當執行上麵的代碼,它會產生以下結果:
Expression value is less than 200 Which is 100 Good bye!