人人都能学编程
English 开始学习
课程 2 · Python 入门第 7 课 / 共 14 课免费阅读

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
逐步执行
  1. L1age = 17age = 17
  2. L217 >= 18 吗?False。False
  3. L5所以运行 else 代码块。minor
  4. L6这一行在 if/else 外面:总会运行。checked

比较的结果也是值

动手试试

直接打印比较,看看 True 和 False。

print(3 < 5, 3 == 3.0)
print("a" == "A", 10 != 10)
逐步执行
  1. L13 小于 5;3 和 3.0 数值相等。True True
  2. 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")
  1. A
    big
    done
  2. B
    big
  3. C
    small
    done
查看答案

答案:A

7 > 5 为 True,所以打印 big;done 总会运行。

2. 这段代码会输出什么?

print(10 == "10")
  1. A
    True
  2. B
    False
  3. C
    10
查看答案

答案:B

数字永远不等于字符串,哪怕看起来一样。

动手练习

3 道练习,分三层:先预测程序的输出,再按新需求改程序,最后从零写一个。代码在浏览器里运行,提交马上判题。

  1. 预测输出走哪条分支?

    准确写出程序的输出。

  2. 改需求加一个 else

    这段程序只对正数有反应。加一个 else,打印 not positive。

  3. 从零写较大的数

    读入两个整数,打印较大的那个。要用 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.