《笨方法学 Python 3》30. else和if

基础练习:

people = 30
cars = 40
trucks = 15

if cars > people:
	print("We should take the cars.///我们应该乘汽车。") 
elif cars < people:
	print("We should not take the cars.///我们不应该乘汽车。")
else:
	print("We can't decide.///我们无法决定。")

if trucks > cars:
	print("That's too many trucks.///卡车太多了。")
elif trucks < cars:
	print("Maybe we could take the trucks.///也许我们可以坐卡车。")
else:
	print("We still can't decide.///我们还是无法决定。")

if people > trucks:
	print("Alright,let's just take the trucks.///好吧,我们坐卡车吧。")
else:
	print("Fine, let's stay home then.///好吧,那我们就呆在家里吧。")

结果: 


巩固练习:

1. 猜想一下elif 和 else 的功能。

先看一段代码:

scores = int(input("请输入成绩!"))

if scores >= 95:
	print("优秀!")
elif scores >= 80:
	print("良好!")
elif scores >= 60:
	print("合格!")
else:
	print("不及格!")

结果:

详解:

else和elif语句都是子句,因为它们不能独立使用,两者都是出现在if、for、while语句内部的。

elif 是 else if 的简写,elif 是 if 语句的条件补充,一个 if 语句中中能存在一个 if 判断,可以用 elif 来判断更多的条件。

一个if语句中可以包含多个elif语句,但结尾只能有一个else语句。

从上面的代码中可以发现,if 语句有个特点:它是从上往下判断,如果在某个判断上是True,把该判断对应的语句执行后,就忽略掉剩下的 elif 和 else 。如果 if 和 elif 都判断为False,则执行 else ,else无法设置判断条件,所以 if 、elif 都为假时,else子句块就会被无条件输出。

if 判断条件还可以简写:

只要x是非零数值、非空字符串、非空list,就判断为True,否则为False 。 习题23中的 if 就是这种写法!!!

END!!!

猜你喜欢

转载自blog.csdn.net/waitan2018/article/details/82814921
今日推荐