Test15-if和else语言

Python系列之笨方法学Python是我学习《笨方法学Python》—Zed A. Show著
的学习思路和理解,如有不如之处,望指出!!!

本节主要学习程序学习中都会学习的ifelse语言,运用和理解起来也是非常简单

源代码

# 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的块会运行。

  • ifelif的区别

如果程序中判断事件很多,全部用if的话,会遍历整个程序,用elif 程序运行时,只要if或后续某一个elif之一满足逻辑值为True,则程序执行完对应输出语句后自动结束该轮if-elif(即不会再去冗余地执行后续的elifelse

示例如下:

#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
  • ifelifelse语句注意一下两点:
  1. elseelif为子块,不能独立使用
  2. 一个if语句中可以包含多个elif语句,但是结尾只能有一个else语句

这是**《笨方法学Python》**的第十五篇文章

希望自己可以坚持下去

希望你也可以坚持下去

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值