Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Whats wrong with the elif?
#1
>>> 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
Reply
#2
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)
Reply
#3
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
Reply
#4
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".
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Am I wrong or is Udemy wrong? String Slicing! Mavoz 3 2,386 Nov-05-2022, 11:33 AM
Last Post: Mavoz
  Whats Wrong!? rjay81 3 2,214 May-13-2020, 08:02 PM
Last Post: rjay81
  Can u see this code and tell whats wrong with it? AhmadKamal 14 5,184 Apr-29-2020, 11:09 AM
Last Post: jefsummers
  python gives wrong string length and wrong character thienson30 2 2,941 Oct-15-2019, 08:54 PM
Last Post: Gribouillis
  Whats a good design/approach? hshivaraj 1 1,742 Sep-16-2019, 01:44 AM
Last Post: snippsat
  Whats the right way to refactor this Big if/elif/elif ? pitosalas 1 2,214 Jul-28-2019, 05:52 PM
Last Post: ichabod801
  elevator simulator...whats the wrong at this code? tasos710 5 5,836 Jun-11-2019, 01:38 AM
Last Post: micseydel
  whats the difference between sys.exit() and break? mitmit293 1 4,083 Jan-27-2019, 09:46 PM
Last Post: ichabod801
  Whats wrong with this code? student1 1 2,373 May-18-2018, 04:19 PM
Last Post: skorpius_
  I have no clue whats wrong... Jack_03 1 2,785 Sep-28-2017, 05:36 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020