HDR
HDR

Reputation: 76

Increment and while loop

Following is the code I'm executing in IDLE for Python 3.5.2 on Windows 10:

spam = 0
while spam < 5:
    print('Hello, world.')
    spam = spam + 1

I can see Hello World printed 5 times however when entering spam in IDLE, I can see the integer 5. Shouldn't this be logically int 6 since while loop will stop as soon as the spam is incremented by 1 from 5 and spam variable is passed with the incremented int?

Thank you!

Upvotes: 0

Views: 11764

Answers (3)

cdarke
cdarke

Reputation: 44444

I added a print statement to illustrate what is happening:

spam = 0
while spam < 5:
    print('Hello, world.')
    spam = spam + 1
    print(spam, 'spam is < 5?', spam < 5, "\n")

The output is:

Hello, world.
1 spam is < 5? True 

Hello, world.
2 spam is < 5? True 

Hello, world.
3 spam is < 5? True 

Hello, world.
4 spam is < 5? True 

Hello, world.
5 spam is < 5? False 

Upvotes: 0

Jonathon Ogden
Jonathon Ogden

Reputation: 1582

spam < 5 can be read as spam is less than 5, so it'll only increment from 0 to 4. In the 4th (last) iteration, spam = 4 so it prints 'Hello, world' and then spam + 1 = 5. At that point it will attempt another iteration, but spam < 5 is no longer true and therefore will exit the loop.

For reference: < means less than, <= means less than or equal to.

Any particular reason you think you'd get 6?

Upvotes: 3

Matt Coats
Matt Coats

Reputation: 332

Your while loop is "while spam is less than 5", not "while spam is less than or equal to 5". The last iteration occurs when spam is 4, and then it gets incremented one last time to 5.

If spam equals 5, it is not less than 5, so the while loop stops iterating.

Upvotes: 2

Related Questions