I'm learning Python. My goal is to print out 1 through 5, skipping 3, using a while loop, if statement, and keyword continue
. My code below prints out just 1 2, and not 1 2 4 5.
i = 1
while i <= 5:
if i == 3:
continue
print(i)
i = 1
- Why does this loop stop when
i == 3
, rather than skipping 3 and continuing withi = 4
andi = 5
? - How would you correct this code so that it prints 1 2 4 5 (continuing/skipping 3)?
CodePudding user response:
To fix this you can do it like this, print the value when it is not three and then you don't even need to use continue
:
i = 1
while i <= 5:
if i != 3:
print(i)
i = 1
However, a faster and easier solution would be this:
for i in range(1, 5 1):
if i != 3:
print(i)
Or in the for
loop case it would be possible to use continue
because the for loop will continue to the next element:
for i in range(1, 5 1):
if i == 3:
continue
print(i)
And just because, but you can also use a short (linewise) (and fast too) solution like this one:
print('\n'.join(str(i) for i in range(1, 5 1) if i != 3))
CodePudding user response:
Once you reach 3 the program will never increase i
anymore and will loop forever
You could increment before the test:
i = 0
while i <= 5:
i = 1
if i == 3:
continue
print(i)
CodePudding user response:
When you call continue
, the increment will be skipped and i
will be stuck at 3 forever
CodePudding user response:
You're stuck in an infinite loop. When you continue
, you never increment i
, so it stays 3 forever.
CodePudding user response:
Because continue
makes you not fulfill the rest of your code. Therefore, you just have an infinite loop. You can see that if you run
i = 1
while i <= 5:
if i == 3:
print(i)
continue
print(i)
i = 1
If you want to do this in this method, you can just increment i before your continue, i.e.
i = 1
while i <= 5:
if i == 3:
i =1
continue
print(i)
i = 1
CodePudding user response:
Your loop doesn't stop once you hit 3, rather it continues indefinitely as you always skip incrementing i
once the value of i
reaches 3.
You need to do something in your if
block before you continue
to ensure you don't get stuck in an infinite loop.
CodePudding user response:
You have an infinite loop, when you reach i == 3
, you want to skip it, and you do it by using continue
.
continue
means going back to the while
condition and evaluating it.
Because you didn't increment i
, the statement will always be true (always less than 5), but because you didn't change i
, the if
condition will also be always true. And your code loops inifintely.
You need to change the value of i
before continue
in the if
block.