Python if-else: A Simple Guide with Examples
Programs often need to make decisions.
For example:
- If the temperature is high, show a warning.
- If a file exists, read it.
- If marks are above 40, consider the student passed.
- If a value is missing, handle it differently.
Python uses "if", "elif", and "else" to handle this kind of logic.
These are simple statements, but you will use them regularly when writing Python programs.
- Python if statement
Let's start with a simple example.
age = 25
if age >= 18:
print("Adult")
The condition "age >= 18" is checked first.
If it is "True", Python runs the indented code below it.
If it is "False", Python skips that code.
- Python if-else
Sometimes we have two possible results.
For example:
marks = 65
if marks >= 40:
print("Pass")
else:
print("Fail")
Here, Python does one of two things:
- "marks >= 40" is true → "Pass"
- "marks >= 40" is false → "Fail"
- Python if-elif-else
What if there are several possible results?
We can use "elif".
marks = 78
if marks >= 75:
print("Distinction")
elif marks >= 60:
print("First Class")
elif marks >= 40:
print("Pass")
else:
print("Fail")
Python checks the conditions from top to bottom.
For "marks = 78", the first condition is true, so Python prints:
Distinction
It does not continue checking the remaining "elif" conditions.
- Multiple if statements vs if-elif-else
This is an important difference.
With separate "if" statements:
num = 10
if num > 0:
print("Positive")
if num > 5:
print("Greater than 5")
Both conditions are checked independently.
With "if-elif":
num = 10
if num > 0:
print("Positive")
elif num > 5:
print("Greater than 5")
Once the first condition is true, Python skips the "elif".
A simple way to remember this:
Separate "if" statements are independent.
"if-elif-else" is one chain of conditions.
- Using "and"
We can combine conditions with logical operators.
With "and", all conditions must be true.
age = 25
salary = 50000
if age >= 18 and salary >= 30000:
print("Eligible")
Both conditions need to be "True" for the message to be printed.
- Using "or"
With "or", at least one condition needs to be true.
day = "Saturday"
if day == "Saturday" or day == "Sunday":
print("Weekend")
The condition is true because "day == "Saturday"" is true.
- Using "not"
"not" reverses a Boolean condition.
is_active = False
if not is_active:
print("Account is inactive")
Since "is_active" is "False", "not is_active" is "True".
- Nested if
An "if" statement can be placed inside another "if".
age = 25
has_id = True
if age >= 18:
if has_id:
print("Access allowed")
This is called a nested "if".
Nested conditions are sometimes useful, but too many levels of nesting can make code difficult to read.
- Python conditional expression
For a simple two-way decision, Python provides a conditional expression.
age = 20
result = "Adult" if age >= 18 else "Minor"
print(result)
This is often called a ternary expression.
It can make short conditions more compact.
For complicated logic, however, a normal "if-else" statement is usually easier to understand.
- Checking positive, negative, or zero
Here is another simple example:
num = -5
if num > 0:
print("Positive")
elif num < 0:
print("Negative")
else:
print("Zero")
Changing "num" to "10", "-10", or "0" will produce different results.
- Checking a leap year
A slightly more interesting example is checking whether a year is a leap year.
year = 2024
if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0):
print("Leap year")
else:
print("Not a leap year")
This example combines the modulo operator "%" with "and" and "or".
Try these values:
2024
2023
2000
1900
and see what happens.
- Comparing two numbers
We can also use conditions to compare values.
a = 25
b = 40
if a > b:
print("a is larger")
elif b > a:
print("b is larger")
else:
print("Both are equal")
The final "else" handles the case where both values are equal.
- Using if inside a function
Conditional logic is also commonly used inside functions.
def check_age(age):
if age < 18:
return "Minor"
return "Adult"
print(check_age(25))
Here, the function returns ""Minor"" when the age is below 18. Otherwise, it returns ""Adult"".
Notice that we don't need an "else" after "return".
Once "return" runs, the function ends.
- Common Python if-else mistakes
Using "=" instead of "=="
Use "=" when assigning a value:
age = 18
Use "==" when comparing values:
if age == 18:
print("Age is 18")
Incorrect indentation
Python uses indentation to define code blocks.
This is incorrect:
if age >= 18:
print("Adult")
The correct version is:
if age >= 18:
print("Adult")
Using "true" and "false"
Python uses "True" and "False".
is_active = True
if is_active:
print("Active")
"true" and "false" are not the Python Boolean values.
A few things to practice
After understanding the examples above, try writing these programs yourself:
- Check whether a number is even or odd.
- Find the largest of three numbers.
- Check whether a person is eligible based on age.
- Convert marks into a grade.
- Check whether a number is positive, negative, or zero.
- Check whether a year is a leap year.
- Check whether a password meets a few basic conditions.
- Use "and", "or", and "not" in a small program.
Try solving them without looking at the examples first.
More Python if-else examples
If you want more practice, I have a separate collection of Python conditional-statement examples and questions covering "if", "elif", "else", nested conditions, logical operators, conditional expressions, and practical problems:
Python If-Else Examples and Interview Questions:
https://www.sankalandtech.com/Tutorials/Python/interview-questions/python-control-structures-if-else.html
The examples can be useful whether you are learning Python for the first time, working with data, writing automation scripts, or preparing for a Python interview.
Top comments (0)