people = 30
cars = 40
trucks = 15
if cars > people: #如果变量cars大于变量people,则运行以下内容,否则跳过。
print("We should take the cars.")
elif cars < people: #如果变量cars小于变量people,则运行以下内容,否则跳过。
print("We should not take the cars.")
else: #如果以上条件都不成立,则打印以下内容
print("We can't decide.")
if trucks > cars: #如果变量trucks大于变量cars,则运行以下内容,否则跳过。
print("That's too many trucks.")
elif trucks < cars: #如果变量trucks小于变量cars,则运行以下内容,否则跳过。
print("Maybe we could take the trucks.")
else: #如果以上条件都不成立,则运行以下内容
print("We still can't decide.")
if people > trucks: #如果变量people大于变量trucks,则运行以下内容,否则跳过。
print("Alright,let's just take the trucks.")
else: #如果以上条件不成立,则运行以下内容。
print("Fine,let's stay home then.")
We should take the cars.
Maybe we could take the trucks.
Alright,let's just take the trucks.
1. 试着猜猜 elif 和 else 的作用是什么。
见知识点1
2. 改变 cars,people,和 trucks 的数值,然后追溯每一个 if 语句,看看什么会被打印出来。
修改cars数值,由40改为15,代码如下:
people = 30
cars = 15 #原数值为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.")
输出结果:
We should not take the cars.
We still can't decide.
Alright,let's just take the trucks.
3. 试试一些更复杂的布尔表达式,比如cars > people or trucks < cars。
people = 30
cars = 15
trucks = 15
if cars > people or trucks < cars:
print("We could take the cars or trucks.")
elif cars < people or trucks > cars:
print("There are too many trucks.")
else:
print("We can't decide.")
输出结果:
There are too many trucks.
4. 在每一行上面加上注释。
源代码已加注释。
1. 如果多个 elif 块都是 True 会发生什么?
Python 从顶部开始,然后运行第一个是 True 的代码块,也就是说,它只会运行第一个。
示例:
if people < cars: #条件不成立
print("We should take the cars.")
elif people > cars: #条件成立
print("We should not take the cars.")
elif people > trucks: #条件成立,当elif只运行第一个成立的条件。
print("Alright,let's just take the trucks.")
else:
print("Fine,let's stay home then.")
输出结果:
We should not take the cars.