if 与 else · Python 从零开始
程序怎样在两条路之间做选择?
课程目录为什么需要它
到现在为止,每一行每次都会运行。真实的程序要能做出反应:登录要检查密码,商店要检查库存,游戏要检查你赢了没有。程序要比较数值,再根据结果运行不同的代码。
直觉理解
在机器人课里你已经用过:if on_gem():。现在的问题换成你自己写的比较 Comparison:
| 运算符 | 含义 |
|---|---|
== | 等于 |
!= | 不等于 |
< > | 小于 / 大于 |
<= >= | 小于等于 / 大于等于 |
每个比较的结果都是 True 或 False。
if age >= 18:
print("adult")
else:
print("minor")两个代码块里只有一个会运行。整个 if/else 后面(不缩进)的行总会运行。
定义
比较运算符 Comparison operator
A comparison operator such as ==, !=, < or >= compares two values and produces True or False.比较运算符(如 ==、!=、<、>=)比较两个值,得到 True 或 False。
if / else 语句
An if statement runs its block when the condition is True; the optional else block runs when it is False.if 语句在条件为 True 时运行它的代码块;可选的 else 代码块在条件为 False 时运行。
示例
成年还是未成年
动手试试在「输入」框里试试 18、17 和 40。
age = int(input())
if age >= 18:
print("adult")
else:
print("minor")
print("checked")输入(每次 input() 读一行)
17
逐步执行
- L1age = 17
age = 17 - L217 >= 18 吗?False。
False - L5所以运行 else 代码块。
minor - L6这一行在 if/else 外面:总会运行。
checked
比较的结果也是值
动手试试直接打印比较,看看 True 和 False。
print(3 < 5, 3 == 3.0)
print("a" == "A", 10 != 10)逐步执行
- L13 小于 5;3 和 3.0 数值相等。
True True - L2字符串要完全一样才相等,大小写有区别。10 != 10 是 False。
False False
常见错误
把 == 写成 =
if x = 5: 是语法错误。一个 = 是赋值,两个 == 才是比较。
文字和数字比较
input() 得到的是文字,"5" == 5 是 False。比较前先用 int() 转换。
小测验
1. 这段代码会输出什么?
x = 7
if x > 5:
print("big")
else:
print("small")
print("done")查看答案
答案:A
7 > 5 为 True,所以打印 big;done 总会运行。
2. 这段代码会输出什么?
print(10 == "10")查看答案
答案:B
数字永远不等于字符串,哪怕看起来一样。
动手练习
3 道练习,分三层:先预测程序的输出,再按新需求改程序,最后从零写一个。代码在浏览器里运行,提交马上判题。
- 预测输出走哪条分支?
准确写出程序的输出。
- 改需求加一个 else
这段程序只对正数有反应。加一个
else,打印not positive。 - 从零写较大的数
读入两个整数,打印较大的那个。要用
if,不要用 max()。如果相等,就打印这个数。
本课术语
| 术语 | 中文 | 英文定义 |
|---|---|---|
| Comparison operator | 比较运算符 | An operator such as == or < that compares two values and gives True or False. |
| Branch | 分支 | One of the alternative blocks of code that an if statement can run. |
| Equality == | 相等 == | The operator that checks whether two values are equal. |