“笨办法”学Python 3 ——练习 30 Else 和 if

练习30 源代码

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. if如果…elif如果…else否则语句。
    if 条件语句可以用 elif 和 else 来追加条件
    语法
    if 如果…就…
    elif 再如果…就…
    else 否则
    与if…if…else的区别:
    if-elif-else只执行一个代码块,即如果符合if的条件,不会再继续判断elif的条件;
    if-if-else可运行多个代码块,如果符合第一个if条件,仍然会继续判断第二个if条件。(多个条件同时满足时)。

附加练习

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.

你可能感兴趣的:(Python,python)