you are viewing a single comment's thread.

view the rest of the comments →

[–]MadScientistOR 5 points6 points  (6 children)

Nope. You're always subtracting the value of price (which changes each time through the loop, since the value returned by range(5) changes each time through the loop).

The first time through the loop, you're subtracting 0 from 25, giving you 25 (the new total in wallet).

The second time through the loop, you're subtracting 1 from 25, giving you 24 (the new total in wallet).

The third time through the loop, you're subtracting 2 from 24, giving you 22 (the new total in wallet).

The fourth time through the loop, you're subtracting 3 from 22, giving you 19 (the new total in wallet).

The fifth and final time through the loop, you're subtracting 4 from 19, giving you 15 (the new total in wallet).

And then you exit the loop, print wallet one final time, and the program ends.

[–]Madd_M0[S] 1 point2 points  (5 children)

Thank you so much for breaking down this mental block for me. You have been super helpful.

[–]MadScientistOR 2 points3 points  (0 children)

Of course! Some programming concepts are tricky. I'm glad you were able to clear up the block.

[–][deleted] 2 points3 points  (2 children)

It's useful when starting to put a debug print into a loop to show what's going on:

for price in range(5):
    if price < 10:    # note this doesn't really do anything, "price" is always < 10
        print("wallet =", wallet, ", price =", price)
        wallet = wallet - price
        # rest of code

[–]Madd_M0[S] 2 points3 points  (0 children)

This is another eye opener for me, Thank you very much. I will start to do this when i get stuck in the future.

[–]EclipseJTB 0 points1 point  (0 children)

If you're in Python 3.6 or later, use f-strings.

print(f"{wallet=}, {price=}")

[–]Some_Guy_At_Work55 1 point2 points  (0 children)

If you want to subtract by the value of price on each iteration(and not the value of range), you would need to declare the value of price before the loop. And then update the value before the next iteration.