《笨办法学python3-Learn Python 3 the HARD WAY》-习题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.if,elif,else
if:若布尔表达式为真,if缩进的内容会运行,否则就跳过。
只要一行以冒号(:)结尾,他接下来的内容就应该有缩进。
if,elif,else的使用:
if和elif的区别:
例1:只用if:条件1和条件2是独立的,只有条件1和条件2都为假,才会执行else.

if a < 6: # 条件1
	print (1)
if a < 7: # 条件2
	print (2)
else:
	print (3)

例2:if-elif-else:条件1和条件2是相关的,条件1成立,不会运行条件2;若条件1不成立,则会运行条件2;若条件1和条件2都失败,则会执行else.

a = 5
if a < 6: # 条件1
	print (1)
elif a < 7: # 条件2
	print (2)
else:
	print (3)

例3:打印出1,4

a = 5
if a < 6:
	print (1)
elif a < 4:
	print (2)
if a > 7:
	print (3)
else:
	print (4)

结果:
在这里插入图片描述
•若只想执行一个代码块,就用if-elif-else结构。
•若要运行多个代码块,就用if-else结构(多条件同时满足)。
•若多个elif都是True,Python只会执行第一个elif.

  1. 自己写一个类似的小脚本。
    这里写了个中文的脚本玩玩。
# -- coding: utf-8 --
cookies = int(input('cookies>'))
box = int(input('box>'))
people = int(input('people>'))


if people > cookies / box:
    print ("今天人有点多,饼干太少了,需要再买点其他的吃的。")
elif people < cookies / box:
    print ("饼干够了,再买些饮料就可以了。")
else:
    print ("还需要再采购一些吃的。")

print ("我们还需要一些花装饰一下。")
tulip = int(input('tulip>'))
rose = int(input('rose>'))
if tulip > rose:
    print ("郁金香有些多,需要在搭配些其他的花。")
if tulip < rose:
    print ("好浪漫!")
else:
    print ("数量刚刚好,太好了!")

结果:
在这里插入图片描述
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值