How to Fix 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.
Related Article - Python Error
- Can Only Concatenate List (Not Int) to List in Python
- How to Fix Value Error Need More Than One Value to Unpack in Python
- How to Fix ValueError Arrays Must All Be the Same Length in Python
- Invalid Syntax in Python
- How to Fix the TypeError: Object of Type 'Int64' Is Not JSON Serializable
- How to Fix the TypeError: 'float' Object Cannot Be Interpreted as an Integer in Python