Previous | Tutorial index | Next

Tutorial 2: The if-else Statement – Two Paths, Two Outcomes

Learning Objective

Use if-else to run one code block if a condition is True, and a completely different block if it is False.

1. The Theory (Deep Dive)

The "Fork in the Road"

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:

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.

The Flowchart of if-else

[ Start ] | v [Check Condition] | +---+---+ | | True False | | v v [If Block] [Else Block] | | +---+---+ | v [Continue with rest of the program]

Real-World Analogy

Imagine a security gate at a parking lot:

Comparison to Tutorial 1

2. Syntax

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:

  1. The if line ends with a colon :.
  2. The else line ends with a colon :.
  3. The else keyword must be aligned vertically with the if keyword (same indentation level).
  4. The code blocks inside must be indented (4 spaces).

3. Expanded Code Examples

Example 1: The Classic Even/Odd Checker

(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.")

Example 2: The Password Checker (Case-Insensitive)

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.")

Example 3: Checking if a Number is Positive (or Not)

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 else block catches everything that isn't > 0. This includes 0, -5, -100.5, etc. Be careful—if you specifically wanted to handle negatives and zeros differently, you'd need elif (Tutorial 3).

Example 4: Discount Eligibility

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}")

Example 5: Check if a String is Empty

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).")

4. Important Rules (Reinforced)

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.

5. Common Pitfalls

  1. Putting a Condition on else (The #1 Mistake)

  2. Forgetting the Colon (:) on else

  3. Indentation Mismatch

  4. Assuming else runs for a specific "other" case

  5. Nested if Confusion (Dangling else)

6. Quiz (Quick Knowledge Check)

Test your understanding before moving to the exercises.

Q1: What keyword do you use to run code when the if condition is False?

Answer(C) `else`

Q2: In an if-else statement, it is possible for both blocks to run.

Answer(B) False

Q3: The else statement cannot have a __________ attached to it.

Answer(B) condition

Q4: What is the output?

value = 0 if value: print("Truthy") else: print("Falsy")
Answer(B) `Falsy`

Q5: If the condition in an if-else is True, which block runs?

Answer(B) The `if` block

7. Hands-on Practice Exercises

Write 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".

Sample Solution
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."

Sample Solution
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."

Sample Solution
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!"

Sample Solution
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".

Sample Solution
year = int(input("Enter year: ")) if year % 4 == 0: print("Leap year") else: print("Not a leap year")

Homework Assignment: The if-else Statement (Tutorial 2 Review)

Instructions: Complete all parts below. After finishing, click the "Answer" sections to check your work.

Homework Part A: Code Predictor (No Computer!)

Write down the exact output for each snippet.

Snippet 1:

x = 10 if x % 2 == 1: print("Odd") else: print("Even")
Answer
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.")
Answer
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}")
Answer
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.")
Answer
No data.

Explanation: An empty string "" is considered falsy in Python. So if data: evaluates to False, and the else block runs.

Homework Part B: Bug Hunter

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")
Answer

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.")
Answer

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!
Answer

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.")

Homework Part C: Write Complete Programs

Write a Python script for each task. Test your code with different inputs.

Task 1: The Voter Validator Ask the user for their age.

Sample Solution
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".

Sample Solution
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.

Sample Solution
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.

Sample Solution
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.

Sample Solution
num = int(input("Enter an integer: ")) if num % 3 == 0: print("Fizz") else: print(num)

Summary Checklist

Before submitting, ensure you can:

Great work completing this homework! You are now ready for Tutorial 3 (if-elif).

9. Quick Reference Card

# 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!

Previous | Tutorial index | Next