0

While loop question

I wrote the following code to practice while loops, however I’m getting an unexpected answer for the number 5. I thought the code would print out "you can count that on one hand". Instead it’s outputting "you need two hands to count that many". Can someone explain why it’s the latter and not the former? The other numbers work as expected. Thanks. Code: i = 1 while i <= 10: print(i) i = i + 1 if i <= 5: print("you can count that on one hand") else: print("you need two hands to count that many") print("Great job!")

6th Dec 2018, 11:25 PM
Steve Fernandez
Steve Fernandez - avatar
2 Answers
+ 3
you are incrementing i before if, so for 1. test you have i=2 then for 5. test you have i=6 move i = i + 1 after if else
7th Dec 2018, 12:04 AM
zemiak
0
That worked, thanks zemiak!
7th Dec 2018, 2:02 AM
Steve Fernandez
Steve Fernandez - avatar