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

Python 100 天 · 第 97 天:百分比计算器:命令行菜单与递归

这是「Python 100 天」系列第 97 天的学习笔记:百分比计算器:命令行菜单与递归。正文包含知识点拆解、可直接运行的代码,以及当天仓库源文件的逐文件讲解。

今天要解决的问题

一个命令行计算器,支持三种计算:

  1. x 是 y 的百分之多少(求比例)
  2. x 的 y% 是多少(求部分)
  3. x 到 y 的增减百分比

README 知识点:Python 的数学运算、为不同计算调用不同过程、数字处理与 f-string、if/else 控制流。

这是一个"纯逻辑"的练习:没有库、没有网络,只有输入、计算、输出。

一、三种计算对应的公式

选项 问题 公式
1x 是 y 的百分之多少?x / y * 100
2x 的 y% 是多少?x * y / 100
3从 x 到 y 增减百分之多少?(y - x) / x * 100

第三种是"变化率",分母是"原来的值" x,不是 y。这一点最容易搞错——"从 100 涨到 150"是涨 50%,(150-100)/100;如果分母用了 y 就变成 33%。

二、函数拆分

1
2
3
4
5
6
def percent_of_num(): ...        # 选项 1
def num_percent_of_num(): ... # 选项 2
def percent_num_to_num(): ... # 选项 3
def another_calc(): ... # 是否再算一次
def main(): ... # 菜单 + 分发
def clear_screen(): ... # 清屏

一个计算一个函数 + 一个菜单函数,这是命令行程序的标准结构。main() 只负责"显示菜单、读选项、调对应函数"。

三、清屏的"假清屏"

1
2
3
def clear_screen():
clear = "n" * 100
print(clear)

打印 100 个换行,把旧内容顶出可视区域。

这不是真清屏(滚动上去还能看到),但跨平台。真清屏要:

1
2
import os
os.system('cls' if os.name == 'nt' else 'clear')

后者在 PyCharm 的运行窗口里常常无效(它不支持 ANSI 控制符),所以很多教程用"打印换行"这种笨办法。

四、递归实现"再算一次"

1
2
3
4
5
6
7
8
9
10
11
def another_calc():
response = input("nWould you like another calculation? (Y/N): ")
if response in ("Y", "y"):
clear_screen()
main() # 回到菜单
elif response in ("N", "n"):
print("Thanks for using the Percentage Calculator!")
else:
print("Choose a valid answer!")
time.sleep(2)
another_calc() # 重新问

main() 里调计算函数,计算函数末尾调 another_calc(),another_calc() 又调 main() —— 这是一个互相递归的循环。

能跑,但有两个后果:

  • 每算一次就多两层调用栈,算 1000 次就 RecursionError;
  • 逻辑上"回到开头"用 while True 更清晰。

五、f-string 直接算

1
answer = f"n{x} is {(x * y) / 100}% of {y}n"

表达式可以直接写在 {} 里,不用先算再拼。这是 f-string 比 "..." + str(x) 好用的地方。

想控制小数位:f"{value:.2f}%"。

代码全文

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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
# 只用到 time.sleep 做“停顿一下再清屏”的视觉效果。
import time


# 清屏:用打印 100 个换行把旧内容顶出可视区。
def clear_screen():
# 'n' * 100 得到 100 个换行符拼成的字符串。
clear = "n" * 100
print(clear)


# 计算 1:x 的百分之 y 是多少(注意原码的文案把 x 与 y 说反了)。
def percent_of_num():
# 一步一步问参数:float(input(...)) 直接把输入转成浮点数,
# 用户输入非数字会抛 ValueError(原码没做校验,输入字母就崩)。
print("You chose option #1 - What is x % of y?n")
x = float(input("What is the value of x?: "))
y = float(input("What is the value of y?: "))
# 公式:x * y / 100。文案写成“{x} is {...}% of {y}”,实际算的是“y 的 x%”,
# 变量顺序与文案对不上,属原码笔误。
answer = f"n{x} is {(x * y) / 100}% of {y}n"
print(answer)
# 算完问是否继续(递归)。
another_calc()


# 计算 2:x 是 y 的百分之几。
def num_percent_of_num():
print("You chose option #2 - x is what % of y?n")
x = float(input("What is the value of x?: "))
y = float(input("What is the value of y?: "))
# 公式:x*100/y。这里文案与变量是对应的。
answer = f"n{x} is {(x * 100) / y}% of {y}"
print(answer)
another_calc()


# 计算 3:从 x 到 y 的百分比增减。
def percent_num_to_num():
print("You chose option #3 - What is the % increase/decrease from x to y?n")
x = float(input("What is the value of x?: "))
y = float(input("What is the value of y?: "))
# x > y 表示下降,所以结果是负数。
if x > y:
# 分母用 x(起点),符合“相对起点变化了多少”的定义。
answer = f"nThere is a -{((x - y) / x) * 100}% difference between {x} and {y}"
else:
# 上升为正。
answer = f"nThere is a +{((y - x) / x) * 100}% difference between {x} and {y}"
print(answer)
another_calc()


# 是否再来一次。
def another_calc():
response = input("nWould you like to perform another calculation? (Y/N): ")
# 同时接受大写与小写:`in ('Y','y')` 更简洁。
if response == "Y" or response == "y":
# 清屏后重新进入主菜单。
clear_screen()
main()
# 退出。
elif response == "N" or response == "n":
clear_screen()
print("Thanks for using the Percentage Calculator!")
# 输入了别的字符。
else:
clear_screen()
# 提示。
print("Choose a valid answer!n")
# 停 2 秒让用户看到提示。
time.sleep(2)
# 清屏。
clear_screen()
# 递归再问一次 —— 输错很多次会不断叠加调用栈。
another_calc()


# 主菜单。
def main():
print("Types of calculations:n")
print("1. What is x % of y?n"
"2. x is what % of y?n"
"3. What is the % increase/decrease from x to y?n")

# 读选项(字符串,不转 int,因为后面直接和 '1' 比)。
choice = input("Select a calculation from 1-3: ")
# 三个分支分别进入三个计算函数。
if choice == "1":
clear_screen()
percent_of_num()
elif choice == "2":
clear_screen()
num_percent_of_num()
elif choice == "3":
clear_screen()
percent_num_to_num()
# 非法选项。
else:
clear_screen()
print("Choose a valid answer!n")
time.sleep(2)
clear_screen()
# 递归回主菜单。
main()


# 程序入口:先打招呼再进菜单(没有 __main__ 保护,被 import 时会直接跑)。
print("Welcome to the Percentage Calculator!n")
main()

代码走读

  1. clear_screen():打印 100 个换行。
  2. percent_of_num():读 x、y → 算 x*y/100 → 打印 → another_calc()。
  3. num_percent_of_num():算 x*100/y。
  4. percent_num_to_num():if x > y 输出负数百分比,否则正数。
  5. another_calc():Y 回菜单、N 退出、其他重问。
  6. main():打印三行菜单 → 读 choice → 三个分支 → 非法输入提示后重来。
  7. 文件末尾直接 main()(没有 if __name__ == "__main__")。

这份代码的问题(数学表述有几处不准)

(1) 选项 1 的文案和公式不对应

1
2
print("You chose option #1 - What is x % of y?")
answer = f"n{x} is {(x * y) / 100}% of {y}n"

菜单说的是"x 的百分之多少是 y"(求比例),代码算的是"x 的 y% 是多少"(求部分)。两个问题被搞混了,输出的句子 "5.0 is 15.0% of 30" 读起来也别扭。

正确配对:

  • 求部分:输入"百分比 p"和"总数 n",算 p/100*n,输出 "p% of n is 结果";
  • 求比例:输入"部分 a"和"总数 b",算 a/b*100,输出 "a is 结果% of b"。

(2) 选项 2 的公式和文案不一致

1
2
print("x is what % of y?")
answer = f"n{x} is {(x * 100) / y}% of {y}"

公式是对的(x/y*100),但字符串里少了 % 的位置说明——{...}% 里的 % 是字面量,读起来是"5.0 is 16.66% of 30",这个是对的。这条是三个里唯一正确的。

(3) 选项 3 的输出措辞有歧义

1
answer = f"nThere is a -{((x - y) / x) * 100}% difference between {x} and {y}"

x > y 时算 (x-y)/x,前面再手写一个 - 号 → 得到 -16.6%。这是"从 y 到 x"的变化率,但文案写的是"between x and y",方向不明。

而且 else 分支用 (y-x)/x,if 分支用 (x-y)/x —— 分母都是 x,但含义完全不同:一个是"从 x 降到 y",一个是"从 x 涨到 y"。统一写 (y-x)/x*100 就够了,正负号自然区分。

(4) 没有处理除以 0

y = 0 时选项 1、2 都 ZeroDivisionError;x = 0 时选项 3 也崩。应该:

1
2
if y == 0:
print("除数不能为 0"); return

(5) float(input(...)) 没有异常处理

用户输入 abc → ValueError → 程序直接退出。应该 try/except 并重问。

(6) 递归会爆栈

见上。

(7) 没有 if __name__ == "__main__"

文件被 import 时会立刻执行 main()。虽然这个小程序不会被 import,但习惯要养对。

运行结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Welcome to the Percentage Calculator!

Types of calculations:

1. What is x % of y?
2. x is what % of y?
3. What is the % increase/decrease from x to y?

Select a calculation from 1-3: 2
What is the value of x?: 5
What is the value of y?: 30

5.0 is 16.666666666666664% of 30
Would you like to perform another calculation? (Y/N):

易错点

  1. 变化率分母用错:应该是"原值",不是"新值"。
  2. input() 返回字符串:忘了 float() 就是字符串拼接。
  3. except 没写:一个非法输入就退出程序。
  4. clear_screen 用 os.system:在某些 IDE 里无效,还会闪一下。

动手改

  • 修正三处文案,让问题和公式一一对应。
  • 加除零检查和 ValueError 处理。
  • 递归改成 while True。
  • 输出统一 :.2f,只保留两位小数。

源文件逐个讲解

2 个文件:

文件 规模 职责
main.py75 行百分比计算器(命令行,三种算法)
README.md8 行说明页

这是「全书最后一个纯命令行程序」——没有库、没有 GUI、没有网络——只有 input() 和 print()。

main.py(75 行)

(1)clear_screen():一个「土办法」

1
2
3
def clear_screen():
clear = "n" * 100
print(clear)

「打印 100 个换行」= 「把旧内容顶出屏幕」——这是跨平台的「清屏」土办法。

正规做法:

1
2
import os
os.system('cls' if os.name == 'nt' else 'clear')

⚠️ 但 "n" * 100 有个「隐藏好处」:它「不清除历史」,只是「滚上去」——用户往上滚还能看到「上次的计算结果」。

(2)三种算法:三个函数

① percent_of_num():x 是 y 的百分之几

1
2
3
4
5
6
7
def percent_of_num():
print("You chose option #1 - What is x % of y?n")
x = float(input("What is the value of x?: "))
y = float(input("What is the value of y?: "))
answer = f"n{x} is {(x * y) / 100}% of {y}n"
print(answer)
another_calc()

⚠️ 这里有个「语义 bug」:

函数名和提示语说「What is x% of y?」(「y 的 x% 是多少」)——正确答案是 y * x / 100(一个数值)。

但输出格式是 f"{x} is {(x*y)/100}% of {y}"(「x 是 y 的多少百分比」)——这是一个「百分数」,不是「数值」。

「提示语」和「输出语」是两回事:

问法 正确公式 正确输出
「y 的 x% 是多少?」y * x / 10050 的 20% 是 10
「x 是 y 的百分之几?」x / y * 10010 是 50 的 20%

这段代码「问 A 答 B」——结果数字是对的(x*y/100),但「单位(%)」和「句式」错了。

② num_percent_of_num():x 是 y 的百分之几

1
2
3
4
5
6
7
def num_percent_of_num():
print("You chose option #2 - x is what % of y?n")
x = float(input("What is the value of x?: "))
y = float(input("What is the value of y?: "))
answer = f"n{x} is {(x * 100) / y}% of {y}"
print(answer)
another_calc()

x / y * 100——这个是对的(「10 是 50 的 20%」)。

③ percent_num_to_num():从 x 到 y 的增减百分比

1
2
3
4
5
6
7
8
9
10
def percent_num_to_num():
print("You chose option #3 - What is the % increase/decrease from x to y?n")
x = float(input("What is the value of x?: "))
y = float(input("What is the value of y?: "))
if x > y:
answer = f"nThere is a -{((x - y) / x) * 100}% difference between {x} and {y}"
else:
answer = f"nThere is a +{((y - x) / x) * 100}% difference between {x} and {y}"
print(answer)
another_calc()

「变化率 = 差值 / 起始值 × 100」——公式对。

⚠️ 但「x > y 时算 (x-y)/x」和「x < y 时算 (y-x)/x」是「两个不同的公式」吗?

不是——(x-y)/x 和 (y-x)/x 只差一个符号——所以「加个 - / + 前缀」是多余的。

更简洁:

1
2
change = (y - x) / x * 100
answer = f"nThere is a {change:+.2f}% change from {x} to {y}"

{change:+.2f}:+ 表示「正数也显示加号」——一个格式符就搞定了 if/else。

⚠️ 另一个问题:x == y 时

x > y 为假 → 走 else → 算 (y-x)/x = 0 → 输出「+0.0%」——能接受,但「没有变化」用「+0.0%」有点怪。

⚠️ x == 0 时会 ZeroDivisionError(三个函数都有这个风险)。

(3)another_calc():递归再算

1
2
3
4
5
6
7
8
9
10
11
12
13
14
def another_calc():
response = input("nWould you like to perform another calculation? (Y/N): ")
if response == "Y" or response == "y":
clear_screen()
main()
elif response == "N" or response == "n":
clear_screen()
print("Thanks for using the Percentage Calculator!")
else:
clear_screen()
print("Choose a valid answer!n")
time.sleep(2)
clear_screen()
another_calc()

三个分支:

输入 动作
Y / y清屏 → 回主菜单(main())
N / n清屏 → 道别
其他清屏 → 提示 → 等 2 秒 → 重问

⚠️ 两个真问题:

① main() 递归调用 → 「算 50 次就压 50 层栈」

main() → 选 1 → percent_of_num() → another_calc() → main() → ...

这是一个「无限递归的循环」——Python 默认递归上限 1000 层,用户算 300 次左右就会 RecursionError。

正确做法是「while True + break」。

② response == "Y" or response == "y" 重复

可以写 response.lower() == "y",或者 response in ("Y", "y")。

(4)main():菜单 + 分发

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
def main():
print("Types of calculations:n")
print("1. What is x % of y?n"
"2. x is what % of y?n"
"3. What is the % increase/decrease from x to y?n")

choice = input("Select a calculation from 1-3: ")
if choice == "1":
clear_screen()
percent_of_num()
elif choice == "2":
clear_screen()
num_percent_of_num()
elif choice == "3":
clear_screen()
percent_num_to_num()
else:
clear_screen()
print("Choose a valid answer!n")
time.sleep(2)
clear_screen()
main()

「打印菜单 → 读输入 → 三个 elif 分发」——命令行程序的经典结构。

⚠️ else 分支里又调 main()——「输错就递归」——和第 3 点同一个问题。

(5)入口

1
2
print("Welcome to the Percentage Calculator!n")
main()

没有 if __name__ == "__main__"——模块级直接执行。

这份代码的问题

  1. percent_of_num() 的「提示语」和「输出语」语义不一致(问 A 答 B)。
  2. main() / another_calc() 递归调用(算几百次就 RecursionError)。
  3. x == 0 会 ZeroDivisionError。
  4. response == "Y" or response == "y" 啰嗦(in 或 .lower() 更短)。
  5. percent_num_to_num() 的 if/else 是多余的({change:+.2f} 一个格式符就够)。
  6. print(clear) 打印了一个变量再打印换行(print("n"*100, end="") 更准)。
  7. 没有 if __name__ == "__main__"。
  8. float(input(...)) 没做「非数字」保护(输个字母就 ValueError)。
  9. 「清屏」用 100 个换行(终端历史会很长)。
  10. 三个函数结构高度相似(可以「合并成一个 + 传公式」)。

「合并」的思路(供对照):

1
2
3
4
5
CALCS = {
"1": ("y 的 x% 是多少", lambda x, y: y * x / 100, "{v:.2f}"),
"2": ("x 是 y 的百分之几", lambda x, y: x / y * 100, "{v:.2f}%"),
"3": ("从 x 到 y 的变化率", lambda x, y: (y - x) / x * 100, "{v:+.2f}%"),
}

「公式即数据」——三个函数变三行字典。

README.md(8 行)

标题 Day 97 - Percentage Calculator,知识点:Functions、Conditionals、User Input。

三个:函数、条件、用户输入。

这一天「没有任何新技术」——它是「Day 1~14 基础语法的期末考」:

用到的 哪一天学的
def 函数Day 8
if/elif/elseDay 3
input() + 类型转换Day 2
f-string 格式化Day 12
while / 递归Day 5/9

「75 行、零依赖、能用但有一堆小毛病」——这正是「新手写出的第一个完整工具」的样子。

而它暴露的问题(递归代替循环、公式和文案不一致、缺边界检查),恰恰是「从「能跑」到「可靠」」要跨的那道坎。

微信收款码 微信
支付宝收款码 支付宝
评论