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

2024-05-15 22:02:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编一个计算器

例如,我有以下几点:

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)”不起作用。有什么办法解决这个问题吗


Tags: 代码innumberforif整数resultelse
2条回答

请在下面查找修改后的代码:

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

print(result)

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

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

^{tb1}$

循环之后,最后一个数字刚好挂在number中,但从未添加到result。所以result最终在2而不是5结束

如果格式始终为“number operator number”,则不需要循环。直接从列表中访问值:

splitted_calculation = ["2", "+", "2"]
left_number = int(splitted_calculation[0])
right_number = int(splitted_calculation[2])
operator = splitted_calculation[1]
if operator == '+':
    result = left_number + right_number
elif operator == '-'
    result = left_number - right_number
# repeat for others.

如果公式更复杂(“例如2+2+2”),则可以修改循环以存储最后一个运算符,并对数字进行计算:

splitted_calculation = ["-5", "+", "2", "-", "3"]
result = 0
last_op = "+"
for n in splitted_calculation:
    if n in "+-*/":
        last_op = n
    else:
        if last_op == '+': result += int(n)
        elif last_op == '-': result -= int(n)
        elif last_op == '*': result *= int(n)
        elif last_op == '/': result /= int(n)

输出:

-6

相关问题 更多 >