Part 1: Detailed Notes on Python Selection (if)
1. Why Selection?
Sequential programming executes line-by-line, top to bottom. Selection (branching)
allows the program to make decisions. It asks a question, and based on the answer (True or
False), it chooses which block of code to execute.
Bridge to Loops: In loops, we ask a condition repeatedly (“Is counter < 10?”). If
the condition is True, we run the loop body. Mastering if statements is mandatory
before touching while or for loops.
2. Boolean Logic (The Foundation)
Python evaluates conditions as Boolean values: True or False.
Comparison Operators:
== (equal to)
!= (not equal to)
> (greater than)
< (less than)
>= (greater than or equal to)
<= (less than or equal to)
3. The if Statement (Single Path)
if condition:
# Indented block (4 spaces)
# Executes ONLY if condition is True
4. The if-else Statement (Two Paths)
if condition:
# Runs if True
else:
# Runs if False
5. The if-elif-else Ladder (Multiple Paths)
Python checks the if condition first.
If False, it moves to the elif.
It stops at the first condition that evaluates to True.
else runs only if everything above is False.
if score >= 90:
grade = "A"
Page 1 of 7
elif score >= 80: # Only checked if score < 90
grade = "B"
elif score >= 70:
grade = "C"
else: # Only runs if all above are False
grade = "F"
6. Logical Operators (Combining Conditions)
and → True only if both sides are True.
or → True if at least one side is True.
not → Reverses the boolean ( not True is False).
Short-Circuiting:
and stops checking at the first False.
or stops checking at the first True.
7. Membership & Identity
in / not in: Check if a value exists inside a list, string, or tuple.
is: Used for comparing objects (better to use == for values at this stage).
8. Chaining Comparisons (Pythonic)
Python allows elegant chaining that reads like math:
if 10 <= age < 20: # Equivalent to age >= 10 and age < 20
print("Teenager")
9. Truthiness (Implicit Booleans)
In Python, non-boolean values can act like True or False:
Falsy (False): 0, 0.0, None, "" (empty string), [] (empty list), {} (empty dict).
Truthy (True): Everything else (e.g., "hello", 5, [1,2]).
name = input("Enter name: ")
if name: # Works! Runs if name is NOT an empty string.
print(f"Hello {name}")
else:
print("You didn't type anything!")
10. Nested if Statements
Putting an if inside another if. Use this sparingly; often, logical operators (and) are cleaner.
11. The pass Placeholder
if blocks cannot be empty. Use pass to do nothing:
Page 2 of 7
if x > 0:
pass # TODO: Implement later
12. The Ternary Operator (Short-hand)
For simple assignments in one line:
# Syntax: value_if_true if condition else value_if_false
status = "Adult" if age >= 18 else "Minor"
⚠️Common Pitfalls (Read Twice!)
1. Missing Colon (:): Forgetting the colon at the end of if, elif, or else.
2. Indentation Errors: Python uses indentation instead of curly braces {}. Mixing tabs
and spaces causes fatal errors. Stick to 4 spaces.
3. Assignment vs Comparison: Using = (assignment) instead of == (comparison). if x =
5: is illegal. if x == 5: is correct.
4. Forgetting elif: Using multiple if statements when you mean to use elif (which stops
when it finds a match).
# BAD (Runs all checks)
if x > 0: print("Pos")
if x > 0: print("Also Pos")
# GOOD (Mutually exclusive)
if x > 0: print("Pos")
elif x == 0: print("Zero")
Part 2: Practice Questions
🟢 Beginner Level (Building Confidence)
1. Even or Odd: Ask the user for an integer. Print "Even" if divisible by 2, else "Odd".
2. Voting Eligibility: Ask age. If >= 18, print "Eligible to vote"; otherwise, print "Too
young".
3. Positive/Negative/Zero: Ask for a number. Print "Positive", "Negative", or "Zero".
🟡 Intermediate Level (Combining Logic)
4. Leap Year Checker: A year is a leap year if it is divisible by 4. However, if it is
divisible by 100, it must also be divisible by 400 to be a leap year. (Hint: if (year %
400 == 0) or (year % 4 == 0 and year % 100 != 0)).
5. Grade Calculator: Ask for a score (0-100). Assign a grade:
o 90+: “A”
o 80-89: “B”
o 70-79: “C”
Page 3 of 7
o 60-69: “D”
o <60: “F” Bonus: If input is outside 0-100, print "Invalid score".
6. Max of Three: Ask the user for 3 numbers. Print the largest one. (Do this without
using Python’s max() function).
🟠 Challenging (Applying Logic & Truthiness)
7. Simple ATM Withdrawal: Ask for balance and withdraw_amount.
o If withdraw_amount > balance: Print "Insufficient funds".
o Else if withdraw_amount <= 0: Print "Invalid amount".
o Else: Deduct the amount and print the new balance.
o Additionally: If the new balance is less than 50, print "Warning: Low balance".
8. Password Strength Checker:
o Ask for a password.
o If len(password) < 6: Print "Too short".
o Else if len(password) >= 6 and "!" in password: Print "Strong password".
o Else: Print "Medium password (add a special character '!' to make it strong)".
9. Shipping Cost Calculator:
o Ask for region ("local" or "international") and weight (kg).
o Local: $5 flat rate.
o International: $10 + $2 per kg.
o Edge case: If weight is negative or region is unknown, print "Invalid input".
🔴 The “Precursor to Loops” Challenge (Input Validation)
10. The “Try Again” Logic (Without Loops):
Ask the user for a PIN (e.g., 1234).
If they enter the correct pin, print "Access Granted".
If they enter the wrong pin, print "Access Denied. Try again."
Reflection: Why is this inefficient? (Because it only lets them try once. Next week,
you will use a while loop to let them keep trying until correct!).
Part 3: Solutions (With Explanations)
Solution 1: Even or Odd
num = int(input("Enter a number: "))
if num % 2 == 0:
print("Even")
else:
print("Odd")
Page 4 of 7
Solution 2: Voting Eligibility
age = int(input("Enter your age: "))
if age >= 18:
print("Eligible to vote")
else:
print("Too young")
Solution 3: Positive/Negative/Zero
num = float(input("Enter a number: "))
if num > 0:
print("Positive")
elif num < 0:
print("Negative")
else:
print("Zero")
Solution 4: Leap Year
year = int(input("Enter year: "))
if (year % 400 == 0) or (year % 4 == 0 and year % 100 != 0):
print("Leap Year")
else:
print("Not a Leap Year")
Solution 5: Grade Calculator (With Validation)
score = float(input("Enter score: "))
if score < 0 or score > 100:
print("Invalid score")
elif score >= 90:
print("A")
elif score >= 80:
print("B")
elif score >= 70:
print("C")
elif score >= 60:
print("D")
else:
print("F")
Solution 6: Max of Three (Nested Logic)
a = float(input("Num 1: "))
b = float(input("Num 2: "))
c = float(input("Num 3: "))
if a >= b and a >= c:
largest = a
elif b >= a and b >= c:
Page 5 of 7
largest = b
else:
largest = c
print(f"Largest is: {largest}")
Solution 7: ATM Withdrawal
balance = 1000.0
withdraw = float(input("Amount to withdraw: "))
if withdraw <= 0:
print("Invalid amount")
elif withdraw > balance:
print("Insufficient funds")
else:
balance -= withdraw
print(f"New balance: ${balance:.2f}")
if balance < 50:
print("Warning: Low balance")
Solution 8: Password Strength
password = input("Enter password: ")
if len(password) < 6:
print("Too short")
elif len(password) >= 6 and "!" in password:
print("Strong password")
else:
print("Medium password (add '!' to make it strong)")
Solution 9: Shipping Cost
region = input("Region (local/international): ").lower()
weight = float(input("Weight in kg: "))
if weight < 0:
print("Invalid weight")
elif region == "local":
print("Total cost: $5.00")
elif region == "international":
total = 10 + (2 * weight)
print(f"Total cost: ${total:.2f}")
else:
print("Invalid region")
Solution 10: Single-try PIN (The Loop Preview)
pin = input("Enter PIN: ")
if pin == "1234":
print("Access Granted")
else:
Page 6 of 7
print("Access Denied. Try again.")
print("(Next week we'll use a while loop to let you try until correct!)")
Next Steps: Notice how in Question 10, the program ends immediately after a wrong guess.
Loops solve this by wrapping the if block inside a while condition. The condition for the
loop will be while pin_entered != correct_pin:. You’re now ready to learn iteration!
Page 7 of 7