如何在for循环中将值存储到变量中



我在编程计算器。

例如,我有以下内容:

result = 0
splitted_calculation = ["2", "+", "2"]
for thing in splited_calculation:
if thing == "+":
result = result + number
else:
number = int(thing)
print(result)

我想要的是,如果for循环中的变量是一个整数,那么该值被存储,以便我可以将前一个整数添加到当前for循环中的下一个整数。然而,当我运行代码时,我总是得到0。似乎"number = int(thing)"&;不是工作。有什么建议来解决这个问题吗?

代码的问题(除了打字错误)是最后一个数字被忽略了。一步一步地完成它——在你的脑海中,在纸上,或者用调试器。

循环的迭代。对于本例,为了清晰起见,将其更改为['2','+','3']:

<表类> SIteration thing 操作 number result tbody><<tr>12将其分配给number202+添加numberresult2233将其分配给number32

查找修改后的代码:

result = 0
splited_calculation = ["2", "+", "2"]
for thing in splited_calculation:
if thing != "+":
result += int(thing)
print(result)

最新更新