Spex3
    

Control Flow in Python: Conditional Statements (if, elif, else) 🔀


    

    

Conditional statements allow Python programs to make decisions based on conditions. The three main conditional statements are:

✅ if – Executes a block of code if the condition is True.
✅ elif (else if) – Checks multiple conditions if the first one is False.
✅ else – Runs if none of the previous conditions are True.

1️⃣ The if Statement

Executes a block of code only if the condition is True.

Example:


age = 18
if age >= 18:
print("You are eligible to vote.")

Output:


You are eligible to vote.


2️⃣ The if-else Statement
The else block runs if the if condition is False.

Example:


age = 16
if age >= 18:
print("You are eligible to vote.")
else:
print("You are too young to vote.")


Output:



You are too young to vote.


3️⃣ The if-elif-else Statement
Used for checking multiple conditions.

Example:


score = 75

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



Grade: C


4️⃣ Nested if Statements
An if statement inside another if.

Example:


age = 20
has_id = True

if age >= 18:
if has_id:
print("You can enter the club.")
else:
print("You need an ID to enter.")
else:
print("You are too young to enter.")
Output:



You can enter the club.


5️⃣ Using Logical Operators with if
You can combine conditions using and, or, and not.

Example:



age = 25
has_ticket = True

if age >= 18 and has_ticket:
print("You can watch the movie.")
else:
print("You cannot watch the movie.")
Output:



You can watch the movie.


    Date: 2025-03-22 00:00:00.000000