Python Forum

Full Version: Whats wrong with the elif?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
>>> x = int(input("Please enter an integer: "))
Please enter an integer: 42
>>> if x < 0:
x = 0
print('Negative changed to zero')


>>> elif x == 0:

SyntaxError: invalid syntax
>>>



I was trying to run through the Python tutorial. This is 4.1
it's not complete,

elif x == 0: then what ?

x = int(input("Please enter an integer: "))
if x < 0:
    x = 0
    print('Negative changed to zero', x)
elif x == 0:
    print(x)
else:
    print(x)
You are trying to do an if/elif in interactive mode. This is a bit tricky. You need to complete your if/elif/else before getting back to the >>> prompt. If you're back that far, the if section is complete and you can't start with elif, but only with a new if.

Putting all this into a file and executing the file is much easier. But here is a similar thing in interactive mode. Note that after the print, I immediately give the (unindented) elif and don't get back to the ">>>" prompt.

>>> x = int(input("Please enter an integer: "))
Please enter an integer: 42
>>> if x < 0:
...   x = 0
...   print("Negative changed to zero")
... elif x == 0:
...   print("Don't enter zero")
... else:
...   print(f"Your positive integer was {x}")
...
Your positive integer was 42
Unless I am debugging or experimenting I don't enter code at the Python prompt. Write code in a file (i.e. myprogram.py) and run the file "python myprogram.py".