Home > OS >  Python output confussion
Python output confussion

Time:10-15

I am pretty new to Python programming and was following my first ever Python tutorial. I tried a piece of code the trainer used to explain for loop which is as follows.

prices = [10,20,30]

total = 0

for price in prices:
    total  = price
    print(f'{total}')

When the tutor executed his output was simply 60. But when I executed the same code the result comes as,

10 30 60.

Can someone explain to me what I am doing wrong here, please?

PS: https://www.youtube.com/watch?v=_uQrJ0TkZlc&t=5727s is the video I was following and the point where this confusion occurred.

CodePudding user response:

one simple mistake. Indention error! You have mistakenly put the print statement in the loop, so it prints off to the console every time it goes around!

Fix it like this:

prices = [10,20,30]

total = 0

for price in prices:
    total  = price
print(f'{total}')

CodePudding user response:

Solution

The quick solution would be changeing the code.

prices = [10, 20, 30]
total = 0
for price in prices:
    total  = price
print(total)

Explanation

The explanation is that the for loop iterates through your given list. Asuming you have 3 items in your list, the for loop would get executed three times. One time with the first value, the second time with the second value and so on.

Since you want to calculate the total of all prices, you can simply add each price to total, because as I said above the for loop iterates through every single item one by one.

After the for loop you want to print the total value, so don't indent the print statement into your for loop, since you don't want to execute it three times.

  • Related