思路如下:从键盘接收输入1/2/3/4,定义x和y的值,如果键盘输入为1,执行x+y,输出计算结果,并将计算过程及结果保存历史;如果键盘输入为2,执行x-y,输出计算结果,并将计算过程及结果保存历史;如果键盘输入为3,输出历史计算结果;如果键盘输入为4,输出历史计算结果,并退出程序。'''1.接受键盘输入的结果'''choice=input("请选择操作(1/2/3/4)")x=8y=7'''2.计算逻辑选择1(choice=1),对x,y执行加法选择2(choice=2),对x,y执行减法选择3(choice=3),查看计算历史选择4(choice=4),退出程序'''history=[]while True: if choice=='1': result=x+y print(f"结果:{x}+{y}={result}") history.append(f"结果:{x}+{y}={result}") elif choice=='2': result=x-y print(f"结果:{x}-{y}={result}") history.append(f"结果:{x}-{y}={result}") elif choice=='3': for h in history: print(h) elif choice=='4': for h in history: print(h) break else: print('无效选择,请重新输入')
以上计算脚本是否有问题?----是否会进入死循环?原因在那里?2.简单计算器脚本(2):修改上一个脚本,包括计算逻辑和x、y也接收从键盘输入。history=[]while True: ''' 1.接受键盘输入的结果 ''' choice=input("请选择操作(1/2/3/4)") ''' 2.计算逻辑 选择1(choice=1),对x,y执行加法1 选择2(choice=2),对x,y执行减法 选择3(choice=3),查看计算历史 选择4(choice=4),退出程序 ''' if choice=='1': x=int(input('请输入x:')) y=int(input('请输入y:')) result=x+y print(f"结果:{x}+{y}={result}") history.append(f"结果:{x}+{y}={result}") elif choice=='2': x=int(input('请输入x:')) y=int(input('请输入y:')) result=x-y print(f"结果:{x}-{y}={result}") history.append(f"结果:{x}-{y}={result}") elif choice=='3': for h in history: print(h) elif choice=='4': for h in history: print(h) break else: print('无效选择,请重新输入')
def add(x,y): result=x+y history.append(f"结果:{x}+{y}={result}") return resultdef subtract(x,y): result=x-y history.append(f"结果:{x}-{y}={result}") return resultdef show_history(): for h in history: print(h)history=[]while True: ''' 1.接受键盘输入的结果 ''' choice=input("请选择操作(1/2/3/4)") ''' 2.计算逻辑 选择1(choice=1),对x,y执行加法1 选择2(choice=2),对x,y执行减法 选择3(choice=3),查看计算历史 选择4(choice=4),退出程序 ''' if choice=='1': x=int(input('请输入x:')) y=int(input('请输入y:')) result=add(x,y) print(f"结果:{x}+{y}={result}") elif choice=='2': x=int(input('请输入x:')) y=int(input('请输入y:')) result=subtract(x,y) print(f"结果:{x}-{y}={result}") elif choice=='3': show_history() elif choice=='4': show_history() break else: print('无效选择,请重新输入')
4.自定义函数(将加、减、输出历史和主程序定义为函数,并调用)def add(x,y): result=x+y history.append(f"结果:{x}+{y}={result}") return resultdef subtract(x,y): result=x-y history.append(f"结果:{x}-{y}={result}") return resultdef show_history(): for h in history: print(h)history=[]def calculator_menu(): while True: ''' 1.接受键盘输入的结果 ''' choice=input("请选择操作(1/2/3/4)") ''' 2.计算逻辑 选择1(choice=1),对x,y执行加法1 选择2(choice=2),对x,y执行减法 选择3(choice=3),查看计算历史 选择4(choice=4),退出程序 ''' if choice=='1': x=int(input('请输入x:')) y=int(input('请输入y:')) result=add(x,y) print(f"结果:{x}+{y}={result}") elif choice=='2': x=int(input('请输入x:')) y=int(input('请输入y:')) result=subtract(x,y) print(f"结果:{x}-{y}={result}") elif choice=='3': show_history() elif choice=='4': show_history() break else: print('无效选择,请重新输入')print('计算器菜单') print('1 加法') print('2 减法') print('3 查看历史') print('4 退出') calculator_menu()
5.执行程序,输出结果如下图所示。
本案例基于《Python程序设计与人工智能项目教程》(梁婷婷等编著)第75页的案例,加工、修改和拓展而来。