T 流年印迹
流年印迹
首页 Python 正文

Python 100 天 · 第 10 天:有返回值的函数:计算器

这是「Python 100 天」系列第 10 天的学习笔记:有返回值的函数:计算器。正文包含知识点拆解、可直接运行的代码,以及当天仓库源文件的逐文件讲解。

今天要解决的问题

一个可以连续计算的计算器:输入第一个数,选运算符,输入第二个数,出结果;然后可以选择"接着拿结果算"、"重新开始"或"退出"。README 知识点:有返回值的函数、多返回值、docstring、字典与函数结合、print 与 return 的区别、while + 标志 + 递归。

一、return 与 print 的区别

这是今天最重要的一课。

1
2
3
4
5
6
7
8
def add_print(a, b):
print(a + b) # 只打印,函数返回 None

def add_return(a, b):
return a + b # 把结果交回调用处

x = add_print(1, 2) # 屏幕显示 3,但 x 是 None
y = add_return(1, 2) # 屏幕什么都不显示,y 是 3

print 是给人看的,return 是给程序用的。 想把结果继续参与运算,必须 return。

return 一旦执行,函数立即结束,后面的代码不会跑。没有 return 的函数隐式返回 None。

二、多返回值

1
2
3
4
def min_max(nums):
return min(nums), max(nums) # 实际返回一个元组

low, high = min_max([3, 1, 4]) # 解包

三、docstring

1
2
3
4
5
6
def add(n1, n2):
"""返回两个数的和。"""
return n1 + n2

help(add) # 显示这段说明
add.__doc__ # 直接取字符串

写在函数体第一行的三引号字符串就是 docstring,是 Python 的文档惯例(对比 C++ 的注释块)。

四、把函数存进字典

1
operations = {'+': add, '-': subtract}

函数是对象,可以像数字一样被赋值、传递、存进容器。operations['+'] 拿到的是函数本身,加括号才是调用。这是"用数据驱动分支"的经典写法:新增一个运算符,只需要往字典里加一行,不用改 if 链。

代码全文

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# ============================================================
# day10/main.py —— 计算器(Function with Outputs)
# 作用:加减乘除四则运算,算完可以用上一次的结果接着算,也可以重新开始。
# 知识点:带 return 的函数、把函数当值存进字典、字典用键取值、
# 递归调用('new' 分支)、while 循环中的状态变量
# 运行:python main.py
# ============================================================

from art import logo


# 四个小函数是“纯函数”的样板:同样的输入永远得到同样的输出,不打印、不改外部状态。
# def add(n1, n2) —— 参数 n1、n2 是要相加的两个数;
# return 把结果交回给调用者(不写 return 则返回 None)。
def add(n1, n2):
return n1 + n2


def subtract(n1, n2):
return n1 - n2


def multiply(n1, n2):
return n1 * n2


def divide(n1, n2):
# 这里没做“除数为 0”的保护,num2 为 0 时会抛 ZeroDivisionError。
# 想更健壮可以写:if n2 == 0: return "不能除以 0"
return n1 / n2


# 字典的键是符号字符串,值是**函数对象本身**(注意:写 add,不是 add())。
# add 是函数;add() 是“调用函数并拿到返回值”,两者完全不同。
# 这样就能用符号当键去查函数,省掉一长串 if/elif。
operations = {
'+': add,
'-': subtract,
'*': multiply,
'/': divide,
}


def calculator():
print(logo)

# 第一个数只问一次;后面“接着算”时会被上一次的 answer 覆盖。
num1 = float(input("What is the first number?: "))
run = True
# 内层循环:一次“计算 → 问要不要继续”的回合。
while run:
# for e in 字典:遍历字典时拿到的是“键”(不是键值对)。
# 所以这里逐个打印的是 + - * / 这四个符号。
for e in operations:
print(e)
perform = input("Type a math operation: ")
num2 = float(input("What is the next number?: "))

# operations[perform]:用键取到对应函数对象,赋给 calculation。
# 如果用户输入了字典里没有的符号,会抛 KeyError。
calculation = operations[perform]
# 此时 calculation 是个函数,加括号才是调用:calculation(num1, num2)。
answer = calculation(num1, num2)

print(f"{num1} {perform} {num2} = {answer}")
print(f"Type 'y' to continue calculating with {answer}, type 'n' to exit or type 'new' for a brand new calculation")
continue_calc = input("Type y/n/new: ")
if continue_calc == 'y':
# 把本轮结果当下一轮的第一个数——这就是“链式计算”。
run = True
num1 = answer
elif continue_calc == 'n':
run = False
print("nGoodbye.")
elif continue_calc == 'new':
# 递归:函数自己调用自己,开一套全新的局部变量(新的 num1、新的循环)。
# 注意递归调用回来后本层并没有退出,只是栈又多了一层;
# 这里靠后面的 return 隐含结束,实际会一直往外套。
# 面试里常被问:这种“递归当重启”不是好习惯,更干净的是外层再套一个 while。
calculator()
else:
print("Invalid response.")
run = False
print("nGoodbye.")

# 程序入口:定义完就调用一次。Python 没有 main 函数的概念,直接写调用即可。
calculator()

代码走读

  1. 四个函数各自只做一件事,都 return 结果,没有一个 print。
  2. operations 字典把符号映射到函数对象。
  3. def calculator(): 把整个流程包成一个函数——这样最后才能递归调用自己实现"重新开始"。
  4. 读 num1,进入 while run:。
  5. 打印所有可用运算符(遍历字典的键)。
  6. calculation = operations[perform]:按符号取出函数;answer = calculation(num1, num2):调用它。
  7. 输出等式后问下一步:
  • y → num1 = answer,继续用结果算(链式计算);
  • n → run = False;
  • new → calculator() 递归开新局;
  • 其它 → 提示无效并退出。

递归 vs 循环

new 分支用递归重开,写法短,但每开一局就多一层函数调用,理论上会栈溢出(Python 默认递归上限约 1000 层)。工程上更稳的是外层套一个 while True:,用 break/continue 控制。这里作为"递归长什么样"的示例可以,但不建议照抄到真实项目。

运行示例

1
2
3
4
5
6
7
8
9
What is the first number?: 10
+
-
*
/
Type a math operation: *
What is the next number?: 3
10 * 3 = 30
Type 'y' to continue calculating with 30.0, ...

易错点

  1. 函数里 print 了但没 return:answer 变成 None,下一步运算报 TypeError。
  2. operations[perform] 键不存在:用户输入 % 会 KeyError,应先用 if perform in operations 校验。
  3. 除以 0:10 / 0 抛 ZeroDivisionError,可以 try/except 兜住(Day 30 讲)。
  4. num1 = answer 漏写:链式计算的灵魂就是这一行。

动手改

  • 增加 **(幂)和 //(整除),体验"加一行字典就多一个功能"。
  • 加 docstring,用 help() 验证。
  • 把递归改成 while True 外层循环。
  • 用 try/except 处理除零和非法输入。

源文件逐个讲解

3 个文件:main.py(53 行)、art.py(8 行)、README.md(11 行)。

art.py(8 行)

1
2
3
4
5
6
logo = """
_____________________
| _________________ |
| | Pythonista 0. | | .----------------. .----------------. ...
...
"""

一幅 6 行的「计算器」字符画,只有 logo 一个变量。注意源码里 logo = """ 后面直接换行,所以 print(logo) 时第一行是空的——这也是一种「留白排版」。

main.py(53 行)

这是全书第一次把「函数当数据用」,结构是:4 个运算函数 + 1 个函数字典 + 1 个主函数。

1
2
3
4
5
6
7
8
9
10
11
def add(n1, n2):
return n1 + n2

def subtract(n1, n2):
return n1 - n2

def multiply(n1, n2):
return n1 * n2

def divide(n1, n2):
return n1 / n2

四个函数签名完全一样(两个参数、一个返回值)。这不是巧合——签名一致才能互相替换,这是后面「策略模式」和「多态」的雏形。

1
2
3
4
5
6
operations = {
'+': add,
'-': subtract,
'*': multiply,
'/': divide,
}

字典的值是函数本身,不是调用结果。对比:

  • '+': add → 存的是函数对象;
  • '+': add(1, 2) → 存的是 3。

这就是「函数是一等公民」:可以放进字典、当参数、当返回值。这一行是全天的核心。

1
2
3
4
5
6
7
8
9
10
11
12
def calculator():
print(logo)
num1 = float(input("What is the first number?: "))
run = True
while run:
for e in operations:
print(e)
perform = input("Type a math operation: ")
num2 = float(input("What is the next number?: "))

calculation = operations[perform]
answer = calculation(num1, num2)

calculation = operations[perform] 取到函数,下一行 calculation(num1, num2) 才调用。这两行分开写是刻意的教学示范:先「查表拿到函数」,再「调用它」。

for e in operations: print(e) 遍历字典只拿键(+ - * /),所以屏幕上只显示四个符号——这是「字典遍历默认给键」的用法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
    print(f"Type 'y' to continue calculating with {answer}, type 'n' to exit or type 'new' for a brand new calculation")
continue_calc = input("Type y/n/new: ")
if continue_calc == 'y':
run = True
num1 = answer
elif continue_calc == 'n':
run = False
print("nGoodbye.")
elif continue_calc == 'new':
calculator()
else:
print("Invalid response.")
run = False
print("nGoodbye.")
calculator()

「接着算」就是把上一次的 answer 赋给 num1,然后循环回到「选运算符」。

「new」用递归实现:calculator() 自己调自己,外层那次调用还挂在栈上。连续按几次 new,栈就有几层。功能上没问题(每次新算完退出时,外层会继续跑它自己的循环),但递归不是「重新开始」的正确工具,用 while 重置变量才对。

最后一行 calculator() 顶格——这是模块级调用,import 这个文件时就会立刻启动计算器(没有 if __name__ == "__main__" 保护)。

这份代码的问题

  1. perform 没校验:输入 "%" → operations["%"] 直接 KeyError 崩掉。
  2. 除零没处理:num2 = 0 且选 / → ZeroDivisionError。
  3. run 变量几乎没用:run = True 之后循环里只在退出时改 False,而 'y' 分支又把它设回 True——写了个「永远为真」的标志。真正控制流程的是 while run + 分支里的 run = False,逻辑能跑但很绕。
  4. 'new' 的递归:算 20 次就 20 层栈,视觉上「清屏重开」实际是「叠一层」。
  5. answer 可能是浮点误差:0.1 + 0.2 会打印 0.30000000000000004。

README.md(11 行)

标题 Day 10 - Functions with Outputs,知识点是 Functions with Outputs、Multiple return values、Docstrings、Combining Dictionaries and Functions、Print vs. Return。

代码里 Print vs. Return 体现得很清楚:四个运算函数都 return(能被继续计算),calculator() 只 print(结果直接给人看)。如果 add 写成 print(n1+n2),answer 就是 None,整个程序立刻崩——这是当天最重要的一句话。

文件间关系

main.py ← art.py(logo)。四个运算函数和字典都在 main.py 里,没有单独模块——因为「运算」是这个程序的核心逻辑,不是素材。

想要更完整的版本

把 perform 校验、除零、while 重开都补上,就是一份能用的命令行计算器:

1
2
3
4
5
6
if perform not in operations:
print("只支持 + - * /")
continue
if perform == '/' and num2 == 0:
print("除数不能为 0")
continue
微信收款码 微信
支付宝收款码 支付宝
评论