Python if Statements
Learn how Python makes decisions using conditions,
if, elif, and
else statements.
What You Will Learn
- Understand how decision-making works in Python.
- Write and understand
ifstatements. - Use comparison operators to create conditions.
- Use
elseandelif. - Combine conditions using logical operators.
- Build nested conditional logic.
- Use conditions with strings, numbers, input, membership, and identity.
- Build practical decision-making programs.
What Is Decision Making?
Programs often need to make decisions.
For example:
- If a student scores 50 or more, they pass.
- If a customer's cart total is high enough, they receive free delivery.
- If a user's password is correct, access is granted.
- If the temperature is high, the program can display a warning.
Python uses conditional statements to control which parts of a program should execute.
Python asks: "Is this condition true?" If the answer
is True, the associated code runs.
The if Statement
The simplest conditional statement in Python is
if.
if condition:
# code to execute
Example:
age = 20
if age >= 18:
print("You are an adult.")
You are an adult.
Since age >= 18 is true, Python executes the
indented statement.
Understanding Conditions
A condition is an expression that produces either
True or False.
age = 25
print(age >= 18)
print(age < 18)
True False
These Boolean results can be used directly inside conditional statements.
age = 25
if age >= 18:
print("Eligible")
Indentation & Code Blocks
Python uses indentation to identify the code that belongs
to an if statement.
age = 20
if age >= 18:
print("Adult")
print("Eligible to vote")
Both print() statements belong to the
if block because they are indented.
Incorrect indentation can cause an
IndentationError or change the logic
of your program.
The standard Python convention is four spaces per indentation level.
if with Comparison Operators
Comparison operators are frequently used to create conditions.
score = 85
if score >= 50:
print("Passed")
Common comparison operators include:
==— equal to!=— not equal to>— greater than<— less than>=— greater than or equal to<=— less than or equal to
temperature = 35
if temperature > 30:
print("It is hot today.")
It is hot today.
if with Boolean Values
Boolean variables can be used directly as conditions.
is_logged_in = True
if is_logged_in:
print("Welcome back!")
Welcome back!
You usually do not need to write
if is_logged_in == True:.
The simpler form is clearer.
# Preferred
if is_logged_in:
print("Welcome")
# Less concise
if is_logged_in == True:
print("Welcome")
The else Statement
An if statement handles the true condition.
The else block handles the alternative.
age = 16
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
You are a minor.
Only one of these two branches executes.
The elif Statement
Use elif, short for "else if", when you have
multiple possible conditions.
marks = 78
if marks >= 90:
print("Grade A+")
elif marks >= 80:
print("Grade A")
elif marks >= 70:
print("Grade B")
else:
print("Needs improvement")
Grade B
Python checks conditions from top to bottom. Once one condition is true, its block runs and the remaining branches are skipped.
Multiple Conditions
You can use several elif branches when a
program has multiple possible outcomes.
age = 35
if age < 13:
category = "Child"
elif age < 20:
category = "Teenager"
elif age < 60:
category = "Adult"
else:
category = "Senior"
print(category)
Adult
Python evaluates the conditions from top to bottom and executes the first matching branch.
Logical Operators with if
You can combine conditions using
and, or, and not.
Using and
age = 25
has_id = True
if age >= 18 and has_id:
print("Access granted")
Using or
is_admin = False
is_manager = True
if is_admin or is_manager:
print("You can access this section.")
Using not
is_blocked = False
if not is_blocked:
print("Account is active.")
Nested if Statements
An if statement can exist inside another
if statement.
age = 25
has_ticket = True
if age >= 18:
if has_ticket:
print("You may enter.")
else:
print("You need a ticket.")
else:
print("You must be an adult.")
You may enter.
Nested conditions are useful when the second decision only matters after the first condition has been satisfied.
Deeply nested conditions can become difficult to read. Later in the course, you will learn techniques for writing cleaner control flow.
Membership Conditions
The in and not in operators can
be used directly inside conditions.
available_colors = ["red", "blue", "green"]
color = "blue"
if color in available_colors:
print("Color is available.")
else:
print("Color is not available.")
Color is available.
This technique is useful for checking membership in lists, sets, strings, and dictionary keys.
Identity Conditions
Python's is and is not operators
check object identity.
They are particularly useful when checking for
None.
value = None
if value is None:
print("No value was provided.")
No value was provided.
Use == to compare values and
is when you specifically need to
test object identity, commonly with
None.
Conditions with Strings
Strings can be compared inside conditional statements.
username = "admin"
if username == "admin":
print("Welcome, administrator.")
else:
print("Welcome, user.")
Welcome, administrator.
String comparisons are case-sensitive.
password = "Python123"
if password == "python123":
print("Correct password.")
else:
print("Incorrect password.")
Incorrect password.
Conditions with Numbers
Numeric conditions are common in calculations, applications, and business logic.
cart_total = 6500
if cart_total >= 5000:
print("You qualify for free delivery.")
else:
print("Delivery charges apply.")
You qualify for free delivery.
Another Example
stock = 4
if stock == 0:
print("Out of stock.")
elif stock < 5:
print("Low stock.")
else:
print("In stock.")
Low stock.
if Statements with User Input
Conditional logic becomes much more useful when combined with user input.
age = int(input("Enter your age: "))
if age >= 18:
print("You are eligible.")
else:
print("You are not eligible.")
Remember that input() returns a string, so
the value is converted to an integer using
int().
Login Example
username = input("Username: ")
password = input("Password: ")
if username == "admin" and password == "1234":
print("Login successful.")
else:
print("Invalid credentials.")
Real applications should never store passwords directly in source code. This example is only demonstrating conditional logic.
Real-World Examples
Student Result System
marks = 82
if marks >= 90:
grade = "A+"
elif marks >= 80:
grade = "A"
elif marks >= 70:
grade = "B"
elif marks >= 60:
grade = "C"
elif marks >= 50:
grade = "D"
else:
grade = "F"
print(f"Grade: {grade}")
Grade: A
Discount Calculator
total = 12000
if total >= 10000:
discount = 20
elif total >= 5000:
discount = 10
else:
discount = 0
print(f"Discount: {discount}%")
Discount: 20%
Weather Alert
temperature = 42
if temperature >= 40:
print("Extreme heat warning.")
elif temperature >= 30:
print("Hot weather.")
elif temperature >= 20:
print("Pleasant weather.")
else:
print("Cool weather.")
Extreme heat warning.
Common Mistakes
Mistake 1 — Using = Instead of ==
# Incorrect
if age = 18:
print("Adult")
The single = operator assigns a value.
Comparison requires ==.
# Correct
if age == 18:
print("Exactly 18")
Mistake 2 — Forgetting the Colon
# Incorrect
if age >= 18
print("Adult")
# Correct
if age >= 18:
print("Adult")
Mistake 3 — Incorrect Indentation
# Incorrect
if age >= 18:
print("Adult")
# Correct
if age >= 18:
print("Adult")
Mistake 4 — Wrong Condition Order
marks = 95
if marks >= 50:
print("Pass")
elif marks >= 90:
print("Excellent")
The second condition is never reached for 95 because the first condition is already true.
More specific conditions should generally come before broader conditions.
marks = 95
if marks >= 90:
print("Excellent")
elif marks >= 50:
print("Pass")
Practice Exercises
Exercise 1 — Age Checker
Ask the user for their age and print whether they are an adult or a minor.
Exercise 2 — Positive or Negative
Ask the user for a number and determine whether it is positive, negative, or zero.
Exercise 3 — Even or Odd
Ask the user for a number and determine whether it is even or odd.
Exercise 4 — Grade Calculator
Ask for marks and display a grade using
if, elif, and
else.
Exercise 5 — Largest Number
Ask for two numbers and display the larger number.
Exercise 6 — Login Checker
Ask for a username and password and display whether the login is successful.
Exercise 7 — Shopping Discount
Give a customer a discount based on their purchase amount.
Exercise 8 — Leap Year Logic
Write a program that determines whether a year is a leap year.
Mini Challenge — Student Result Analyzer
Build a complete student result program using conditional statements.
The program should:
- Ask the user for their name.
- Ask for marks in three subjects.
- Calculate the total and average.
- Determine whether the student passed or failed.
- Assign a grade based on the average.
- Display a professional result summary.
name = input("Enter student name: ")
math = float(input("Math marks: "))
english = float(input("English marks: "))
computer = float(input("Computer marks: "))
total = math + english + computer
average = total / 3
if average >= 90:
grade = "A+"
elif average >= 80:
grade = "A"
elif average >= 70:
grade = "B"
elif average >= 60:
grade = "C"
elif average >= 50:
grade = "D"
else:
grade = "F"
if average >= 50:
result = "Passed"
else:
result = "Failed"
print("\n--- Student Result ---")
print(f"Name: {name}")
print(f"Total: {total:.2f}")
print(f"Average: {average:.2f}")
print(f"Grade: {grade}")
print(f"Result: {result}")
--- Student Result --- Name: Ali Total: 246.00 Average: 82.00 Grade: A Result: Passed
Improve the program by checking whether the student's marks are valid. Reject marks below 0 or above 100 before calculating the result.
Quick Knowledge Check
Test your understanding of Python conditional statements.
1. Which keyword starts a conditional statement?
2. What does a condition normally produce?
3. Which keyword handles the alternative branch?
4. Which keyword is used to test another condition?
5. Which operator checks equality?
6. What is required after an if condition?
7. Which operator checks whether an item exists in a collection?
8. Which statement is normally used to check for
None?
Lesson Summary
Conditional statements allow Python programs to make decisions and choose which code should execute.
Conditional statements are the foundation of
program decision-making. Once you understand
if, elif, and
else, your programs can respond
intelligently to different situations.
Ready to Continue?
You have learned how Python makes decisions using conditions and conditional statements.
You've reached the end of this lesson.
Review the examples, open the Practice Lab, and mark this lesson complete when you're ready.