Previous | Tutorial index | Next
if-else Statement – Two Paths, Two OutcomesUse if-else to run one code block if a condition is True, and a completely different block if it is False.
In Tutorial 1, you learned that an if statement can either run a block or skip it entirely (doing nothing). But in many real-world programs, you must choose between two actions. This is where if-else comes in.
An if-else statement creates a guaranteed fork:
if block): Runs only if the condition is True.else block): Runs only if the condition is False.Crucial Concept – Mutual Exclusivity:
The if block and the else block are mutually exclusive. This means exactly one of the two blocks will always execute. There is no scenario where both run, and no scenario where neither runs. The program must choose one of the two paths.
if-else [ Start ]
|
v
[Check Condition]
|
+---+---+
| |
True False
| |
v v
[If Block] [Else Block]
| |
+---+---+
|
v
[Continue with rest
of the program]
Imagine a security gate at a parking lot:
if alone: "If it rains, take an umbrella." (If it doesn't rain, you do nothing with the umbrella).if-else: "If it rains, take an umbrella. Else, put on sunglasses." (You are guaranteed to do one of these two things).if condition:
# Code block for when condition is True
action_a()
else:
# Code block for when condition is False
action_b()
# Code here runs regardless of which block executed
Grammar Rules to Memorize:
if line ends with a colon :.else line ends with a colon :.else keyword must be aligned vertically with the if keyword (same indentation level).(This is the practice task from the prompt, now shown as a full solution)
number = int(input("Enter a number: "))
if number % 2 == 0:
print(f"{number} is an even number.")
else:
print(f"{number} is an odd number.")
4 → 4 % 2 == 0 is True → Prints "4 is an even number."7 → 7 % 2 == 0 is False → Prints "7 is an odd number."password = input("Enter password: ")
if password.lower() == "python123": # .lower() converts to lowercase to ignore case
print("Access Granted. Welcome!")
else:
print("Access Denied. Incorrect password.")
"Python123".lower() becomes "python123", so the check passes.number = float(input("Enter a number: "))
if number > 0:
print("Positive number.")
else:
print("Not a positive number.") # This catches zero AND negative numbers!
Takeaway: The
elseblock catches everything that isn't> 0. This includes0,-5,-100.5, etc. Be careful—if you specifically wanted to handle negatives and zeros differently, you'd needelif(Tutorial 3).
total_purchase = float(input("Enter total purchase amount: $"))
if total_purchase >= 100:
discounted_price = total_purchase * 0.9 # 10% discount
print(f"Discount applied! You pay: ${discounted_price:.2f}")
else:
print(f"No discount. You pay: ${total_purchase:.2f}")
user_name = input("Enter your name: ")
if user_name: # An empty string "" is falsy. A non-empty string is truthy.
print(f"Hello, {user_name}!")
else:
print("Hello, stranger! (You didn't type anything).")
| Rule | Explanation |
|---|---|
else has NO condition |
else: is always written alone. You cannot write else (x > 5):. |
else must follow an if |
A lone else without a preceding if causes a SyntaxError. |
| Indentation determines ownership | The else must be indented exactly at the same level as its matching if. |
| Only ONE block runs | Because the condition is binary (True/False), Python will never run both blocks. |
Putting a Condition on else (The #1 Mistake)
else (x > 5): or else x > 5:SyntaxError: invalid syntaxelse stands for "everything else." If you need another condition, wait for Tutorial 3 (elif).Forgetting the Colon (:) on else
else (no colon)SyntaxError: invalid syntaxelse:.Indentation Mismatch
The else must align with its if. If the if is indented, the else must be indented to the exact same level.
Wrong:
if x > 5:
print("Big")
else: # Indented incorrectly!
print("Small")
Error: IndentationError: unindent does not match any outer indentation level
Assuming else runs for a specific "other" case
if score > 80 and use else, that else runs for every score <= 80 (including negative scores, strings if they got past, etc.). Remember, else is a catch-all, not a specific alternative.Nested if Confusion (Dangling else)
else always belongs to the nearest unpaired if at the same indentation level. This is rarely a bug if you indent correctly.Test your understanding before moving to the exercises.
Q1: What keyword do you use to run code when the if condition is False?
elifotherwiseelsethenQ2: In an if-else statement, it is possible for both blocks to run.
Q3: The else statement cannot have a __________ attached to it.
Q4: What is the output?
value = 0
if value:
print("Truthy")
else:
print("Falsy")
TruthyFalsyQ5: If the condition in an if-else is True, which block runs?
else blockif blockWrite a Python script for each task. Test them with different inputs.
Exercise 1: Pass or Fail
Ask for a score (0–100). Print "Pass" if 50 or higher, else "Fail".
score = float(input("Enter score: "))
if score >= 50:
print("Pass")
else:
print("Fail")
Exercise 2: Minimum Purchase
Ask for number of items. If 5 or more, print "Bulk discount applied!", else "No discount available."
items = int(input("How many items? "))
if items >= 5:
print("Bulk discount applied!")
else:
print("No discount available.")
Exercise 3: Name Length
Ask for a name. If length > 5, print "Long name!", else "Short name."
name = input("Enter name: ")
if len(name) > 5:
print("Long name!")
else:
print("Short name.")
Exercise 4: Guessing Game
Set secret = 7. Ask user to guess. If correct, print "You win!", else "Wrong guess!"
secret = 7
guess = int(input("Guess the number: "))
if guess == secret:
print("You win!")
else:
print("Wrong guess!")
Exercise 5: Leap Year (simplified)
Ask for a year. If divisible by 4, print "Leap year", else "Not a leap year".
year = int(input("Enter year: "))
if year % 4 == 0:
print("Leap year")
else:
print("Not a leap year")
if-else Statement (Tutorial 2 Review)Instructions: Complete all parts below. After finishing, click the "Answer" sections to check your work.
Write down the exact output for each snippet.
Snippet 1:
x = 10
if x % 2 == 1:
print("Odd")
else:
print("Even")
Even
Explanation: 10 % 2 equals 0. The condition 0 == 1 is False, so the else block runs and prints "Even".
Snippet 2:
city = "New York"
if city == "new york":
print("Welcome to the Big Apple!")
else:
print("You are in a different city.")
You are in a different city.
Explanation: The condition city == "new york" compares "New York" (capital 'N' and 'Y') to "new york" (lowercase). In Python, string comparisons are case‑sensitive, so they are not equal. Therefore, the else block runs.
Snippet 3:
age = 25
if age < 18:
ticket_price = 5
else:
ticket_price = 15
print(f"Ticket price: ${ticket_price}")
Ticket price: $15
Explanation: The condition age < 18 is False (25 is not less than 18). So the else block runs and sets ticket_price = 15. The final print outputs the string.
Snippet 4:
data = ""
if data:
print("Data received.")
else:
print("No data.")
No data.
Explanation: An empty string "" is considered falsy in Python. So if data: evaluates to False, and the else block runs.
The following snippets contain errors. Identify the error, explain why it's wrong, and write the corrected code.
Buggy Code 1:
score = 85
if score >= 60
print("Pass")
else:
print("Fail")
Error: Missing colon : at the end of the if line.
Explanation: In Python, every if statement must end with a colon. Without it, Python raises a SyntaxError.
Corrected Code:
score = 85
if score >= 60:
print("Pass")
else:
print("Fail")
Buggy Code 2:
temperature = 30
if temperature > 25:
print("It's hot.")
else temperature <= 25: # Something is wrong here!
print("It's cool.")
Error: Putting a condition on the else block. The else keyword does not accept a condition.
Explanation: else is a catch‑all for everything that didn't match the preceding if. If you need another condition, you must use elif (covered in Tutorial 3). This code raises a SyntaxError.
Corrected Code (using if-else):
Since the condition temperature <= 25 is the exact opposite of temperature > 25, we can simply remove the condition:
temperature = 30
if temperature > 25:
print("It's hot.")
else:
print("It's cool.")
(If you wanted a different condition, you would use elif).
Buggy Code 3:
num = 7
if num == 7:
print("Lucky number!")
else:
print("Not lucky.") # Check the indentation!
Error: The print("Not lucky.") statement is not indented correctly.
Explanation: In Python, the code inside the else block must be indented (usually 4 spaces) to show that it belongs to the else. Incorrect indentation raises an IndentationError.
Corrected Code:
num = 7
if num == 7:
print("Lucky number!")
else:
print("Not lucky.")
Write a Python script for each task. Test your code with different inputs.
Task 1: The Voter Validator Ask the user for their age.
"You are eligible to vote.""You are too young to vote."age = int(input("Enter your age: "))
if age >= 18:
print("You are eligible to vote.")
else:
print("You are too young to vote.")
Task 2: Positive or Not
Ask the user for a number. If it is greater than 0, print "Positive". If it is 0 or less, print "Non-positive".
num = float(input("Enter a number: "))
if num > 0:
print("Positive")
else:
print("Non-positive")
Task 3: Temperature Suitability Ask the user for the current temperature in Fahrenheit.
"Perfect weather!"."Weather is not ideal."temp = float(input("Enter temperature (°F): "))
if temp >= 60 and temp <= 80:
print("Perfect weather!")
else:
print("Weather is not ideal.")
Task 4: The Empty Input Guard Ask the user to type a message.
"You said: " followed by their message."You didn't say anything!".message = input("Type a message: ")
if message: # Non-empty strings are truthy
print(f"You said: {message}")
else:
print("You didn't say anything!")
Challenge Task: The FizzBuzz Warm-up Ask the user for an integer.
"Fizz".num = int(input("Enter an integer: "))
if num % 3 == 0:
print("Fizz")
else:
print(num)
Before submitting, ensure you can:
Great work completing this homework! You are now ready for Tutorial 3 (if-elif).
# Basic structure:
if CONDITION:
# Do this when True
else:
# Do this when False
# Real example:
age = int(input("Age: "))
if age >= 18:
print("Adult")
else:
print("Minor")
Key Takeaway for Tutorial 2:
Always ask yourself: "What are the two possible outcomes I need to handle?" If you have exactly two mutually exclusive paths, if-else is your tool. If you have more than two, or you need a "do nothing" option, you'll need if (Tutorial 1) or elif (Tutorial 3).
You are now ready to move on to Tutorial 3: The if-elif Statement – Multiple Selective Checks. Keep up the great work!