Sonu
Sonu

Reputation: 3

While True loop breaking early

I was expecting the result as:

1
2
3
rest of the code

However I only see:

1
rest of the code

Can anyone help clear my understanding?

This is my code:

i = 0
while True:
    i += 1
    print(i)
    if(i <= 3):
        break
print("rest of the code")

Upvotes: 0

Views: 45

Answers (2)

Tomerikoo
Tomerikoo

Reputation: 19432

The whole point of a while loop is

for repeated execution as long as an expression is true

So instead of putting an if inside the loop, just use the loop's condition:

i = 0
while i <= 3:
    i += 1
    print(i)

print("rest of the code")

Upvotes: 2

Aur&#233;lien
Aur&#233;lien

Reputation: 1655

The loop stops, because i is equal to 1, so 1 < 3, so the break instruction is called. Maybe the following code is what you want to achieve:

i=0
while True:
    i+=1
    print(i)
    if(i == 3):
        break
print("rest of the code")

Upvotes: 1

Related Questions