简体   繁体   English

while/for 循环中的错误是什么?

[英]what is the mistake in the while/for loop?

This is the output using the wrong for/while-loop operation:这是 output 使用错误的 for/while 循环操作:

current value is 60当前值为 60

current value is 120当前值为 120

total value is 120总值为 120

This is what I would like it to be:这就是我想要的:

current value is 10当前值为 10

current value is 30当前值为 30

total value is 30总值为 30

prices = [10, 20, 30]
total = 0
steps = 0
step_limit = 2
while steps < step_limit:
    steps +=1
    for i in prices:
        total += i
    print(f'current value is {total}')
print(f'total value is {total}')

If you want to add each element from the list, the problem that arises here is in the following part of your code:如果要添加列表中的每个元素,则此处出现的问题出在代码的以下部分:

for i in prices:
    total += i

This means that you iterate through each element inside the list and add it to the total (10+20+30).这意味着您遍历列表中的每个元素并将其添加到总数 (10+20+30) 中。 This is done 2 times, so the total will be 120.这样做了 2 次,所以总数为 120。

You have to replace that part of the code with something that accesses only one element at a time.你必须用一次只访问一个元素的东西替换那部分代码。 For instance:例如:

total += prices[steps]

If you desire to add the last element and display the total straight away with it, you can add the last price outside of the while loop right before the message display at the end:如果您希望添加最后一个元素并立即显示总价,您可以在最后的消息显示之前在while循环之外添加最后一个价格:

total += prices[steps]
print(f'total value is {total}')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM