🐍
Conditional Statements (if/else)
Beginner
80 XP
35 min
Lesson Content
Making Decisions: Conditional Statements
Conditional statements allow your program to make decisions and execute different code based on conditions. This is fundamental to programming!
The if Statement
Execute code only if a condition is True:
age = 18
if age >= 18:
print("You are an adult")The if-else Statement
Execute one block if True, another if False:
age = 15
if age >= 18:
print("You are an adult")
else:
print("You are a minor")The if-elif-else Statement
Check multiple conditions:
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"
print(f"Your grade is {grade}")Comparison Operators Review
# Equal to
if x == 5:
print("x is 5")
# Not equal to
if x != 5:
print("x is not 5")
# Greater than
if x > 10:
print("x is greater than 10")
# Less than
if x < 10:
print("x is less than 10")
# Greater than or equal
if x >= 10:
print("x is 10 or more")
# Less than or equal
if x <= 10:
print("x is 10 or less")Logical Operators
Combine multiple conditions:
age = 25
has_license = True
# AND - both must be True
if age >= 18 and has_license:
print("You can drive")
# OR - at least one must be True
if age < 18 or age > 65:
print("Special pricing available")
# NOT - reverses the condition
if not has_license:
print("You need a license")Nested Conditionals
Conditionals inside conditionals:
age = 20
has_ticket = True
if age >= 18:
if has_ticket:
print("Welcome to the event!")
else:
print("You need a ticket")
else:
print("You must be 18 or older")Common Patterns
# Check if number is positive, negative, or zero
number = 5
if number > 0:
print("Positive")
elif number < 0:
print("Negative")
else:
print("Zero")
# Check if string is empty
text = ""
if text:
print("Text has content")
else:
print("Text is empty")Example Code
Create a program that assigns a grade based on a score.
# Grade Calculator
# Score >= 90: A
# Score >= 80: B
# Score >= 70: C
# Score >= 60: D
# Otherwise: F
score = 85
# Your code here:
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"Score: {score}, Grade: {grade}")Expected Output:
Score: 85, Grade: B
Study Tips
- •Read the theory content thoroughly before practicing
- •Review the example code to understand key concepts
- •Proceed to the Practice tab when you're ready to code