Conditional Statements
Conditional statements let your code make decisions.
if Statement: Executes code if condition is True.
if...elif...else: Chain multiple conditions.
Key Points:
- Use colon (:) after conditions
- Indentation defines the code block
- elif is short for "else if"
- Comparison operators: ==, !=, <, >, <=, >=
- Logical operators: and, or, not
Truthy and Falsy: Falsy values: False, None, 0, "", [], {}, () Everything else is truthy.
Ternary Expression: value_if_true if condition else value_if_false
Code Examples
If/Elif/Elsepython
# Simple if
age = 20
if age >= 18:
print("You are an adult")
# if...else
temperature = 15
if temperature > 25:
print("It's hot!")
else:
print("It's not hot")
# if...elif...else
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"
print(f"Grade: {grade}")
# Ternary expression
status = "adult" if age >= 18 else "minor"
print(f"Status: {status}")
# Multiple conditions
has_ticket = True
age = 25
if has_ticket and age >= 18:
print("You can enter the venue")
# Checking membership
fruits = ["apple", "banana", "cherry"]
if "banana" in fruits:
print("We have bananas!")
# Falsy values
if not []: # Empty list is falsy
print("Empty list is falsy")Python's clean syntax makes conditionals easy to read. Remember: indentation is required!
Quick Quiz
1. What is 'elif' short for in Python?
Was this lesson helpful?