笨方法学Python 习题 30: Else 和 If
2017-08-04 16:16
435 查看
#!usr/bin/python # -*-coding:utf-8-*- 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 too many 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.")
运行结果如下:
$ python ex30.py
We should take the cars.
Maybe we could take the buses.
Alright, let's just take the buses.
$
加分习题
猜想一下 elif 和 else 的功能。
将 cars, people, 和 buses 的数量改掉,然后追溯每一个 if 语句。看看最后会打印出什么来。
试着写一些复杂的布尔表达式,例如 cars > people and buses < cars。
在每一行的上面写注解,说明这一行的功用。
常见问题回答
如果多个 elif 区块都是 True 是 python 会如何处理?
Python 只会运行它碰到的是 True 的第一个区块,所以只有第一个为 True 的区块会被运行。
相关文章推荐
- 笨方法学习Python-习题30: Else 和 If
- python 笔记 if语句中的elif和else 《笨办法学Python》习题30 ——1.2
- 习题30 else 和 if
- Learn Python The Hard Way学习(30) - Else和If
- Python列表解析配合if else的方法
- 笨方法学python 习题27(逻辑之前的内容)习题28(布尔)29、30、31
- 笨方法学Python 习题 29: 如果(if)
- 笨方法学习Python-习题29: 如果(if)
- python 手记9 〖笨方法学python习题30〗
- 习题30 else 和 if. 附加练习3
- Python列表解析配合if else
- c语言 习题5.8参考答案(第一种解法,用if~else~语句)
- R语言:if-else条件判断及any、all、na.omit使用方法
- 习题(简单IF~else)
- 笨方法学习Python-习题16: 读写文件
- 笨方法学习Python-习题37: 复习各种符号
- Python学习笔记(4)——控制流If-else
- avalonjs 中的if else实现的几种方法
- Python流程控制语句->if .......else
- c#扩展方法奇思妙用变态篇二:封装 if/else、swith/case及while