def gukan(count): while count!=100: print(count) count=count+1; gukan(0)
My question is: When I try to increment by 3 or 9 instead of 1 in count=count+1
I get an infinite loop - why is that?
The first line defines the variable. The second line loops it to 100, the third adds 1 to a and the 4th divides a by 3 and if there is no remainder (0) it will print that number otherwise it will print a blank line.
print(x,end=" ")#print the number. Code Explanation : The above code is in Python language, which holds one for loop which runs for the value of 1 to 50. Then the print statement will prints every value from one to 50 using x variable, because the x variable will scan the all element one by one.
The answers here have pointed out that because after incrementing count it doesn't equal exactly 100, then it keeps going as the criteria isn't met (it's likely you want <
to say less than 100).
I'll just add that you should really be looking at Python's builtin range
function which generates a sequence of integers from a starting value, up to (but not including) another value, and an optional step - so you can adjust from adding 1 or 3 or 9 at a time...
0-100 (but not including 100, defaults starting from 0 and stepping by 1):
for number in range(100): print(number)
0-100 (but not including and makes sure number doesn't go above 100) in steps of 3:
for number in range(0, 100, 3): print(number)
When you change count = count + 1
to count = count + 3
or count = count + 9
, count
will never be equal to 100. At the very best it'll be 99. That's not enough.
What you've got here is the classic case of infinite loop: count
is never equal to 100 (sure, at some point it'll be greater than 100, but your while
loop doesn't check for this condition) and the while
loop goes on and on.
What you want is probably:
while count < 100: # Or <=, if you feel like printing a hundred.
Not:
while count != 0: # Spaces around !=. Makes Guido van Rossum happy.
Now the loop will terminate when count >= 100
.
Take a look at Python documentation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With