简单 Calculator (Python)
你将构建什么
Python script 使用 calculate(, op, b) 函数 supporting +, -, *, / and CLI 那个读取 two 数字 and 运算符, 然后 prints result or 错误消息.
学习目标
- 定义函数使用多个参数
- Use 如果/elif/else 到选择操作
- Guard 针对 division 通过零
- Handle unknown 运算符使用清晰消息
前置要求
- 函数 and 返回值
- 如果/elif/else 语句
- 输入() and float()
步骤
- 1
编写 calculate 函数
定义 calculate(, op, b) 那个分支 on op and 返回 result. Use 如果/elif/else for four 运算符, and 返回错误字符串 for unknown ops.
代码def calculate(a, op, b): if op == "+": return a + b elif op == "-": return a - b elif op == "*": return a * b elif op == "/": if b == 0: return "Cannot divide by zero" return a / b else: return "Unknown operator"预期结果
calculate(4, "+", 5) 返回 9; calculate(5, "/", 0) 返回错误消息.
提示
检查零-division 情况之前执行 division.
- 2
读取输入从 用户
Ask 用户 for two 数字 and 运算符. Convert 数字使用 float() 所以 decimal 输入工作; leave 运算符 as 字符串.
代码a = float(input("First number: ")) op = input("Operator (+, -, *, /): ") b = float(input("Second number: "))预期结果
Three 值读取从 用户, ready 到通过到 calculate.
- 3
Call 函数 and print result
通过输入到 calculate and print result. Keeping math in 函数平均值 CLI 是只是输入 → call → 输出.
代码result = calculate(a, op, b) print(f"{a} {op} {b} = {result}")预期结果
输入 4, +, 5 prints "4.0 + 5.0 = 9.0"; 输入 5, /, 0 prints 错误消息.
- 4
测试边缘情况
运行 script 使用少数边缘情况: division 通过零, unknown 运算符, and 负数字. 确认每个返回 sensible result or 消息.
代码# Test cases (run mentally or in a REPL) print(calculate(4, "+", 5)) # 9 print(calculate(10, "/", 0)) # Cannot divide by zero print(calculate(3, "%", 2)) # Unknown operator print(calculate(-6, "*", 7)) # -42预期结果
Four 行: 9, 零-division 消息, unknown-运算符消息, and -42.
- 5
添加输入验证与异常处理
在主函数中添加 try/except 块处理用户输入错误,使用 ValueError 捕获非法转换。Python 的异常处理让程序对错误输入优雅降级而非崩溃。
代码def safe_input(prompt, validator=None): """Read input with validation and error handling.""" while True: try: raw = input(prompt) value = float(raw) if validator and not validator(value): raise ValueError(f"Value {value} failed validation") return value except ValueError as err: print(f"Invalid input: {err}. Please try again.") # Usage age = safe_input("Enter your age: ", lambda x: x > 0)预期结果
非法输入(非数字或验证失败)提示重新输入;合法输入返回数值。
自己动手试试
def calculate(a, op, b):
# TODO: implement +, -, *, / with zero-division and unknown-op guards
pass
# TODO: read a, op, b from input, call calculate, print resultdef calculate(a, op, b):
if op == "+":
return a + b
elif op == "-":
return a - b
elif op == "*":
return a * b
elif op == "/":
if b == 0:
return "Cannot divide by zero"
return a / b
else:
return "Unknown operator"
a = float(input("First number: "))
op = input("Operator (+, -, *, /): ")
b = float(input("Second number: "))
result = calculate(a, op, b)
print(f"{a} {op} {b} = {result}")你学到了什么
你构建函数那个分支 on 输入, handles two 错误情况, and wired 它到 CLI — 相同结构后面大多数 command-行 utilities.
相关资源
相关练习
- 函数概念
Solidify 参数, 返回, and 通过-通过模式.
- 条件 Predict
Predict 哪个分支运行 for given 输入.
相关工具
- Math Evaluator
Compare 你的 calculator 使用完整表达式 evaluator.
相关速查表
- Python Cheatsheet
函数, conditional, and 输入语法引用.
相关参考文档
- Python Math
Math 模块引用.
相关错误
- 语法错误
常见 Python 语法 mistakes.
- 类型错误
操作 on incompatible 类型.
- Indentation 错误
Inconsistent indentation.
相关术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
相关错误
用大白话解释常见错误——什么意思、为什么发生、如何修复。
- 语法错误
常见 Python 语法 mistakes.
- 类型错误
操作 on incompatible 类型.
- Indentation 错误
Inconsistent indentation.