Python Programming

Control Flow: Conditional Statements

5 sections AI-powered notes
GET THE FULL EXPERIENCE

This is the chapter notes. Students get the interactive version.

  • Ask Aarav Sir anything — instant voice + chat doubts
  • Interactive lessons with audio narration + visual diagrams
  • Study Lab — paste any photo, PDF, or YouTube link to get it explained

What Are Conditions?

What Are Conditions?

Every day, you make countless decisions based on conditions. If it's raining, you take an umbrella. If you're hungry, you eat. If the traffic light is red, you stop. These simple if-then patterns form the foundation of how we navigate the world—and they're exactly how programs make decisions too.

In Python, conditions allow your code to be intelligent and responsive. Instead of executing the same instructions every single time, your programs can examine the current situation, evaluate what's true, and choose different paths accordingly. This is called conditional logic, and it's one of the most powerful concepts in programming.

Programs That Think

Imagine a simple login system. When someone enters their password, the program needs to decide: is this password correct or not? Based on that answer, it either grants access or denies it. The program isn't just blindly following a single set of instructions—it's evaluating a condition and responding appropriately.

password = "secret123"
user_input = input("Enter password: ")

if user_input == password:
    print("Access granted!")
else:
    print("Access denied!")

This tiny program demonstrates conditional thinking. The code looks at two values, compares them, and makes a decision. But to understand how this works, we need to explore what makes a condition "true" or "false."

{{VISUAL: diagram: flowchart showing a decision point where user input is compared to stored password, branching to either "Access granted" or "Access denied"}}

Boolean Values: The Language of True and False

At the heart of all conditions are Boolean values—named after mathematician George Boole. In Python, there are only two Boolean values: True and False (notice they're capitalized). These aren't strings or numbers; they're a special data type that represents the answer to yes/no questions.

When you write a condition, Python evaluates it and reduces it to one of these two values:

is_raining = True
is_sunny = False

print(is_raining)  # Output: True
print(is_sunny)    # Output: False

But most conditions aren't this straightforward. Usually, you're asking Python to compare things and determine whether the comparison is true or false.

Comparison Operators: Asking Questions About Data

Python provides six comparison operators that let you ask questions about values. Each operator compares two values and returns either True or False:

OperatorMeaningExampleResult
==Equal to5 == 5True
!=Not equal to5 != 3True
>Greater than7 > 4True
<Less than3 < 8True
>=Greater than or equal to5 >= 5True
<=Less than or equal to4 <= 3False

Let's see these in action:

age = 18
temperature = 72
score = 95

print(age >= 18)           # True (18 is equal to 18)
print(temperature > 100)   # False (72 is not greater than 100)
print(score == 100)        # False (95 does not equal 100)
print(score != 0)          # True (95 is not equal to 0)

Notice something crucial: we use == (double equals) for comparison, not = (single equals). This is because = is the assignment operator—it stores a value in a variable. The == operator asks "are these equal?" without changing anything.

x = 10      # Assignment: store 10 in x
x == 10     # Comparison: is x equal to 10? (Returns True)

This distinction trips up many beginners, so keep it in mind!

{{VISUAL: diagram: side-by-side comparison showing "x = 10" labeled as "Assignment (stores value)" versus "x == 10" labeled as "Comparison (tests equality)"}}

Conditions with Different Data Types

Comparison operators work with various data types, not just numbers:

Strings can be compared alphabetically:

print("apple" < "banana")    # True (a comes before b)
print("hello" == "Hello")    # False (case-sensitive!)
print("Python" != "python")  # True (different cases)

Numbers can be integers or floats:

print(3.14 > 3)      # True
print(10.0 == 10)    # True (Python treats these as equal)

Mixed comparisons between incompatible types will cause errors:

print(5 > "3")  # TypeError: '>' not supported between int and str

Building Intuition: Conditions Are Questions

The best way to think about conditions is as questions your program asks. Every condition you write should translate into a clear yes/no question:

  • temperature > 75 → "Is the temperature greater than 75?"
  • username == "admin" → "Is the username equal to 'admin'?"
  • balance >= 100 → "Is the balance at least 100?"

When Python evaluates these questions, it gets back True or False. Your program then uses that answer to decide what to do next. In the upcoming pages, you'll learn exactly how to use if, elif, and else statements to build these decision-making pathways into your code.

Practice Check

Before moving forward, try evaluating these conditions in your head:

x = 15
y = 20

x < y        # ?
x == 15      # ?
y != 20      # ?
x >= 20      # ?

Understanding conditions is like learning to ask the right questions. Once you master that, you can teach your programs to think critically and respond intelligently to any situation they encounter.


Basic if Logic

Basic if Logic

At the heart of decision-making in Python lies the if statement. Think of it as a gatekeeper that checks whether something is true before allowing code to run. Just like you might check if it's raining before deciding to take an umbrella, your program can check conditions before executing certain code blocks.

The Anatomy of an if Statement

An if statement in Python follows a simple structure:

if condition:
    # Code to execute if condition is True
    print("The condition was met!")

Let's break down each component:

  • if keyword: Signals the start of a conditional check
  • condition: An expression that evaluates to either True or False
  • colon (:): Marks the end of the condition line (required!)
  • indented block: The code that runs only when the condition is True

Critical Rule: Python uses indentation (typically 4 spaces) to define code blocks. Everything indented beneath the if statement belongs to that conditional block.

{{VISUAL: diagram: anatomy of an if statement showing the keyword, condition, colon, and indented code block with labels}}

Your First if Statement

Let's start with a simple example:

temperature = 30

if temperature > 25:
    print("It's a hot day!")
    print("Remember to stay hydrated.")

Output:

It's a hot day!
Remember to stay hydrated.

Here's what happens step-by-step:

  1. Python evaluates the condition: temperature > 25
  2. Since 30 is greater than 25, the condition is True
  3. Python executes all indented lines below the if statement
  4. Both print statements run

Now, what if we change the temperature?

temperature = 20

if temperature > 25:
    print("It's a hot day!")
    print("Remember to stay hydrated.")

print("This line always runs!")

Output:

This line always runs!

Notice that the two indented print statements didn't run because the condition was False (20 is not greater than 25). However, the final print statement—which is not indented—runs regardless because it's not part of the if block.

Comparison Operators: The Building Blocks

To write meaningful conditions, you need comparison operators. These operators compare values and return either True or False:

OperatorMeaningExampleResult
==Equal to5 == 5True
!=Not equal to5 != 3True
>Greater than7 > 4True
<Less than3 < 8True
>=Greater than or equal5 >= 5True
<=Less than or equal4 <= 3False

Important: Notice the double equals (==) for comparison versus single equals (=) for assignment. This is a common source of bugs!

# Assignment (storing a value)
age = 18

# Comparison (checking a value)
if age == 18:
    print("You just became an adult!")

Practical Examples

Example 1: Access Control

user_age = 17

if user_age >= 18:
    print("Access granted. Welcome!")
    print("You may proceed to the content.")

Since user_age is 17, which is less than 18, nothing prints. The condition is False, so the code block is skipped entirely.

Example 2: Positive Number Checker

number = 42

if number > 0:
    print(f"{number} is a positive number")
    result = number * 2
    print(f"Double that number is {result}")

Output:

42 is a positive number
Double that number is 84

{{VISUAL: diagram: flowchart showing if statement decision path with True branch executing code block and False branch skipping it}}

Example 3: String Comparison

Conditions work with strings too:

password = "python123"

if password == "python123":
    print("Password correct!")
    print("Login successful")

Output:

Password correct!
Login successful

Understanding Boolean Values

Every condition ultimately evaluates to a boolean value—either True or False. You can even check boolean values directly:

is_raining = True

if is_raining:
    print("Take an umbrella")

When the condition itself is a boolean variable, you don't need comparison operators. Python simply checks if the value is True.

Common Beginner Mistakes

1. Forgetting the colon

# Wrong ❌
if temperature > 25
    print("Hot!")

# Correct ✓
if temperature > 25:
    print("Hot!")

2. Incorrect indentation

# Wrong ❌
if temperature > 25:
print("Hot!")  # Not indented!

# Correct ✓
if temperature > 25:
    print("Hot!")  # Properly indented

3. Using = instead of ==

# Wrong ❌
if age = 18:  # This is assignment, not comparison!

# Correct ✓
if age == 18:
    print("Just turned 18!")

Building Your Intuition

Think of an if statement as a question your program asks itself: "Is this condition true?" If the answer is yes, the program takes action. If the answer is no, it simply moves on to the next line of code outside the indented block.

This simple mechanism is incredibly powerful. With just the basic if statement, you can already create programs that respond differently based on user input, sensor data, time of day, or any other condition you can imagine. In the next section, we'll expand on this foundation by learning how to handle multiple possible outcomes with elif and else.


if and else

if and else: Handling Both Paths

In real life, decisions rarely have just one outcome. When you check the weather before leaving home, you don't only plan for rain—you also decide what to do if it's not raining. Programming works the same way. The else statement pairs with if to handle the alternative path when your condition is false.

The Basic if-else Pattern

While a standalone if statement lets you execute code when a condition is true, adding else gives you complete control over both possibilities:

temperature = 15

if temperature > 20:
    print("It's warm outside!")
else:
    print("It's cool outside!")

Output: It's cool outside!

Here's what happens: Python evaluates the condition temperature > 20. Since 15 is not greater than 20, the condition is false. Python skips the first block entirely and executes the code inside the else block instead.

{{VISUAL: diagram: flowchart showing if-else decision split with condition diamond branching to two rectangular code blocks}}

Why else Matters

Without else, you'd need two separate if statements to cover both scenarios:

# Without else (redundant and error-prone)
age = 16

if age >= 18:
    print("You can vote")

if age < 18:
    print("You cannot vote yet")

This works, but it's inefficient. Python checks both conditions even though only one can be true. More importantly, if you later change the first condition, you must remember to update the second one too—a common source of bugs.

The if-else structure is cleaner and more logical:

# With else (clear and efficient)
age = 16

if age >= 18:
    print("You can vote")
else:
    print("You cannot vote yet")

Python evaluates the condition once. If true, run the first block. If false, run the second block. Simple, readable, and foolproof.

Indentation: The Rules Still Apply

Just like with if, everything inside an else block must be indented. Python uses this indentation to know which lines belong to the else:

score = 45

if score >= 50:
    print("Pass!")
    print("Well done!")
else:
    print("Fail")
    print("Keep studying!")

Both print statements under else will execute when the score is below 50. The indentation creates a clear visual boundary showing which code belongs to which branch.

Practical Examples

Example 1: Password Checker

password = input("Enter password: ")

if password == "secret123":
    print("Access granted")
    print("Welcome back!")
else:
    print("Access denied")
    print("Invalid password")

This simple security check grants or denies access based on password correctness.

Example 2: Even or Odd

Stuck on something here?
Aarav Sir explains any part — voice or chat — 24/7.
number = int(input("Enter a number: "))

if number % 2 == 0:
    print(f"{number} is even")
else:
    print(f"{number} is odd")

The modulo operator % returns the remainder of division. If a number divided by 2 has no remainder (remainder is 0), it's even. Otherwise, it's odd.

{{VISUAL: diagram: side-by-side comparison showing if-only structure versus if-else structure with arrows indicating execution flow}}

Example 3: Temperature Advisor

temp = 28

if temp > 25:
    print("Turn on the air conditioning")
    advice = "Stay hydrated"
else:
    print("Temperature is comfortable")
    advice = "Enjoy your day"

print(advice)  # This runs regardless of the condition

Notice that the final print(advice) is not indented under either block—it runs after the entire if-else structure completes, regardless of which branch executed.

Common Mistakes to Avoid

Missing the colon

# WRONG
if x > 10:
    print("Big")
else       # Missing colon!
    print("Small")

Forgetting indentation

# WRONG
if x > 10:
    print("Big")
else:
print("Small")  # Not indented!

Using else without if

# WRONG
else:
    print("This doesn't work")

The else keyword is not standalone—it must always follow an if statement.

Key Takeaways

  • else provides the alternative path when your if condition is false
  • Only one block executes—never both. Python chooses one path based on the condition
  • Don't forget the colon after else:
  • Indent everything inside the else block
  • Use if-else instead of two separate if statements when you have mutually exclusive conditions

The if-else pattern is fundamental to decision-making in Python. In the next section, you'll learn how to handle more than two options using elif, opening up even more powerful branching logic.


Chain Many Conditions

Chain Many Conditions

You've learned how to make a binary choice with if and else—either one path or another. But real-world programs often need to choose between many different possibilities. What if you're building a grading system that assigns A, B, C, D, or F? Or a weather app that responds differently to sunny, rainy, snowy, or cloudy conditions?

This is where elif (short for "else if") comes in. It allows you to chain multiple conditions together, checking them one by one until Python finds a match.

The Problem with Multiple if Statements

Before we explore elif, let's see why using multiple separate if statements isn't ideal:

score = 85

if score >= 90:
    print("Grade: A")

if score >= 80:
    print("Grade: B")

if score >= 70:
    print("Grade: C")

Output:

Grade: B
Grade: C

Wait—that's wrong! The student scored 85, so they should get a B, not both B and C. The problem is that Python checks every if statement independently. Since 85 is greater than both 80 and 70, both conditions are true, and both print statements execute.

This is inefficient and produces incorrect results. We need a way to say: "Check this condition, and if it's not true, check the next one, and if that's not true, check the next one..." This is exactly what elif does.

{{VISUAL: diagram: flowchart showing multiple separate if statements all being checked versus a single if-elif chain stopping at the first match}}

Introducing elif: The Sequential Checker

The elif statement creates a chain of conditions that Python checks in order from top to bottom. As soon as one condition is true, Python executes that block and skips all the remaining conditions.

Here's the basic structure:

if condition1:
    # Runs if condition1 is True
elif condition2:
    # Runs if condition1 is False AND condition2 is True
elif condition3:
    # Runs if condition1 and condition2 are False AND condition3 is True
else:
    # Runs if all conditions above are False

Let's fix our grading system:

score = 85

if score >= 90:
    print("Grade: A")
elif score >= 80:
    print("Grade: B")
elif score >= 70:
    print("Grade: C")
elif score >= 60:
    print("Grade: D")
else:
    print("Grade: F")

Output:

Grade: B

Perfect! Here's what happens step by step:

  1. Python checks: Is score >= 90? No, 85 < 90, so skip this block
  2. Python checks: Is score >= 80? Yes! Execute this block and print "Grade: B"
  3. Python stops checking—it never even looks at the remaining elif or else blocks

Order Matters: Start with the Most Specific

The order of your conditions is crucial with elif. Python stops at the first true condition, so you should generally arrange them from most specific to most general or from highest to lowest (or vice versa, depending on your logic).

Here's what happens if you reverse the order:

score = 85

if score >= 60:
    print("Grade: D")
elif score >= 70:
    print("Grade: C")
elif score >= 80:
    print("Grade: B")
elif score >= 90:
    print("Grade: A")

Output:

Grade: D

Oops! Since 85 is greater than 60, the first condition is true, and Python never checks the others. Always think carefully about the sequence of your conditions.

{{VISUAL: diagram: side-by-side comparison showing correct descending order versus incorrect ascending order in if-elif chains with arrows indicating where execution stops}}

Practical Example: Temperature Advisor

Let's build something more interactive—a program that gives clothing advice based on temperature:

temperature = int(input("Enter the temperature in °F: "))

if temperature >= 85:
    print("It's hot! Wear shorts and a t-shirt.")
elif temperature >= 70:
    print("Nice weather! A light outfit works well.")
elif temperature >= 50:
    print("Getting cool. Bring a jacket.")
elif temperature >= 32:
    print("It's cold! Wear a coat and layers.")
else:
    print("Freezing! Bundle up with winter gear.")

Try running this with different inputs:

  • Input: 92 → "It's hot! Wear shorts and a t-shirt."
  • Input: 65 → "Nice weather! A light outfit works well."
  • Input: 28 → "Freezing! Bundle up with winter gear."

Combining elif with Complex Conditions

You can make your elif chains even more powerful by using logical operators (and, or, not):

age = 16
has_license = True

if age >= 18:
    print("You can drive without restrictions.")
elif age >= 16 and has_license:
    print("You can drive with restrictions.")
elif age >= 16 and not has_license:
    print("You're old enough but need a license first.")
else:
    print("You're too young to drive.")

This checks multiple factors together, making your decision-making logic sophisticated and realistic.

Key Takeaways

  • Use elif to check multiple conditions sequentially
  • Python stops at the first true condition and skips the rest
  • Order matters—arrange conditions from most to least specific
  • You can have as many elif statements as needed
  • The final else is optional but useful as a "catch-all" for everything else

In the next section, you'll learn how to nest conditional statements inside one another to handle even more complex decision-making scenarios!


Conditional Challenges

Conditional Challenges

Welcome to the final page of this chapter! Now that you've learned the mechanics of if, elif, and else statements, it's time to put your knowledge into practice. These challenges will help solidify your understanding and build your confidence in writing decision-making code.

Challenge Structure

Each exercise below increases in complexity. Don't rush—read each challenge carefully, plan your approach, and test your code thoroughly. Remember: making mistakes is part of learning. If your code doesn't work the first time, analyze the error message and debug systematically.


Challenge 1: Temperature Advisor

Difficulty: ⭐ Beginner

Write a program that takes a temperature in Celsius and provides clothing advice:

  • If temperature > 25: "Wear shorts and a t-shirt"
  • If temperature is between 15 and 25 (inclusive): "Wear a light jacket"
  • If temperature < 15: "Wear a warm coat"

Starter Code:

temperature = float(input("Enter temperature in Celsius: "))

# Your code here

Expected Output Examples:

Enter temperature in Celsius: 28
Wear shorts and a t-shirt

Enter temperature in Celsius: 18
Wear a light jacket

Enter temperature in Celsius: 10
Wear a warm coat

Learning Goal: Practice using comparison operators and elif for range checking.


Challenge 2: Grade Calculator with Validation

Difficulty: ⭐⭐ Intermediate

Create a grade calculator that converts numerical scores to letter grades. Add input validation to handle invalid scores.

Requirements:

  • A+ (90-100), A (80-89), B (70-79), C (60-69), D (50-59), F (below 50)
  • Reject scores below 0 or above 100 with an error message

{{VISUAL: diagram: flowchart showing grade calculation logic with validation check at the start, then decision tree for different grade ranges}}

score = float(input("Enter your score (0-100): "))

# Your code here

Test Cases:

  • Score: 95 → "A+"
  • Score: 72 → "B"
  • Score: 105 → "Invalid score. Please enter a value between 0 and 100."
  • Score: -5 → "Invalid score. Please enter a value between 0 and 100."

Hint: Check for validity first before checking grade ranges.


Challenge 3: Login System

Difficulty: ⭐⭐ Intermediate

Build a simple login system that checks both username and password. Use nested conditionals to validate credentials.

Requirements:

  • Correct username: "admin"
  • Correct password: "python123"
  • Show different messages for wrong username vs. wrong password
  • Show success message only when both are correct
username = input("Username: ")
password = input("Password: ")

# Your code here

Expected Behavior:

Username: admin
Password: python123
Login successful! Welcome, admin.

Username: user
Password: python123
Invalid username.

Username: admin
Password: wrong
Invalid password.

Learning Goal: Master nested conditionals where one condition is checked inside another.


Challenge 4: Ticket Pricing System

Difficulty: ⭐⭐⭐ Advanced

Create a cinema ticket pricing system with multiple factors:

Base Prices:

  • Child (age < 12): $8
  • Adult (age 12-64): $15
  • Senior (age 65+): $10

Discounts:

  • Students get 20% off (except children who already have the lowest price)
  • Weekend shows cost $3 extra for everyone
age = int(input("Enter age: "))
is_student = input("Are you a student? (yes/no): ").lower() == "yes"
is_weekend = input("Is this a weekend show? (yes/no): ").lower() == "yes"

# Your code here
# Calculate final price and display it

{{VISUAL: diagram: table showing ticket pricing matrix with age categories in rows and student/weekend status creating different price outcomes}}

Sample Calculations:

  • Child, age 10, weekend → $8 + $3 = $11
  • Adult, age 25, student, weekday → $15 × 0.80 = $12
  • Senior, age 70, not student, weekend → $10 + $3 = $13

Bonus Challenge: Display a breakdown showing base price, discounts, and additional charges.


Challenge 5: Number Analyzer

Difficulty: ⭐⭐⭐ Advanced

Write a program that analyzes an integer and reports multiple properties about it.

Check for:

  • Is it positive, negative, or zero?
  • Is it even or odd? (only if not zero)
  • Is it divisible by 5? (only if not zero)
number = int(input("Enter an integer: "))

# Your code here

Example Output:

Enter an integer: 30
The number is positive
The number is even
The number is divisible by 5

Enter an integer: -7
The number is negative
The number is odd
The number is not divisible by 5

Enter an integer: 0
The number is zero

Learning Goal: Combine multiple independent conditions and use the modulo operator (%) for divisibility checks.


Debugging Tips

When your conditionals don't work as expected:

  1. Print intermediate values to see what your conditions are actually checking
  2. Check your comparison operators (>, <, >=, <=, ==, !=)
  3. Verify indentation - Python is strict about proper indenting of code blocks
  4. Test edge cases - try boundary values like 0, maximum values, or empty inputs
  5. Use elif when conditions are mutually exclusive to avoid redundant checks

Next Steps

Congratulations on completing these challenges! You've now mastered conditional statements in Python. These skills form the foundation of programming logic and decision-making.

As you continue learning, you'll discover how conditionals combine with loops, functions, and data structures to create powerful, intelligent programs. Keep practicing, and happy coding! 🎉

In this chapter

  • 1.What Are Conditions?
  • 2.Basic `if` Logic
  • 3.`if` and `else`
  • 4.Chain Many Conditions
  • 5.Conditional Challenges

Frequently asked questions

What Are Conditions?

Every day, you make countless decisions based on conditions. If it's raining, you take an umbrella. If you're hungry, you eat. If the traffic light is red, you stop. These simple **if-then** patterns form the foundation of how we navigate the world—and they're exactly how programs make decisions too.

What is Basic `if` Logic?

At the heart of decision-making in Python lies the `if` statement. Think of it as a gatekeeper that checks whether something is true before allowing code to run. Just like you might check if it's raining before deciding to take an umbrella, your program can check conditions before executing certain code blocks.

What is `if` and `else`?

In real life, decisions rarely have just one outcome. When you check the weather before leaving home, you don't only plan for rain—you also decide what to do if it's *not* raining. Programming works the same way. The `else` statement pairs with `if` to handle the alternative path when your condition is false.

What is Chain Many Conditions?

You've learned how to make a binary choice with `if` and `else`—either one path or another. But real-world programs often need to choose between **many different possibilities**. What if you're building a grading system that assigns A, B, C, D, or F? Or a weather app that responds differently to sunny, rainy, snowy, or

What is Conditional Challenges?

Welcome to the final page of this chapter! Now that you've learned the mechanics of `if`, `elif`, and `else` statements, it's time to put your knowledge into practice. These challenges will help solidify your understanding and build your confidence in writing decision-making code.

More chapters in Python Programming

Want the full Python Programming experience?

Every chapter. Interactive lessons. AI teacher on tap. Study Lab for any photo or PDF. 3-day free trial — no credit card.

1000s of students
100% NCERT-aligned
Powered by AI

Install Learn Skill

Add to home screen for the best experience