0

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!

2
  • check your indentation of the last line. I believe it should be part of your while loop code Commented Aug 3, 2016 at 15:59
  • As written, your while loop stops as soon as spam is 5, why do you think it would print 6? Commented Aug 3, 2016 at 16:03

3 Answers 3

3

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?

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

0

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 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.