Error: else & elif Statements Not Working in Python

Error: else & elif Statements Not Working in Python

You can combine the else statement with the elif and if statements in Python. But when running if...elif...else statements in your code, you might get an error named SyntaxError: invalid syntax in Python.

It mainly occurs when there is a wrong indentation in the code. This tutorial will teach you to fix SyntaxError: invalid syntax in Python.

Fix the else & elif Statements SyntaxError in Python

Indentation is the leading whitespace (spaces and tabs) in a code line in Python. Unlike other programming languages, indentation is very important in Python.

Python uses indentation to represent a block of code. When the indentation is not done properly, it will give you an error.

Let us see an example of else and elif statements.

Code Example:

num=25
guess=int(input("Guess the number:"))
if guess == num:
    print("correct")
    elif guess < num:
        print("The number is greater.")
else:
    print("The number is smaller.")

Error Output:

  File "c:\Users\rhntm\myscript.py", line 5
    elif guess < num:
    ^^^^
SyntaxError: invalid syntax

The above example raises an exception, SyntaxError, because the indentation is not followed correctly in line 5. You must use the else code block after the if code block.

The elif statement needs to be in line with the if statement, as shown below.

Code Example:

num=25
guess=int(input("Guess the number:"))
if guess == num:
    print("correct")
elif guess < num:
    print("The number is greater.")
else:
    print("The number is smaller.")

Output:

Guess the number:20
The number is greater.

Now, the code runs successfully.

The indentation is essential in Python for structuring the code block of a statement. The number of spaces in a group of statements must be equal to indicate a block of code.

The default indentation is 4 spaces in Python. It is up to you, but at least one space has to be used.

If there is a wrong indentation in the code, you will get an IndentationError in Python. You can fix it by correcting the indent in your code.

Rohan Timalsina avatar Rohan Timalsina avatar

Rohan is a learner, problem solver, and web developer. He loves to write and share his understanding.

Related Article - Python Error

  • Local Variable Referenced Before Assignment Error in Python
  • Python Handling Socket.Error: [Errno 104] Connection Reset by Peer
  • Python Is Not Recognized in Windows 10
  • NameError: The OS Module Is Not Defined in Python
  • Python ValueError: Not Enough Values to Unpack
  • Resolve the TypeError: Can't Multiply Sequence by Non-Int of Type STR in Python