Python计算器,包括使用列表进行历史检查



我是python的初学者,所以我想通过使用列表创建python计算器(带有历史记录)。但是当我尝试这样做时,它总是给我当我检查历史时"没有过去的计算来显示">

如何修改下面的代码为我的要求?

def add(a,b):
return a+b
def subtract(a,b):
return a-b
def multiply (a,b):
return a*b
def divide(a,b):
try:
return a/b
except Exception as e:
print(e)
def power(a,b):
return a**b
def remainder(a,b):
return a%b
def select_op(choice): 
if (choice == '#'):
print("Done. Terminating")
exit()
elif (choice == '$'):
return main()
elif (choice in ('+','-','*','/','^','%','?')):
while (True):
num1s = str(input("Enter first number: "))
print(num1s)
if num1s.endswith('$'):
return main()
if num1s.endswith('#'):
print("Done. Terminating")
exit()   
try:
num1 = float(num1s)
break
except:
print("Not a valid number,please enter again")
continue

while (True):
num2s = str(input("Enter second number: "))
print(num2s)
if num2s.endswith('$'):
return main()
if num2s.endswith('#'):
print("Done. Terminating")
exit()
try:  
num2 = float(num2s)
break
except:
print("Not a valid number,please enter again")
continue
last_calculation_1=last_calculation_2=last_calculation_3=last_calculation_4=last_calculation_5=last_calculation_6=[]
if choice == '+':
result = add(num1, num2)
msg="{0} {1} {2} = {3}".format(str(num1), str(choice), str(num2), str(result))
print(msg)
last_calculation_1.append(msg)
elif choice == '-':
result = subtract(num1, num2)
msg="{0} {1} {2} = {3}".format(str(num1), str(choice), str(num2), str(result))
print(msg)
last_calculation_2.append(msg)
elif choice == '*':
result = multiply(num1, num2)
msg="{0} {1} {2} = {3}".format(str(num1), str(choice), str(num2), str(result))
print(msg)
last_calculation_3.append(msg)
elif choice == '/':
result =  divide(num1, num2)
msg="{0} {1} {2} = {3}".format(str(num1), str(choice), str(num2), str(result))
print(msg)
last_calculation_4.append(msg)
elif choice == '^':
result = power(num1, num2)
msg="{0} {1} {2} = {3}".format(str(num1), str(choice), str(num2), str(result))
print(msg)
last_calculation_5.append(msg)
elif choice == '%':
result = remainder(num1, num2)
msg="{0} {1} {2} = {3}".format(str(num1), str(choice), str(num2), str(result))
print(msg)
last_calculation_6.append(msg)
elif choice=='?':
last_calculation=last_calculation_1+last_calculation_2+last_calculation_3+last_calculation_4+last_calculation_5+last_calculation_6
# x=[str(i) for i in last_calculation]
if len(last_calculation) ==0:
print("No past calculations to show")
else:
b="n".join(last_calculation)
print(b)
else:
print("Something Went Wrong")
else:
print("Unrecognized operation")
return main()
def main():   
while True:
print("Select operation.")
print("1.Add      : + ")
print("2.Subtract : - ")
print("3.Multiply : * ")
print("4.Divide   : / ")
print("5.Power    : ^ ")
print("6.Remainder: % ")
print("7.Terminate: # ")
print("8.Reset    : $ ")
print("8.History  : ? ")
# take input from the user
choice = input("Enter choice(+,-,*,/,^,%,#,$,?): ")
print(choice)
select_op(choice)
main()    

任务1:声明一个列表来存储前面的操作将运算符、操作数和结果保存为单个字符串,用于每次计算后的每个操作

任务2:实现一个history()函数来处理操作'?'使用新命令' ? '显示已保存的完整操作列表(按执行顺序)。"如果没有以前的计算当历史?命令时,会显示如下信息"No past calculation to show">

这类事情最好使用控件字典来完成。此外,不需要编写加法、减法等函数,因为它们都可以在操作符模块中使用。

这大大简化了问题:

import operator
history = []
control = {
'+': (operator.add, 'Add'),
'-': (operator.sub, 'Subtract'),
'*': (operator.mul, 'Multiply'),
'/': (operator.truediv, 'Divide'),
'^': (operator.pow, 'Power'),
'%': (operator.mod, 'Remainder'),
'#': (None, 'Terminate'),
'$': (None, 'Reset'),
'?': (None, 'History')
}
while True:
for i, (k, v) in enumerate(control.items(), 1):
print(f'{i}. {v[1]:<10}: {k} ')
option = input(f'Choose option ({",".join(control)}): ')
match option:
case '#':
break
case '$':
history = []
case '?':
print(*history, sep='n')
case _:
if t := control.get(option):
a = input('Input first value: ')
b = input('Input second value: ')
try:
r = t[0](float(a), float(b))
print(res := f'{a} {option} {b} = {r}')
history.append(res)
except (ValueError, ZeroDivisionError) as e:
print(e)
else:
print('Invalid optionx07')

这样做的一种方法是摆脱所有的last_calculation列表,并坚持一个名为history的历史列表,并在main函数中初始化它,然后将其作为参数传递给select_op函数,因此它可以在每次后续调用中更新。然后设置逻辑,如果?是输入,则打印history列表的内容。例如:

def add(a,b):
return a+b
def subtract(a,b):
return a-b
def multiply (a,b):
return a*b
def divide(a,b):
try:
return a/b
except Exception as e:
print(e)
def power(a,b):
return a**b
def remainder(a,b):
return a%b
def select_op(choice, history):
if (choice == '#'):
print("Done. Terminating")
exit()
elif (choice == '$'):
return main()
elif (choice in ('+','-','*','/','^','%')):
while (True):
num1s = str(input("Enter first number: "))
print(num1s)
if num1s.endswith('$'):
return main()
if num1s.endswith('#'):
print("Done. Terminating")
exit()
try:
num1 = float(num1s)
break
except:
print("Not a valid number,please enter again")
continue
while (True):
num2s = str(input("Enter second number: "))
print(num2s)
if num2s.endswith('$'):
return main()
if num2s.endswith('#'):
print("Done. Terminating")
exit()
try:
num2 = float(num2s)
break
except:
print("Not a valid number,please enter again")
continue
if choice == '+':
result = add(num1, num2)
msg="{0} {1} {2} = {3}".format(str(num1), str(choice), str(num2), str(result))
print(msg)
history.append(msg)
elif choice == '-':
result = subtract(num1, num2)
msg="{0} {1} {2} = {3}".format(str(num1), str(choice), str(num2), str(result))
print(msg)
history.append(msg)
elif choice == '*':
result = multiply(num1, num2)
msg="{0} {1} {2} = {3}".format(str(num1), str(choice), str(num2), str(result))
print(msg)
history.append(msg)
elif choice == '/':
result =  divide(num1, num2)
msg="{0} {1} {2} = {3}".format(str(num1), str(choice), str(num2), str(result))
print(msg)
history.append(msg)
elif choice == '^':
result = power(num1, num2)
msg="{0} {1} {2} = {3}".format(str(num1), str(choice), str(num2), str(result))
print(msg)
history.append(msg)
elif choice == '%':
result = remainder(num1, num2)
msg="{0} {1} {2} = {3}".format(str(num1), str(choice), str(num2), str(result))
print(msg)
history.append(msg)
else:
print("Something Went Wrong")
elif choice=='?':
if len(history) ==0:
print("No past calculations to show")
else:
b="n".join(history)
print(b)
else:
print("Unrecognized operation")
return main()
def main():
history = []
while True:
print("Select operation.")
print("1.Add      : + ")
print("2.Subtract : - ")
print("3.Multiply : * ")
print("4.Divide   : / ")
print("5.Power    : ^ ")
print("6.Remainder: % ")
print("7.Terminate: # ")
print("8.Reset    : $ ")
print("8.History  : ? ")
# take input from the user
choice = input("Enter choice(+,-,*,/,^,%,#,$,?): ")
print(choice)
select_op(choice, history)
main()

还可以对代码进行大量的进一步优化,例如创建一个字典来保存操作符及其相应的函数,还可以使用另一个循环来选择数字以减少重复代码的数量。

这是与上面相同的解决方案,但优化了可读性和减少代码重复。

def add(a,b):
return a+b
def subtract(a,b):
return a-b
def multiply (a,b):
return a*b
def divide(a,b):
try:
return a/b
except Exception as e:
print(e)
def power(a,b):
return a**b
def remainder(a,b):
return a%b
def select_op(choice, history):
if (choice == '#'):
print("Done. Terminating")
exit()
elif (choice == '$'):
return main()
elif (choice in ('+','-','*','/','^','%')):
nums = []
for _ in range(2):
while (True):
numstr = str(input("Enter first number: "))
print(numstr)
if numstr.endswith('$'):
return main()
if numstr.endswith('#'):
print("Done. Terminating")
exit()
try:
num = float(numstr)
nums.append(num)
break
except:
print("Not a valid number,please enter again")
continue
funcmap = {
"+": add,
"-": subtract,
"*": multiply,
"/": divide,
"^": power,
"%": remainder
}
if choice in funcmap:
num1,num2 = nums
result = funcmap[choice](num1, num2)
msg = "{0} {1} {2} = {3}".format(num1, choice, num2, result)
print(msg)
history.append(msg)
else:
print("Something Went Wrong")
elif choice=='?':
if len(history) ==0:
print("No past calculations to show")
else:
b="n".join(history)
print(b)
else:
print("Unrecognized operation")
return main()
def main():
history = []
while True:
print("Select operation.")
print("1.Add      : + ")
print("2.Subtract : - ")
print("3.Multiply : * ")
print("4.Divide   : / ")
print("5.Power    : ^ ")
print("6.Remainder: % ")
print("7.Terminate: # ")
print("8.Reset    : $ ")
print("8.History  : ? ")
# take input from the user
choice = input("Enter choice(+,-,*,/,^,%,#,$,?): ")
print(choice)
select_op(choice, history)
main()

最新更新