Python系列之笨方法学Python是我学习《笨方法学Python》—Zed A. Show著
的学习思路和理解,如有不如之处,望指出!!!
本节主要学习程序学习中都会学习的if
和else
语言,运用和理解起来也是非常简单
源代码
# ex30.py
people=30
cars=40
buses=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 buses>cars:
print "that's we could take the buses."
elif buses<cars:
print "maybe we could take the buses."
else:
print "we still can't decide."
if people>buses:
print "alright,let's just take the buses."
else:
print "fine,let's stay home then."
应该看到的结果
本节需要注意的事
- 如果多个
elif
块都是True
,Python会如何处理?
Python只会运行它遇到的是True
的第一个块,所以只有第一个为True
的块会运行。
if
和elif
的区别
如果程序中判断事件很多,全部用if
的话,会遍历整个程序,用elif
程序运行时,只要if
或后续某一个elif
之一满足逻辑值为True
,则程序执行完对应输出语句后自动结束该轮if-elif
(即不会再去冗余地执行后续的elif
或else
)
示例如下:
#encoding=utf-8
a=88
if a>= 90:
print u"优秀"
if a == 88:
print u"正好88"
if a >= 80:
print u"良好"
else:
print u"都不合格"
print "* * "*10
if a>= 90:
print u"优秀"
elif a == 88:
print u"正好88"
elif a >= 80:
print u"良好"
else:
print u"都不合格"
以上指令的执行结果如下:
正好88
良好
* * * * * * * * * * * * * * * * * * * *
正好88
if
、elif
和else
语句注意一下两点:
else
、elif
为子块,不能独立使用- 一个
if
语句中可以包含多个elif
语句,但是结尾只能有一个else
语句
这是**《笨方法学Python》**的第十五篇文章
希望自己可以坚持下去
希望你也可以坚持下去