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!