DSPython Logo DSPython

Conditional Statements

Make decisions in your code using if, elif, and else.

Python Basics Beginner 30 min

👋 Introduction to Control Flow

Imagine you are driving a car using GPS. The GPS doesn't just give you one single straight line to your destination. Instead, it makes decisions based on the situation: "If there is traffic, take a left," or "If the road is closed, take a U-turn."

In programming, this is called Control Flow. Normally, Python runs your code line-by-line from top to bottom. But sometimes, you want to run certain lines of code only if a specific condition is met. This ability to make decisions makes your software "smart" and dynamic.

🎯 Topic 1: The if Statement

The if statement is the most fundamental decision-making tool in Python. It acts like a gatekeeper. It checks a condition (a question that results in either True or False). If the answer is True, the gate opens, and the code inside is executed. If it is False, the code is skipped entirely.

📝 Syntax Breakdown:

Pay close attention to two things here:

  • The colon (:) at the end of the `if` line. This tells Python "Ok, get ready for the code block."
  • The indentation (spaces) for the code block. Python strictly relies on whitespace.
if condition:
    # This code runs ONLY if condition is True
    # Notice the 4 spaces of indentation

💻 Example: Basic Check

# Let's check if a user is eligible to vote
age = 20

if age >= 18:
print("Success: You are eligible to vote.")
print("Don't forget to bring your ID!")

# Since 20 is greater than 18, both print statements will run.

🔄 Topic 2: The else Statement

An if statement by itself only handles the "Success" case. But what if you want to do something specific when the condition fails? That is where else comes in.

Think of it like a fork in the road. You MUST go one way or the other. You cannot go both ways, and you cannot stand still. If the if condition is False, the code automatically jumps to the else block.

[Image of flowchart showing if-else branching logic]

💻 Example: Pass or Fail

# Checking exam results
marks = 35

if marks >= 40:
print("Congratulations! You passed.")
else:
print("Sorry, you failed. Try again.")

# Output: Sorry, you failed. Try again.

🎲 Topic 3: The elif Statement

Life isn't always binary (True or False). sometimes you have many options. For example, buying a shirt: "If it's Red, I'll buy it. Else if it's Blue, I'll buy it. Else if it's Black, I'll buy it. Else, I'll leave."

In Python, we use elif (short for "else if") to handle multiple conditions. Python checks them from top to bottom. Crucial Point: As soon as Python finds one condition that is True, it executes that block and ignores all the rest below it.

💻 Example: Traffic Light System

light_color = "yellow"

if light_color == "green":
print("Go!")
elif light_color == "yellow":
print("Slow down and prepare to stop.")
elif light_color == "red":
print("Stop!")
else:
print("Signal malfunction. Proceed with caution.")

📦 Topic 4: Nested if Statements

Sometimes, a decision depends on another decision. This is called "Nesting". It simply means putting an if statement inside another if statement.

Think of an ATM machine. First, it checks "Is the PIN correct?". ONLY if the PIN is correct does it ask the second question: "Is there enough balance?". If the PIN is wrong, it doesn't even bother checking the balance.

💻 Example: ATM Logic

pin_correct = True
balance = 500
withdraw_amount = 1000

if pin_correct:
# We are now inside the first if
print("PIN Accepted.")
if balance >= withdraw_amount:
# This requires double indentation!
print("Transaction Successful. Collecting Cash.")
else:
print("Insufficient Funds.")
else:
print("Wrong PIN.")

🔧 Topic 5: Advanced Operators

To make complex decisions, we use Logical Operators. These allow us to combine multiple checks into a single line of code.

🔗 The "Big Three" Logical Operators

  • AND: Returns True only if BOTH sides are True.
    Example: To drive, you need a license AND a car.
  • OR: Returns True if AT LEAST ONE side is True.
    Example: To pay, you can use Cash OR Credit Card.
  • NOT: Reverses the result. True becomes False, False becomes True.
    Example: If NOT raining, go outside.

🎯 Try It Yourself (Leap Year Logic):

A year is a leap year if it is divisible by 4, EXCEPT if it is divisible by 100, UNLESS it is also divisible by 400. Sounds confusing? Logic operators make it easy:

year = 2024

# Complex logic in one line using AND/OR
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print(f"{year} is a leap year")
else:
print(f"{year} is not a leap year")

⚠️ Common Mistakes to Avoid

Even experienced developers make these mistakes. Watch out for them!

1. Assignment vs Comparison

Wrong: if x = 5: (This tries to assign 5 to x)
Right: if x == 5: (This asks "Is x equal to 5?")

2. Indentation Errors

Python does not use curly braces {} like C++ or Java. It uses spaces. If your indentation is messy, your code will crash with an IndentationError. Always use 4 spaces (or 1 tab) consistently.

3. Forgetting the Colon

Every if, elif, and else line MUST end with a colon :. It is the most common syntax error for beginners.