Table of Contents
What Will You Learn
In this lesson, you'll explore how Python uses if
, else
, and elif
statements to execute code based on specific conditions. You'll learn the correct syntax, nesting strategies, and real-world use cases that require conditional branching. This foundation is crucial for building responsive, intelligent Python programs that adapt to different inputs and states.
Control flow statements like if
, else
, and elif
are essential tools in any programming language, especially in Python. They allow your
program to make decisions and execute certain blocks of code based on conditions. Without control flow, your script would execute sequentially from top to bottom, regardless of
context or input. That would make it impossible to build dynamic, responsive, or interactive applications.
In Python, the if…else
structure is one of the first decision-making tools you'll learn. It checks whether a condition is true and runs specific code accordingly. As
a beginner, you’ll rely heavily on these constructs to control what your program does in different scenarios. They’re used in loops, validations, calculations, and almost every
kind of logic.
What Does an if/else Statement Look Like in Python?
The if…else
statement in Python checks a condition and chooses between two different blocks of code. If the condition evaluates to True
, the
if
block runs. If it's False
, the else
block runs instead. This is one of the clearest and most readable decision-making structures in any
programming language.
Here's the example of if else python in one line:
result = "Even" if number % 2 == 0 else "Odd"
In this example, the variable result
will be assigned the string "Even" if number
is even, and "Odd" if it is not.
Here's the basic syntax:
x = 10
if x > 5:
print("x is greater than 5")
else:
print("x is 5 or less")
In this example, if x
is greater than 5, the program prints "x is greater than 5". If not, it prints "x is 5 or less".
In Python, indentation is crucial. The code inside the
if
andelse
blocks must be indented to indicate that it belongs to that block. This is different from many other languages that use curly braces or keywords to define blocks.
Let’s break down the elements:
Part | Description |
if |
Starts the conditional statement |
Condition | An expression that evaluates to True or False |
: |
Indicates the start of an indented block |
else: |
Executes when the if condition is not met |
Indentation | Required in Python; shows the scope of the block |
This structure is easy to scale with more logic using elif
(short for “else if”), which we’ll discuss next.
How to Do Else If in Python
In Python, the equivalent of “else if” from other languages is written as elif
. It allows you to check multiple conditions in sequence. The interpreter evaluates
each if
or elif
condition in order and runs the first block where the condition is True
. If none of them are true, and there is an
else
, that block runs by default.
Example:
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
else:
print("Grade: C or lower")
Using elif
helps avoid deeply nested if
statements and keeps your logic readable and efficient.
What Is the Difference Between if and if else Statement in Python?
An if
statement in Python checks a single condition and executes a block of code only if that condition is true. If the condition is false, nothing happens — the
interpreter skips over the if
block entirely. In contrast, an if…else
structure allows you to handle both outcomes — when the condition is true and when
it's false.
For example:
# if only
if x > 0:
print("Positive number")
# if...else
if x > 0:
print("Positive")
else:
print("Zero or negative")
The if…else
form is more complete and ensures your program responds in all scenarios, not just when the condition is true.
Why Do We Use If/Else Statements in Python?
The if/else
statement is one of the most important tools in programming because it allows your code to make decisions. In real-world programs, actions often depend
on conditions — such as user input, data validation, or program state. Without control flow, a program would always behave the same way, regardless of the situation. That’s why
conditional logic is essential for writing flexible and intelligent code.
Python’s if
, elif
, and else
keywords give you full control over execution depending on multiple logical cases. It helps your program
respond correctly, whether it's a login check, form input validation, or choosing between calculation branches. These structures also make your code cleaner and easier to
understand.
Key reasons to use if/else in Python:
- User input validation. Check if the user entered correct data before continuing the program.
- Branching logic. Choose between multiple paths of execution depending on specific conditions.
- Error prevention. Avoid performing invalid operations (e.g., dividing by zero).
- Controlling program flow. Stop or redirect actions when certain criteria are not met.
- Dynamic behavior. Make the program react to different values or system states.
- Simple decision-making. Quickly evaluate whether a condition is met and take appropriate action.
- Combining with loops. Control execution within
while
orfor
loops based on dynamic logic. - Fallback defaults. Provide a default behavior with
else
if none of the conditions are satisfied.
Common Beginner Mistakes
1. Missing Indentation After if
or else
Block
The mistake: Beginners often forget to indent the code that follows an if
, else
, or elif
statement. Since indentation is
syntactically required in Python, this leads to an IndentationError
.
Incorrect:
if x > 0:
print("Positive number")
Correct:
if x > 0:
print("Positive number")
Solution: Always indent the block under if
, else
, or elif
. The Python standard is 4 spaces.
2. Using elseif
Instead of elif
The mistake: Developers with experience in other languages (like JavaScript or PHP) may use elseif
, which is not valid in Python. This causes a
SyntaxError
.
Incorrect:
if x > 0:
print("Positive")
elseif x == 0:
print("Zero")
Correct:
if x > 0:
print("Positive")
elif x == 0:
print("Zero")
Solution: In Python, the correct keyword is elif
— short for "else if."
3. Confusing =
with ==
The mistake: New programmers sometimes confuse the assignment operator =
with the equality operator ==
. Using =
in a
condition raises a SyntaxError
.
Incorrect:
if x = 10:
print("x is ten")
Correct:
if x == 10:
print("x is ten")
Solution: Use ==
when comparing values. Remember: =
assigns, ==
compares.
4. Empty if
or else
Block
The mistake: Writing an if
or else
without any code inside it results in an IndentationError
or logical confusion.
Incorrect:
if x > 0:
elif x == 0:
print("Zero")
Correct:
if x > 0:
pass
elif x == 0:
print("Zero")
Solution: Use the pass
keyword if you want a placeholder without actual logic yet.
5. Comparing Strings with Numbers Without Type Conversion
The mistake: Comparing a string input with a number without converting its type always returns False
or causes a TypeError
.
Incorrect:
x = input("Enter a number: ")
if x > 5:
print("Greater than 5")
Correct:
x = input("Enter a number: ")
if int(x) > 5:
print("Greater than 5")
Solution: Always convert strings to integers (int()
) or floats (float()
) before numerical comparisons.
6. Overusing Nested if
Statements
The mistake: Beginners often create deeply nested if...else
blocks, which makes the code hard to read and maintain.
Incorrect:
if x > 0:
if x < 10:
if x % 2 == 0:
print("Even and between 0 and 10")
Better:
if 0 < x < 10 and x % 2 == 0:
print("Even and between 0 and 10")
Solution: Combine conditions using logical operators (and
, or
) to reduce unnecessary nesting and improve clarity.
FAQ on if…else Statement in Python
How to write if else in Python?
To write an if...else
Python code, you use the if
keyword followed by a condition, a colon, and an indented block of code. The else
keyword
handles the opposite case. This structure helps your code decide between two execution paths. Here's an example:
age = 20
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
How to use else if in Python?
Python doesn't use the phrase else if
— it uses elif
, which stands for "else if". It allows you to check multiple conditions without nesting multiple
if
statements. Here's a simple example:
score = 75
if score >= 90:
print("Grade A")
elif score >= 70:
print("Grade B")
else:
print("Grade C")
How to exit if else statement in Python?
The if...else
structure executes only one block based on the first True
condition and then moves forward with the rest of the code. There's no need
for a special "exit" keyword. However, you can use return
, break
, or exit()
if you want to stop further execution. For example:
def check_login(user):
if user == "admin":
print("Access granted")
return
else:
print("Access denied")
return
Can you use if else without else in Python?
Yes, you can use an if
statement without else
. In fact, it’s very common. Sometimes, you only need to perform an action if a condition is true and do
nothing otherwise. For example:
temperature = 35
if temperature > 30:
print("It's hot today.")
How many elif can you use in Python?
There’s no limit to the number of elif
blocks you can use. You can write as many as needed to cover all possible conditions. For example:
day = "Wednesday"
if day == "Monday":
print("Start of the week")
elif day == "Wednesday":
print("Midweek")
elif day == "Friday":
print("Almost weekend")
else:
print("Normal day")
What happens if none of the conditions in if/elif/else match?
If none of the if
or elif
conditions are true and there’s no else
clause, Python simply skips that block and continues execution. For
example:
x = 3
if x > 5:
print("Greater than 5")
elif x == 5:
print("Equal to 5")
Since neither condition is true, the program does nothing and moves on. That’s why it’s good practice to include an else
block when a fallback action is important
— it catches everything that wasn’t handled before.