Python中的if、else、elif语句用法简明讲解
下面我们学习if语句,输入下面的代码,确保能够正确运行。
people=20 cats=30 dogs=15 ifpeople<cats: print"Toomanycats!Theworldisdoomed!" ifpeople>cats: print"Notmanycats!Theworldissaved!" ifpeople<dogs: print"Theworldisdrooledon!" ifpeople>dogs: print"Theworldisdry!" dogs+=5 ifpeople>=dogs: print"Peoplearegreaterthanorequaltodogs." ifpeople<=dogs: print"Peoplearelessthanorequaltodogs." ifpeople==dogs: print"Peoplearedogs."
运行结果
root@he-desktop:~/mystuff#pythonex29.py
Toomanycats!Theworldisdoomed! Theworldisdry! Peoplearegreaterthanorequaltodogs. Peoplearelessthanorequaltodogs. Peoplearedogs.
加分练习
通过上面的练习,我们自己猜测一下if语句的作用,用自己的话回答下面的问题。
1.你认为if对它下面的代码做了什么?
判断为True就执行它下面的代码,否则不执行。
2.为什么if下面的代码要缩进4个空格?
为了表示这些代码属于if判断下包括的代码。
3.如果不缩进会发生什么?
会提示一个缩进错误。
4.你可以从第27节中拿一些布尔表达式来做if判断吗?
5.改变people,dogs,cats变量的值,看看会发生什么?
答案:
1.if语句下面的代码是if的一个分支。就像书里的一个章节,你选择了这章就会跳到这里阅读。这个if语句就像是说:“如果布尔判断为True,就执行下面的代码,否则跳过这些代码”。
2.用冒号结束一个语句就是要告诉python,我要开始一个新的代码段了。缩进4个空格就是说,这些代码是包含在这个代码段中的,和函数的使用一样。
3.不缩进会报错,python规定冒号后面语句必须有缩进。
4.可以,而且可以是复杂的语句。
5.修改变量的值后,判断语句就会相应的变True或者False,然后输出不同的语句。
比较我的答案和你自己的答案,确保你能理解代码块这个概念,因为这个对于下面的练习非常重要。
输入下面的代码,运行它:
people=30 cars=40 buses=15 ifcars>people: print"Weshouldtakethecars." elifcars<people: print"Weshouldnottakethecars." else: print"Wecan'tdicide." ifbuses>cars: print"That'stoomanybuses." elifbuses<cars: print"Maybewecouldtakethebuses." else: print"Westillcan'tdecide." ifpeople>buses: print"Alright,let'sjusttakethebuses." else: print"Fine,let'sstayhomethen."
运行结果
root@he-desktop:~/mystuff#pythonex30.py
Weshouldtakethecars. Maybewecouldtakethebuses. Alright,let'sjusttakethebuses.