If/Else Statements
If/Else Statements
Basic If Statement
age = 18if age >= 18:
print("You are an adult")
If-Else
age = 16if age >= 18:
print("You can vote")
else:
print("You are too young to vote")
Elif (Else If)
score = 85if 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}") # B
Nested Conditions
age = 25
has_license = Trueif age >= 18:
if has_license:
print("You can drive!")
else:
print("You need to get a license")
else:
print("You are too young to drive")
Logical Operators in Conditions
temperature = 25
is_sunny = Trueif temperature > 20 and is_sunny:
print("Perfect day for the beach!")
Ternary Operator
age = 20
status = "adult" if age >= 18 else "minor"
print(status) # adult
Summary
- If: execute code if condition is True
- Else: execute code if condition is False
- Elif: multiple conditions
- Use logical operators (and, or, not) to combine conditions
Next Lesson
In the next lesson, you'll learn about loops (for and while).
Quiz - Quiz - If/Else Statements
1. What keyword starts a conditional statement?
2. What does elif mean?
3. What is the correct syntax for ternary operator?