PyLearn Learn Python. Build Anything.
Home Course Roadmap
Home / Python Foundations / Lesson 24
Lesson 24 · Control Flow

Python if Statements

Learn how Python makes decisions using conditions, if, elif, and else statements.

45–55 minutes Beginner Control Flow
0%

What You Will Learn

  • Understand how decision-making works in Python.
  • Write and understand if statements.
  • Use comparison operators to create conditions.
  • Use else and elif.
  • Combine conditions using logical operators.
  • Build nested conditional logic.
  • Use conditions with strings, numbers, input, membership, and identity.
  • Build practical decision-making programs.
01

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.

Think of an if statement as a question.

Python asks: "Is this condition true?" If the answer is True, the associated code runs.

02

The if Statement

The simplest conditional statement in Python is if.

Syntax
if condition:
    # code to execute

Example:

age = 20

if age >= 18:
    print("You are an adult.")
Output
You are an adult.

Since age >= 18 is true, Python executes the indented statement.

03

Understanding Conditions

A condition is an expression that produces either True or False.

age = 25

print(age >= 18)
print(age < 18)
Output
True
False

These Boolean results can be used directly inside conditional statements.

age = 25

if age >= 18:
    print("Eligible")
04

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.

Indentation is not optional.

Incorrect indentation can cause an IndentationError or change the logic of your program.

The standard Python convention is four spaces per indentation level.

05

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.")
Output
It is hot today.
06

if with Boolean Values

Boolean variables can be used directly as conditions.

is_logged_in = True

if is_logged_in:
    print("Welcome back!")
Output
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")
07

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.")
Output
You are a minor.

Only one of these two branches executes.

08

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")
Output
Grade B

Python checks conditions from top to bottom. Once one condition is true, its block runs and the remaining branches are skipped.

09

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)
Output
Adult
Execution flow

Python evaluates the conditions from top to bottom and executes the first matching branch.

10

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.")
11

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.")
Output
You may enter.

Nested conditions are useful when the second decision only matters after the first condition has been satisfied.

Avoid unnecessary nesting.

Deeply nested conditions can become difficult to read. Later in the course, you will learn techniques for writing cleaner control flow.

12

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.")
Output
Color is available.

This technique is useful for checking membership in lists, sets, strings, and dictionary keys.

13

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.")
Output
No value was provided.
Remember

Use == to compare values and is when you specifically need to test object identity, commonly with None.

14

Conditions with Strings

Strings can be compared inside conditional statements.

username = "admin"

if username == "admin":
    print("Welcome, administrator.")
else:
    print("Welcome, user.")
Output
Welcome, administrator.

String comparisons are case-sensitive.

password = "Python123"

if password == "python123":
    print("Correct password.")
else:
    print("Incorrect password.")
Output
Incorrect password.
15

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.")
Output
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.")
Output
Low stock.
16

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.")
Learning example only

Real applications should never store passwords directly in source code. This example is only demonstrating conditional logic.

17

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}")
Output
Grade: A

Discount Calculator

total = 12000

if total >= 10000:
    discount = 20
elif total >= 5000:
    discount = 10
else:
    discount = 0

print(f"Discount: {discount}%")
Output
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.")
Output
Extreme heat warning.
18

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")
19

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.

20

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.
Possible Solution
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}")
Possible Output
--- Student Result ---
Name: Ali
Total: 246.00
Average: 82.00
Grade: A
Result: Passed
Challenge Upgrade

Improve the program by checking whether the student's marks are valid. Reject marks below 0 or above 100 before calculating the result.

21

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?

22

Lesson Summary

Conditional statements allow Python programs to make decisions and choose which code should execute.

if Runs code when a condition is true.
else Handles the alternative.
elif Tests additional conditions.
and / or / not Combine logical conditions.
Nested if Places decisions inside decisions.
Input Makes programs interactive.
Key takeaway

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.

Open Practice Lab