0

This is the code--

while True:
    spam = 0
    spam + 1
    if spam == 1:
        print('Hello')
    elif spam == 2:
        print('Howdy')
    else:
        print('Greetings!')
        break 

What i want it to do is output "Hello" first, then "Howdy" second and after the third time it output "Greetings" and breaks the code. However the code loops infinitely with "Hello" being the output Thanks in advance for the help!

5 Answers5

1

You want to declare spam outside the while loop so that it does not get reinitilalized to 0 every time. Also, make sure you reassign spam to spam + 1:

spam = 0
while True:
    spam += 1
    if spam == 1:
        print('Hello')
    elif spam == 2:
        print('Howdy')
    else:
        print('Greetings!')
        break 
A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76
1

Firstly, initialize spam outside the loop. Secondly, you might have missed a "=" so you are not updating spam. The correct code should looks like this:

spam = 0
while True:
  spam += 1
  ...
0

The reason why its failing is because:

spam = 0

^ is initialized inside the loop, hence with every iteration, the value of spam is set to 0. Also spam + 1 does not modify spam

Take the var initializing part outside the loop and increment to it after the iteration:

spam = 1            # could be set to spam = 0
while True:
    # spam += 1       # uncomment if spam is set to 0 at top
    if spam == 1:
        print('Hello')
    elif spam == 2:
        print('Howdy')
    else:
        print('Greetings!')
        break
    spam += 1                       # used when spam = 1 at top
DirtyBit
  • 16,613
  • 4
  • 34
  • 55
0

That's because you write the spam variable inside the while loop if you write it outside it will work fine.

spam = 0
while True: 
    spam += 1
    if spam == 1:
        print('Hello')
    elif spam == 2:
        print('Howdy')
    else:
        print('Greetings!')
        break 
0

Try this

spam = 0
a = True
while a is True:
    spam += 1
    if spam == 1:
        print('Hello')
    elif spam == 2:
        print('Howdy')
    else:
        a = False
        print('Greetings!')
trillion
  • 1,207
  • 1
  • 5
  • 15