扫码一下
查看教程更方便
可能会出现在条件解析为真后您想检查另一个条件的情况。在这种情况下,您可以使用嵌套的if 结构。在嵌套if结构中,你可以有一个,IF... ELIF ...ELSE 构造里面写另一个 IF... ELIF...ELSE 结构。
嵌套的if...elif...else构造的语法可能是 -
if expression1:
statement(s)
if expression2:
statement(s)
elif expression3:
statement(s)
elif expression4:
statement(s)
else:
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!