1 people = 30 2 cars = 40 3 buses = 15 4 5 if cars > people: 6 print "We should take the cars." 7 elif cars < people: 8 print "We should not take the cars." 9 else: 10 print "We can‘t decide." 11 12 if buses > cars: 13 print "That‘s too many buses." 14 elif buses < cars: 15 print "Maybe we chould take the buses." 16 else: 17 print "We still can‘t decide." 18 19 if people > buses: 20 print "Alright, let‘s just take the buses." 21 else: 22 print "Fine, let‘s stay home then."
Study Drills
1、Try to guess what elif and else are doing.
elif & else 是子句,因为它们不能独立使用,两者都是出现在if、for、while语句内部的。else子句可以增加一种选择;而elif子句则是需要检查更多条件时会被使用,与if和else一同使用,elif是else if 的简写。
1 num = 0 2 if num > 0 : 3 print ‘这个数比0大‘ 4 elif num < 0 : 5 print ‘这个数比0小‘ 6 else : 7 print ‘这个数是0‘
程序分别对if和elif做了判断,如果条件不为真,则输出else的语句块内容。程序运行结果是:这个数是0
需留意:
1、else、elif为子块,不能独立使用
2、一个if语句中可以包含多个elif语句,但结尾只能有一个else语句
原文:http://www.cnblogs.com/LevenLau/p/6366484.html