
Python if Statement Examples
The if
statement is one of the most fundamental building blocks in Python—and programming in general. It allows your code to make decisions, execute certain parts conditionally, and bring logic to life. In this article, we’ll explore how if
statements work in Python, with plenty of examples to help you understand and apply them confidently.
Basic if Statement
Let’s start with the simplest form: the if statement by itself. It checks a condition, and if that condition evaluates to True
, the code inside the block runs.
age = 20
if age >= 18:
print("You are an adult.")
In this example, since age
is 20 (which is indeed greater than or equal to 18), the message will be printed.
You can use any expression that returns a boolean (True
or False
) inside the condition. Common operators include ==
, !=
, <
, >
, <=
, and >=
.
name = "Alice"
if name == "Alice":
print("Hello, Alice!")
if-else Statement
What if you want to do one thing when a condition is true, and something else when it’s false? That’s where if-else comes in.
temperature = 30
if temperature > 25:
print("It's a warm day.")
else:
print("It's not so warm.")
Here, if the temperature is above 25, the first message prints. Otherwise, the second one does.
You can think of if-else
as a fork in the road—your program takes one path or the other, but not both.
if-elif-else Statement
Sometimes you have more than two conditions to check. For that, use if-elif-else. The elif
is short for "else if".
score = 85
if score >= 90:
grade = 'A'
elif score >= 80:
grade = 'B'
elif score >= 70:
grade = 'C'
else:
grade = 'D'
print(f"Your grade is {grade}.")
The conditions are checked from top to bottom. The first condition that is True
runs, and the rest are skipped.
Note: You can have as many elif
blocks as you need, but only one else
(at the end), and it’s optional.
Nested if Statements
You can also place an if
statement inside another if
(or elif
, or else
) block. This is called nesting.
num = 10
if num > 0:
print("Positive number.")
if num % 2 == 0:
print("And it's even.")
else:
print("And it's odd.")
else:
print("Not a positive number.")
Be cautious with nesting—it can make code harder to read if overused.
Conditional Expressions with Logical Operators
You can combine multiple conditions using logical operators: and
, or
, and not
.
age = 25
has_license = True
if age >= 18 and has_license:
print("You can drive.")
else:
print("You cannot drive.")
Here, both conditions must be true for the first block to run.
You can also use or
(if at least one condition is true) and not
(to invert a condition).
is_weekend = True
is_holiday = False
if is_weekend or is_holiday:
print("No work today!")
Below is a summary of common comparison and logical operators you’ll use in if
conditions.
Operator | Description | Example |
---|---|---|
== |
Equal to | x == y |
!= |
Not equal to | x != y |
> |
Greater than | x > y |
< |
Less than | x < y |
>= |
Greater than or equal to | x >= y |
<= |
Less than or equal to | x <= y |
and |
Both conditions true | x > 0 and y < 10 |
or |
At least one condition true | x == 5 or y == 5 |
not |
Negates the condition | not(x < 5) |
Truthiness in Conditions
In Python, you don’t always need a boolean in an if
condition. Other values have inherent "truthiness":
- Numbers: 0 is
False
, any non-zero isTrue
. - Strings: Empty string
""
isFalse
, non-empty isTrue
. - Lists, tuples, dictionaries: Empty ones are
False
, non-empty areTrue
. None
is alwaysFalse
.
name = ""
if name:
print(f"Hello, {name}!")
else:
print("Name is empty.")
This prints "Name is empty." because an empty string is falsy.
Common Use Cases
if
statements are used everywhere. Here are a few practical examples:
- Validating user input
user_input = input("Enter yes or no: ")
if user_input.lower() == "yes":
print("You agreed.")
elif user_input.lower() == "no":
print("You disagreed.")
else:
print("Invalid input.")
- Checking file extensions
filename = "report.pdf"
if filename.endswith(".pdf"):
print("PDF file detected.")
- Access control
is_admin = True
is_logged_in = True
if is_logged_in and is_admin:
print("Access granted to admin panel.")
One-Liner if Statements
For very simple conditions, you can write an if
statement in one line.
x = 5
message = "Even" if x % 2 == 0 else "Odd"
print(message)
This is called a conditional expression (or ternary operator). Use it sparingly—it can harm readability if overused.
Pitfalls and Best Practices
While if
statements are straightforward, a few things can trip you up:
- Don’t forget the colon (
:
) at the end of the condition. - Mind the indentation. Python uses indentation to define code blocks.
- Avoid unnecessarily deep nesting. If you find yourself nesting too many
if
statements, consider refactoring.
A useful tip: Use meaningful variable names in your conditions to make the logic clear.
# Instead of this:
if x > 5 and y < 10 and z == 0:
...
# Use descriptive names:
is_within_range = x > 5 and y < 10
is_valid = z == 0
if is_within_range and is_valid:
...
Practice Examples
Let’s reinforce what we’ve learned with a few more examples.
Example 1: Check if a number is positive, negative, or zero.
num = -3
if num > 0:
print("Positive")
elif num < 0:
print("Negative")
else:
print("Zero")
Example 2: Check if a year is a leap year.
year = 2024
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print("Leap year")
else:
print("Not a leap year")
Example 3: Simple authentication.
username = "admin"
password = "1234"
if username == "admin" and password == "1234":
print("Login successful.")
else:
print("Invalid credentials.")
To write effective conditions, keep these points in mind:
- Keep conditions simple and readable.
- Use parentheses to group expressions when using multiple operators.
- Test edge cases to ensure your logic handles all scenarios.
Remember, practice is key. Try writing your own if
statements with different conditions. The more you use them, the more intuitive they will become.
Whether you're building a simple script or a complex application, mastering if
statements is a crucial step in your Python journey. They empower you to write dynamic, responsive code that can handle real-world decision making.