gpt4 book ai didi

Python计算器: Key Error

转载 作者:行者123 更新时间:2023-12-01 04:32:32 25 4
gpt4 key购买 nike

我的代码中出现以下错误(如下):

Traceback (most recent call last):
File "2.py", line 29, in <module>
print calculate(raw_input("enter expression"))
File "2.py", line 27, in calculate
return operations[operation](int(firstnum), int(secondnum))
KeyError: None

我已经尝试多次检查代码,但仍然不明白为什么将正确的操作分配给变量“operator”,然后调用字典“operations”的正确函数。

operations = {
"+": lambda x, y: x + y,
"-": lambda x, y: x - y,
"*": lambda x, y: x * y,
"/": lambda x, y: x / y
}

def calculate(expr):
firstnum = ""
secondnum = ""
operation = None
print expr
for char in expr:
if char.isdigit():
if firstnum != "":
secondnum += char
else:
firstnum += char
elif char.isspace():
break
elif char in operations:
operation = char
print operation
else:
raise Exception("invalid character: " + char)
return operations[operation](int(firstnum), int(secondnum))

print calculate(raw_input("enter expression"))

编辑:删除错误的缩进后,代码会处理例如 7*4,但在 7 * 4 处给出相同的键错误。不明白为什么会发生这种情况。

EDIT2:我只是将中断更改为通过

谢谢大家!

最佳答案

你的缩进弄错了;您的 return 位于您的 for 内,因此一旦您到达第一个循环的末尾,它将立即执行。将其凹陷一次,使其位于外部。

关于Python计算器: Key Error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32174051/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com