Chapter 5: Making Decisions 🤔
So far, your programs have been running straight from top to bottom — every line executes, every time. But real programs need to make decisions. Should I show this message or that one? Should I continue or stop? That’s what this chapter is all about!
By the end of this chapter, you’ll be able to write programs that think and adapt based on different situations.
Booleans: True and False 🎯
Before we can make decisions, we need to understand Boolean values. Named after mathematician George Boole, these are the simplest data type in Python — they can only be one of two values: True or False.
is_raining = True
is_sunny = False
print(is_raining) # Shows: True
print(is_sunny) # Shows: False
Notice that True and False start with capital letters — this is important! Python won’t recognize true or false in lowercase.
Why Booleans Matter
Booleans are the foundation of decision-making in programming. They answer yes/no questions:
- Is the user logged in?
TrueorFalse - Is the player out of lives?
TrueorFalse - Is this the correct password?
TrueorFalse
Every decision your program makes ultimately comes down to something being True or False.
Checking Data Types
You can verify that a value is Boolean using the type() function:
print(type(True)) # Shows: <class 'bool'>
print(type(False)) # Shows: <class 'bool'>
The abbreviation bool stands for Boolean.
Comparison Operators 🔍
Comparison operators let you compare values and get Boolean results. These are the building blocks for making decisions.
The Six Comparison Operators
| Operator | Meaning | Example | Result |
|---|---|---|---|
== | Equal to | 5 == 5 | True |
!= | Not equal to | 5 != 3 | True |
> | Greater than | 7 > 4 | True |
< | Less than | 3 < 8 | True |
>= | Greater than or equal to | 5 >= 5 | True |
<= | Less than or equal to | 4 <= 6 | True |
Important: == vs =
This is a common mistake for beginners. Remember:
=assigns a value to a variable (e.g.,age = 14)==checks if two values are equal (e.g.,age == 14)
# Assignment (one equal sign)
age = 14
# Comparison (two equal signs)
print(age == 14) # Shows: True
print(age == 20) # Shows: False
Using Comparisons
Let’s see comparisons in action:
score = 85
passing_score = 60
print(score > passing_score) # Shows: True
print(score == 100) # Shows: False
print(score >= 80) # Shows: True
You can compare numbers, strings, and even variables:
# Comparing numbers
temperature = 25
print(temperature < 30) # Shows: True
# Comparing strings
name = "Alex"
print(name == "Alex") # Shows: True
print(name == "Jordan") # Shows: False
# Comparing variables
player1_score = 100
player2_score = 95
print(player1_score > player2_score) # Shows: True
String Comparisons
When comparing strings, Python checks if they’re exactly the same:
answer = "python"
print(answer == "python") # Shows: True
print(answer == "Python") # Shows: False (case matters!)
The if Statement 🚦
Now we can finally make decisions! The if statement lets your program execute code only when a condition is True.
Basic Syntax
if condition:
# Code here runs only if condition is True
print("The condition was true!")
The structure is important:
- Start with the keyword
if - Write your condition (which evaluates to
TrueorFalse) - End the line with a colon
: - Indent the code that should run if the condition is true
Indentation Matters
Python uses indentation (spaces at the start of a line) to know which code belongs to the if statement. Use 4 spaces or one Tab:
age = 16
if age >= 13:
print("You are a teenager!")
print("Welcome to the teen zone!")
print("This always runs, outside the if block")
Real Examples
# Example 1: Temperature check
temperature = 35
if temperature > 30:
print("It's hot outside!")
print("Don't forget sunscreen!")
# Example 2: Password validation
password = "secret123"
correct_password = "secret123"
if password == correct_password:
print("Access granted!")
print("Welcome back!")
# Example 3: Game score
score = 100
if score >= 100:
print("Achievement unlocked: Century!")
If the condition is False, the indented code simply doesn’t run — Python skips right over it.
The else Block ⚖️
What if you want to do one thing when a condition is True, and something different when it’s False? That’s where else comes in.
Basic Syntax
if condition:
# Runs if condition is True
print("Condition is true")
else:
# Runs if condition is False
print("Condition is false")
How It Works
The else block provides an alternative path. One of the two blocks will always run — never both, never neither.
age = 10
if age >= 13:
print("You can create a social media account")
else:
print("You're too young for social media")
If age is 13 or more, the first message shows. Otherwise, the second message shows.
More Examples
# Example 1: Even or odd
number = 7
if number % 2 == 0:
print(f"{number} is even")
else:
print(f"{number} is odd")
# Example 2: Temperature advice
temperature = 15
if temperature >= 20:
print("It's warm! Wear a t-shirt.")
else:
print("It's cold! Wear a jacket.")
# Example 3: Pass or fail
score = 55
passing_grade = 60
if score >= passing_grade:
print("Congratulations! You passed!")
else:
print("Keep studying, you'll get it next time!")
Visualizing the Flow
Think of if-else as a fork in the road:
- If the condition is
True, take the left path (theifblock) - If the condition is
False, take the right path (theelseblock) - You always take exactly one path
The elif Block 🌿
Sometimes you need to check multiple conditions, not just two. That’s where elif (short for “else if”) comes in.
Basic Syntax
if condition1:
# Runs if condition1 is True
elif condition2:
# Runs if condition1 is False and condition2 is True
elif condition3:
# Runs if condition1 and condition2 are False, and condition3 is True
else:
# Runs if all conditions above are False
How It Works
Python checks each condition from top to bottom:
- If the first condition is
True, run that block and skip the rest - Otherwise, check the next
elifcondition - Continue until a condition is
Trueor you reachelse - Only one block will ever run
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
print(f"Your grade is: {grade}") # Shows: Your grade is: B
Multiple Conditions Example
# Traffic light system
light = "yellow"
if light == "green":
print("Go!")
elif light == "yellow":
print("Slow down, prepare to stop")
elif light == "red":
print("Stop!")
else:
print("Unknown light color")
Order Matters
Be careful with the order of your conditions:
# This works correctly
age = 16
if age < 13:
print("Child")
elif age < 18:
print("Teenager")
else:
print("Adult")
# Output: Teenager
# This has a problem!
age = 16
if age < 18:
print("Not an adult") # This runs first
elif age < 13:
print("Child") # This never runs for age 16!
# Output: Not an adult
Always put more specific conditions before general ones.
Logical Operators 🔗
Sometimes one condition isn’t enough. Logical operators let you combine multiple conditions into complex decision-making.
The Three Logical Operators
| Operator | Meaning | Example | Result |
|---|---|---|---|
and | Both must be True | True and True | True |
or | At least one must be True | True or False | True |
not | Reverses the Boolean | not True | False |
The and Operator
Both conditions must be True for the whole expression to be True:
age = 16
has_license = True
if age >= 16 and has_license:
print("You can drive!")
else:
print("You cannot drive yet")
Truth table for and:
| Condition 1 | Condition 2 | Result |
|---|---|---|
True | True | True |
True | False | False |
False | True | False |
False | False | False |
The or Operator
At least one condition must be True:
day = "Saturday"
if day == "Saturday" or day == "Sunday":
print("It's the weekend!")
else:
print("It's a weekday")
Truth table for or:
| Condition 1 | Condition 2 | Result |
|---|---|---|
True | True | True |
True | False | True |
False | True | True |
False | False | False |
The not Operator
Reverses a Boolean value:
is_raining = False
if not is_raining:
print("Let's go to the park!")
else:
print("Stay inside today")
not True becomes False
not False becomes True
Combining Operators
You can combine multiple logical operators:
# Must be a teenager AND have permission
age = 14
has_permission = True
if age >= 13 and age <= 19 and has_permission:
print("You can attend the event!")
# Weekend OR holiday
day = "Monday"
is_holiday = False
if day == "Saturday" or day == "Sunday" or is_holiday:
print("No school today!")
else:
print("Time for school")
Using Parentheses for Clarity
When combining and and or, use parentheses to make your intention clear:
# Check if someone can get a discount
age = 65
is_student = False
# Senior (65+) OR student gets discount
if (age >= 65) or (is_student):
print("You get a discount!")
Quick Recap 🎯
Excellent progress! Here’s what you’ve learned:
- Booleans are
TrueorFalsevalues - Comparison operators (
==,!=,<,>,<=,>=) compare values ifstatements run code only when a condition isTrueelseprovides an alternative when the condition isFalseeliflets you check multiple conditions- Logical operators (
and,or,not) combine conditions
You now have the power to make your programs intelligent and responsive!
Hands-On Mini Project: Quiz Game 🚀
Let’s put everything together by building an interactive quiz game! This project will use input, decisions, and everything you’ve learned so far.
Your Mission
Create a quiz game with at least 3 questions. Track the user’s score and give them feedback at the end based on how well they did.
Example Solution
# Python Knowledge Quiz Game
print("=" * 40)
print(" PYTHON QUIZ GAME")
print("=" * 40)
print("\nAnswer the following questions!")
print("Type your answer and press Enter.\n")
# Initialize score
score = 0
total_questions = 5
# Question 1
print("Question 1: What symbol is used for comments in Python?")
print("a) //")
print("b) #")
print("c) /* */")
answer = input("Your answer: ").lower()
if answer == "b" or answer == "#":
print("✓ Correct!\n")
score += 1
else:
print("✗ Wrong! The correct answer is: b) #\n")
# Question 2
print("Question 2: Which of these is a Boolean value?")
print("a) Yes")
print("b) 1")
print("c) True")
answer = input("Your answer: ").lower()
if answer == "c" or answer == "true":
print("✓ Correct!\n")
score += 1
else:
print("✗ Wrong! The correct answer is: c) True\n")
# Question 3
print("Question 3: What operator checks if two values are equal?")
print("a) =")
print("b) ==")
print("c) ===")
answer = input("Your answer: ").lower()
if answer == "b" or answer == "==":
print("✓ Correct!\n")
score += 1
else:
print("✗ Wrong! The correct answer is: b) ==\n")
# Question 4
print("Question 4: What is 5 % 2 in Python?")
print("a) 2.5")
print("b) 2")
print("c) 1")
answer = input("Your answer: ").lower()
if answer == "c" or answer == "1":
print("✓ Correct!\n")
score += 1
else:
print("✗ Wrong! The correct answer is: c) 1\n")
# Question 5
print("Question 5: Which keyword is used for decision making?")
print("a) when")
print("b) if")
print("c) check")
answer = input("Your answer: ").lower()
if answer == "b" or answer == "if":
print("✓ Correct!\n")
score += 1
else:
print("✗ Wrong! The correct answer is: b) if\n")
# Calculate results
print("=" * 40)
print(" QUIZ COMPLETE!")
print("=" * 40)
print(f"\nYou scored: {score} out of {total_questions}")
# Give feedback based on score
if score == total_questions:
print("🏆 Perfect score! You're a Python master!")
elif score >= 4:
print("🌟 Excellent work! You really know your stuff!")
elif score >= 3:
print("👍 Good job! You're learning well!")
elif score >= 2:
print("📚 Not bad! Keep practicing!")
else:
print("💪 Keep studying! You'll get better with practice!")
# Extra challenge: Calculate percentage
percentage = (score / total_questions) * 100
print(f"Percentage: {percentage}%")
Challenge Yourself
Try adding these features to your quiz:
- More questions — Add 5-10 questions total
- Different topics — Include questions about variables, strings, math operators
- Lives system — Give the player 3 lives; lose one for each wrong answer
- Difficulty levels — Ask the user to choose Easy, Medium, or Hard
- Randomized questions — Change the order each time (we’ll learn how to do this in future chapters!)
Tips for Your Quiz
- Use
input().lower()to accept both uppercase and lowercase answers - Accept multiple correct formats (e.g., “b” or “true”)
- Give encouraging feedback even for wrong answers
- Make the output visually appealing with separators and emojis
- Test your quiz yourself to make sure it works correctly
What’s Next?
In the next chapter, we’ll learn about loops — a way to repeat code automatically without writing it over and over. You’ll discover how to make your programs more efficient and powerful!
Get ready to level up your coding skills even further!
Great work completing this chapter! Decision-making is one of the most important skills in programming.