foreach-ui logo
codeLanguages
account_treeDSA

Quick Actions

quizlock Random Quiz
trending_uplock Progress
  • 1
  • 2
  • 3
  • 4
  • quiz
Python
  • Understand what conditional statements are and why they matter
  • Learn how Python makes decisions using conditions
  • Write your first if statements
  • Understand how indentation defines code blocks

Introduction to Conditional Statements

Life is full of decisions. Should I bring an umbrella? Is this movie appropriate for my age? Do I have enough money for this purchase? We make hundreds of decisions daily, each one following a pattern: IF something is true, THEN do something.

Programming works exactly the same way. Conditional statements give your programs the ability to think, decide, and react. Without them, programs would be like trains on a track – always going the same direction, no matter what. With conditionals, your programs become intelligent and responsive.


What Are Conditional Statements?

Conditional statements are the decision-makers of programming. They evaluate a condition and choose which code to run based on whether that condition is True or False.


                  The Decision Process                            

                                                                  
                                                  
                      Condition                                
                                                  
                                                                 
                                      
                                                               
                                          
           True                   False                      
                                          
                                                               
                                          
          Do This                 Skip or                    
           Code                  Do Other                    
                                          
                                                                  

Real-World Analogies

Real-Life Decision Programming Equivalent
"If it's raining, take an umbrella" if is_raining: take_umbrella()
"If you're 18 or older, you can vote" if age >= 18: can_vote = True
"If the password is correct, log in" if password == correct: login()
"If items in cart, show checkout" if cart_items: show_checkout()

The Basic if Statement

The if statement is Python's most fundamental decision-making tool.

Anatomy of an if Statement


                    Structure of if Statement                     

                                                                  
   if condition:          ← Keyword + Condition + Colon          
       do_something()     ← Indented code block (4 spaces)       
       do_more()          ← Still part of the if block           
   next_code()            ← Not indented = outside the if        
                                                                  

Your First if Statement

Let's write a simple age verification:

age = 20

if age >= 18:
    print("You are an adult!")
    print("You can vote in elections.")

print("Thanks for checking!")  # Always runs

What happens here?

  1. Python checks: Is age >= 18? (Is 20 >= 18?)
  2. Answer: True
  3. Python runs the indented code
  4. Then continues with unindented code

Output:

You are an adult!
You can vote in elections.
Thanks for checking!

When the Condition is False

age = 15

if age >= 18:
    print("You are an adult!")
    print("You can vote in elections.")

print("Thanks for checking!")  # Always runs

What happens here?

  1. Python checks: Is age >= 18? (Is 15 >= 18?)
  2. Answer: False
  3. Python skips the indented code
  4. Continues with unindented code

Output:

Thanks for checking!

The Power of Indentation

In Python, indentation isn't just for aesthetics – it's how Python knows which code belongs to the if statement. This is different from many other languages that use curly braces {}.

Correct Indentation

temperature = 35

if temperature > 30:
    print("It's hot outside!")      #  Part of if
    print("Stay hydrated!")         #  Part of if
    print("Wear sunscreen!")        #  Part of if

print("Have a nice day!")           #  Outside if (always runs)

Common Indentation Mistakes

#  WRONG: Missing indentation
if temperature > 30:
print("It's hot!")  # IndentationError!

#  WRONG: Inconsistent indentation
if temperature > 30:
    print("It's hot!")
  print("Stay cool!")  # IndentationError!

#  WRONG: Tab/space mixing
if temperature > 30:
    print("It's hot!")    # 4 spaces
	print("Stay cool!")   # Tab - Don't mix!

Visual Guide to Indentation


                  Understanding Indentation                       

                                                                  
   if condition:                                                  
   ····print("Inside if")    ← 4 spaces = inside the block      
   ····print("Still inside") ← 4 spaces = still inside          
   print("Outside")          ← 0 spaces = outside the block     
                                                                  
   (···· represents 4 spaces)                                    
                                                                  

Conditions: The Heart of Decisions

A condition is any expression that evaluates to True or False. You already know the comparison operators from earlier lessons!

Comparison Operators in Conditions

Operator Meaning Example Result
== Equal to 5 == 5 True
!= Not equal to 5 != 3 True
> Greater than 5 > 3 True
< Less than 5 < 3 False
>= Greater or equal 5 >= 5 True
<= Less or equal 5 <= 3 False

Examples with Different Conditions

# Numeric comparisons
score = 85

if score >= 90:
    print("Excellent! You got an A!")

if score >= 70:
    print("Good job! You passed!")  # This will print (85 >= 70)

# String comparisons
user_input = "yes"

if user_input == "yes":
    print("Great! Let's continue!")

# Boolean checks
is_logged_in = True

if is_logged_in:
    print("Welcome back!")

# With variables
password = "secret123"
entered = "secret123"

if password == entered:
    print("Access granted!")

Truthy and Falsy Values

Python doesn't always need explicit comparisons. Some values are inherently "truthy" or "falsy":

What Python Considers False (Falsy)

# All of these are "falsy" - they act like False
if 0:           # Zero
    print("Won't print")
    
if "":          # Empty string
    print("Won't print")
    
if []:          # Empty list
    print("Won't print")
    
if None:        # None value
    print("Won't print")

What Python Considers True (Truthy)

# All of these are "truthy" - they act like True
if 1:           # Any non-zero number
    print("Will print!")
    
if "hello":     # Any non-empty string
    print("Will print!")
    
if [1, 2, 3]:   # Any non-empty list
    print("Will print!")

Practical Use of Truthy/Falsy

# Instead of:
if len(username) > 0:
    print("Username provided")

# You can write:
if username:  # Truthy if not empty
    print("Username provided")

# Checking for items
cart = ["apple", "banana"]

if cart:  # Truthy if not empty
    print(f"You have {len(cart)} items in your cart")

Combining Conditions with Logical Operators

Make complex decisions by combining multiple conditions:

Using and (Both must be True)

age = 25
has_license = True

if age >= 18 and has_license:
    print("You can rent a car!")

Think of it like a strict bouncer: "You need ID AND a ticket to enter."

Using or (At least one must be True)

is_weekend = True
is_holiday = False

if is_weekend or is_holiday:
    print("No work today! ")

Think of it like flexible payment: "Pay with cash OR card."

Using not (Reverses the condition)

is_raining = False

if not is_raining:
    print("Great weather for a walk!")

Practical Examples

Example 1: Temperature Advisor

temperature = 28

print(" Weather Advisor")
print("-" * 20)

if temperature > 30:
    print("It's very hot! Stay cool and drink water.")

if temperature > 20:
    print("Nice weather! Perfect for outdoor activities.")

if temperature < 10:
    print("It's cold! Bundle up and stay warm.")

print("-" * 20)
print("Stay safe out there!")

Example 2: Login Validation

correct_username = "admin"
correct_password = "secret123"

# User input (simulated)
entered_user = "admin"
entered_pass = "secret123"

print(" Login System")
print("=" * 25)

if entered_user == correct_username and entered_pass == correct_password:
    print(" Login successful!")
    print("Welcome to the dashboard!")

print("=" * 25)

Example 3: Discount Calculator

total_purchase = 150
is_member = True

print(" Checkout")
print("-" * 25)
print(f"Subtotal: ${total_purchase}")

if total_purchase >= 100:
    print("You qualify for free shipping! ")

if is_member:
    print("Member discount applied! ")

print("-" * 25)

Key Takeaways


                   Remember These Points                          

                                                                  
   if statements make decisions based on conditions            
                                                                  
   Syntax: if condition:                                       
             (indented code)                                      
                                                                  
   Always end the if line with a colon (:)                     
                                                                  
   Indentation (4 spaces) defines what's inside the block      
                                                                  
   Conditions evaluate to True or False                        
                                                                  
   Use and, or, not to combine conditions                      
                                                                  
   Empty values (0, "", [], None) are "falsy"                  
                                                                  

What's Next?

You've learned the basics of making decisions with if statements. But what if you want to do something else when the condition is False? In the next lesson, we'll explore else and elif to handle multiple possibilities and create complete decision trees!

© 2026 forEach. All rights reserved.

Privacy Policy•Terms of Service