This section introduces conditional logic in Python. You'll learn how to write programs that make decisions based on certain conditions using if, elif, and else statements.
By the end of this section, you should be able to:
Understand how Python evaluates conditions
Use comparison operators to create conditions
Write multi-branch if statements
Handle user input to guide program behavior
Lesson 1: Making Decisions with if
The if statement lets your program run certain code only when a condition is true.
Example:
age = 18
if age >= 18:
print("You are an adult.")
In this example, Python checks the condition age >= 18. If it’s true, it runs the code inside the block. If not, it skips it.
Note: Python uses indentation (spaces or tabs) to define blocks. This is required—don’t forget it.
Lesson 2: Adding else
Sometimes you want your program to do something else if the condition is false.
age = 16
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
The else block runs if the if condition is not true.
Lesson 3: Using elif for Multiple Conditions
You can chain multiple conditions using elif, short for “else if.”
Example:
score = 72
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: D or lower")
Python checks each condition in order. Once it finds one that is true, it runs that block and skips the rest.
Lesson 4: Comparison Operators
You’ll use comparison operators in your conditions:
Operator
Meaning
Example
==
Equals
x == 5
!=
Not equal
x != 3
>
Greater than
x > 10
<
Less than
x < 100
>=
Greater than or equal
x >= 0
<=
Less than or equal
x <= 50
Example:
number = int(input("Enter a number: "))
if number == 0:
print("You entered zero.")
else:
print("You did not enter zero.")
Quiz: Check Your Understanding
1. What does this code print if age = 20?
if age >= 18:
print("Welcome")
else:
print("Sorry")
Answer: Welcome
2. Which operator means "not equal to" in Python? a) !== b) != c) <> Answer: b) !=
3. What is wrong with this code?
x = 10 if x > 5
print("Big")
Answer: Missing a colon : after the if condition.
4. True or False: The else block will always run if no other condition is true. Answer: True
Practice Exercise: Number Checker
Write a program that:
Asks the user to enter a number
Tells the user if the number is:
Negative
Zero
Positive
Example:
Enter a number: -5
That number is negative.
Starter code:
number = int(input("Enter a number: "))
if number < 0:
print("That number is negative.")
elif number == 0:
print("That number is zero.")
else:
print("That number is positive.")
Challenge: Also print whether the number is even or odd (use number % 2 to get the remainder).