学习内容:
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.
- 自己写一个类似的小脚本。
这里写了个中文的脚本玩玩。
# -- 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 ("数量刚刚好,太好了!")
结果: