【发布时间】:2022-01-21 05:02:12
【问题描述】:
我已经为一个接受字符串输入的计算器准备了这段代码:
keepAsking = True
equationList = []
while keepAsking: # keep looping until keepAsking is false
print("Please enter the mathematical expression you want the program to evaluate: \n") # taking user input
userInput = input()
equationList.append(userInput)
print("Do you have other operations to add? \n") # another user input (choice)
userChoice = input()
if userChoice.lower() == "yes": # if the user wants to keep asking
keepAsking = True
else:
print(100*"-")
print("|{0:<15s}|{1:^40s}|{2:>40s}|".format("Operation no.", "operation expression", "operation output"))
# if not print the following
print(100*"-")
# For each equation get index and the item itself
for i, item in enumerate(equationList):
# evaluate executes python code
print("|{0:<15d}|{1:^40s}|{2:>40.2f}|".format(i + 1, item, eval(item)))
keepAsking = False
print(100*"-")
但是我想用 For 循环替换 eval() 函数来评估表达式并产生相同的结果,这可能吗?
【问题讨论】:
-
我看不出这个程序是如何工作的。就像如果有人说
1*2作为他们的第一个输入然后yes然后*3它会导致错误,所以也许不是说要添加的操作,你可能会再次说数学表达式......如果你想解析字符串自己来评估它当然是可能的。 nerdparadise.com/programming/parsemathexpr
标签: python loops eval calculator