1. Program Branching: Making Decisions
By default, computer programs execute linearly, line by line. To create smart applications, we must let programs make decisions. Python uses if, elif (else-if), and else keywords to evaluate statements and branch code execution accordingly. A conditional statement evaluates to a Boolean value (True or False). Python uses indentations (4 spaces) rather than brackets to mark blocks of code under each branch.
2. Comparison Operators
Comparison operators are used to compare two values, yielding a Boolean output:
==Equal to (Note:=is for assignment,==is for comparison!)!=Not equal to<Less than |>Greater than<=Less than or equal to |>=Greater than or equal to
temperature = 22
if temperature > 30:
print("It's a hot day!")
elif temperature >= 15:
print("It's a pleasant day.")
else:
print("It's a cold day.")
3. Logical Operators: and, or, not
Logical operators allow you to combine multiple conditional statements or invert them:
and: ReturnsTrueif both conditions are True.or: ReturnsTrueif at least one condition is True.not: Inverts the Boolean state (returnsTrueif the condition is False).
age = 20
has_ticket = True
is_vip = False
# Both must be True
if age >= 18 and has_ticket:
print("Allowed entry")
# Either can be True
if has_ticket or is_vip:
print("Welcome inside")
4. Common Beginner Mistakes
⚠️ Watch out for these mistakes:
- Missing Colon: Forgetting the
:at the end ofif,elif, orelse. This causes aSyntaxError. - Single '=' for Comparison: Writing
if score = 100:instead ofif score == 100:. This is a syntax error because=assigns variables. - Indentation Errors: Failing to indent the code blocks under the conditional statement or mixing spaces and tabs. Ensure exactly 4 spaces.
Mini Practice: Movie Ticket Calculator
Write a script that prompts a user for their age. If they are under 12, the ticket costs $5. If they are between 12 and 64, the ticket costs $10. If they are 65 or older, the ticket costs $7. Print the ticket price in a formatted string.
Practice complete!
Awesome. You can branch code. Complete the quiz below to unlock loops.
Test Your Understanding
1. Which operator is used to check if two values are equal in Python?
2. What is the output of `print(True or False)`?
3. What happens if you skip indenting the code inside an `if` block?
🚀 Progression
Decisions are completed. Next, you'll learn how to repeat actions efficiently using **Loops**.