20241117 《Python程序设计》实验二报告
课程:《Python程序设计》
班级: 2411
姓名: 林世源
学号:20241117
实验教师:王志强
实验日期:2025年3月26日
必修/选修: 公选课
一、实验内容
(一)设计并完成一个计算器,支持整数和复数,可以完成加、减、乘、除、对数和幂等运算,并设计简单的封面。
(二)设计一个出计算题程序,每次出10题,支持加减乘除四则运算,并统计正确率。
二、实验过程及结果
(一)设计一个计算器
1.该计算器包含加减乘除四则运算,可定义函数进行计算,注意除数不能为零。并设计属于自己的计算器封面,循环结构控制计算器是否继续。
代码如下
import math
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
if y == 0:
print("除数不能为0!")
return None
return x / y
print("""
+—————————————————————————+
| Python 计算器 |
+—————————————————————————+
| |
| |
+—————————————————————————+
| +———+ +———+ +———+ +———+ |
| | 7 | | 8 | | 9 | | / | |
| +———+ +———+ +———+ +———+ |
| +———+ +———+ +———+ +———+ |
| | 4 | | 5 | | 6 | | * | |
| +———+ +———+ +———+ +———+ |
| +———+ +———+ +———+ +———+ |
| | 1 | | 2 | | 3 | | - | |
| +———+ +———+ +———+ +———+ |
| +———+ +———+ +———+ +———+ |
| | . | | 0 | | = | | + | |
| +———+ +———+ +———+ +———+ |
+—————————————————————————+
made by 20241117林世源
""")
while True:
print("欢迎使用计算器!")
num1 = float(input("请输入第一个数:"))
num2 = float(input("请输入第二个数:"))
operator = input("请输入运算符(+-*/):")
if operator == '+':
print(num1, "+", num2, "=", add(num1, num2))
elif operator == '-':
print(num1, "-", num2, "=", subtract(num1, num2))
elif operator == '*':
print(num1, "*", num2, "=", multiply(num1, num2))
elif operator == '/':
result = divide(num1, num2)
if result is not None:
print(num1, "/", num2, "=", result)
else:
print("?")
next_calculation = input("您想再做一次计算吗?(是/否): ")
if next_calculation.lower() != '是':
break
运行结果
2.增加对数函数和幂函数计算。注意对数函数需要满足的条件
代码如下
import math
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
if y == 0:
print("除数不能为0!")
return None
return x / y
def power(x, y):
return x ** y
def logarithm(x, y):
if x <= 0 or y <= 0 or y == 1:
print("对数的底数必须大于0且不等于1,真数必须大于0!")
return None
return math.log(x, y)
print("""
+—————————————————————————+
| Python 计算器 |
+—————————————————————————+
| |
| |
+—————————————————————————+
| +———+ +———+ |
| | ^ | |log| |
| +———+ +———+ |
| +———+ +———+ +———+ +———+ |
| | 7 | | 8 | | 9 | | / | |
| +———+ +———+ +———+ +———+ |
| +———+ +———+ +———+ +———+ |
| | 4 | | 5 | | 6 | | * | |
| +———+ +———+ +———+ +———+ |
| +———+ +———+ +———+ +———+ |
| | 1 | | 2 | | 3 | | - | |
| +———+ +———+ +———+ +———+ |
| +———+ +———+ +———+ +———+ |
| | . | | 0 | | = | | + | |
| +———+ +———+ +———+ +———+ |
+—————————————————————————+
made by 20241117林世源
""")
while True:
print("欢迎使用计算器!")
num1 = float(input("请输入第一个数:"))
num2 = float(input("请输入第二个数:"))
operator = input("请输入运算符(+,-,*,/,^,log):")
if operator == '+':
print(num1, "+", num2, "=", add(num1, num2))
elif operator == '-':
print(num1, "-", num2, "=", subtract(num1, num2))
elif operator == '*':
print(num1, "*", num2, "=", multiply(num1, num2))
elif operator == '/':
result = divide(num1, num2)
if result is not None:
print(num1, "/", num2, "=", result)
elif operator == '^':
print(num1, "^", num2, "=", power(num1, num2))
elif operator == 'log':
result = logarithm(num1, num2)
if result is not None:
print(f"log({num1}, {num2}) =", result)
else:
print("?")
next_calculation = input("您想再做一次计算吗?(是/否): ")
if next_calculation.lower() != '是':
break
运行结果如下
3.将计算器功能从整数拓展到复数。注意python中的复数是a+bj而不是a+bi
代码如下
import cmath
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
if y == 0:
print("除数不能为0!")
return None
return x / y
def power(x, y):
return x ** y
def logarithm(x, y):
if y == 0 or y == 1:
print("对数的底数必须大于0且不等于1!")
return None
try:
return cmath.log(x, y)
except ValueError as e:
print(f"无效的输入: {e}")
return None
def get_complex_input(prompt):
while True:
try:
value = complex(input(prompt))
return value
except ValueError:
print("输入无效,请输入一个有效的复数(例如:3+4j 或 5)")
print("""
+—————————————————————————+
| Python 计算器 |
+—————————————————————————+
| |
| |
+—————————————————————————+
| +———+ +———+ +———+ |
| | ^ | |log| | i | |
| +———+ +———+ +———+ |
| +———+ +———+ +———+ +———+ |
| | 7 | | 8 | | 9 | | / | |
| +———+ +———+ +———+ +———+ |
| +———+ +———+ +———+ +———+ |
| | 4 | | 5 | | 6 | | * | |
| +———+ +———+ +———+ +———+ |
| +———+ +———+ +———+ +———+ |
| | 1 | | 2 | | 3 | | - | |
| +———+ +———+ +———+ +———+ |
| +———+ +———+ +———+ +———+ |
| | . | | 0 | | = | | + | |
| +———+ +———+ +———+ +———+ |
+—————————————————————————+
made by 20241117林世源
""")
while True:
print("欢迎使用计算器!")
num1 = get_complex_input("请输入第一个数(例如:3+4j 或 5):")
num2 = get_complex_input("请输入第二个数(例如:3+4j 或 5):")
operator = input("请输入运算符(+,-,*,/,^,log):")
if operator == '+':
print(num1, "+", num2, "=", add(num1, num2))
elif operator == '-':
print(num1, "-", num2, "=", subtract(num1, num2))
elif operator == '*':
print(num1, "*", num2, "=", multiply(num1, num2))
elif operator == '/':
result = divide(num1, num2)
if result is not None:
print(num1, "/", num2, "=", result)
elif operator == '^':
print(num1, "^", num2, "=", power(num1, num2))
elif operator == 'log':
result = logarithm(num1, num2)
if result is not None:
print(f"log({num1}, {num2}) =", result)
else:
print("?")
next_calculation = input("您想再做一次计算吗?(是/否): ")
if next_calculation.lower() != '是':
break
运行结果如下
**二、设计一个出计算题程序 **
编写小学生刷题程序,一次出十道题,最后统计正确率。
改进题目生成逻辑,使减法题的答案都为正数,除法题的答案都为整数
代码如下
import random
def generate_question():
operators = ['+', '-', '*', '/']
operator = random.choice(operators)
if operator == '+':
x = random.randint(1, 50)
y = random.randint(1, 50)
correct_answer = x + y
elif operator == '-':
x = random.randint(1, 100)
y = random.randint(1, 100)
if x < y:
x, y = y, x
correct_answer = x - y
elif operator == '*':
x = random.randint(1, 10)
y = random.randint(1, 10)
correct_answer = x * y
elif operator == '/':
y = random.randint(1, 10)
x = y * random.randint(1, 10)
correct_answer = x // y # Ensure the result is an integer
question = f"{x} {operator} {y}"
return question, correct_answer
def main():
while True:
print("欢迎来到小学生刷题程序!")
print("您将依次回答10道题目\n")
questions = []
for _ in range(10):
question, correct_answer = generate_question()
questions.append((question, correct_answer))
score = 0
for i, (question, correct_answer) in enumerate(questions, start=1):
user_answer = input(f"第{i}题: {question} = ")
try:
user_answer = int(user_answer)
if user_answer == correct_answer:
print("正确!")
score += 1
else:
print(f"错误!正确答案是 {correct_answer}")
except ValueError:
print("请输入一个有效的整数。")
total_questions = len(questions)
accuracy = (score / total_questions) * 100
print(f"\n您答对了 {score} 题")
print(f"您的正确率为 {accuracy:.2f}%\n")
next_round = input("您想再做一次练习吗?(是/否): ")
if next_round.lower() != '是':
break
if __name__ == "__main__":
main()
运行结果如下
**三、实验过程中遇到的问题和解决过程 **
问题1:复数无法表示
问题1解决方案:不能用a+bi,要用a+bj
问题2:程序只能运行一次
问题2解决方案:修正循环结构
**四、其他(感悟、思考等) **
1.本以为复数运算需要额外定义函数,后来却发现程序自己可以解决复数运算。
2.灵活定义一些函数有奇效(如除法、对数的额外条件等)。
参考资料****
零基础学《Python》
python—函数详解