If statements
Make decisions in your code
Learning to make decisions in your code is a fundamental skill, and Python's if statements are the perfect tool for the job.
What are if statements?
Imagine you're giving instructions. Sometimes you want to say, "If it's raining, take an umbrella." if statements let your computer do the same thing. They check if a condition is true.
If the condition is true, a specific block of code runs. If it's false, that block of code is skipped.
Basic if statement
The simplest if statement checks one thing. You provide a condition. If it's True, the indented code below it executes.
temperature = 25
if temperature > 20:
print("It's a warm day!")if statement.If-else statements
What if you want to do one thing when a condition is true, and something different when it's false? That's where else comes in.
is_sunny = False
if is_sunny:
print("Wear sunglasses!")
else:
print("Might need a jacket.")If-elif-else chains
Sometimes you have more than two possibilities. Use elif (short for "else if") to check additional conditions if the previous ones were false.
grade = 85
if grade >= 90:
print("A")
elif grade >= 80:
print("B")
elif grade >= 70:
print("C")
else:
print("Fail")Multiple conditions
You can combine multiple conditions using the logical operators and and or.
and: Both conditions must beTrue.or: At least one condition must beTrue.
age = 18
has_ticket = True
if age >= 18 and has_ticket:
print("Welcome to the concert!")
else:
print("Sorry, you can't come in.")Nested if statements
You can put an if statement inside another if statement. This is called nesting. It allows for more complex decision-making.
is_member = True
purchases_last_month = 150
if is_member:
if purchases_last_month > 100:
print("You qualify for a premium discount!")
else:
print("Thanks for being a member.")
else:
print("Join our club for great benefits!")Common mistakes
- Forgetting the colon (
:) at the end ofif,elif, orelselines. - Incorrect indentation, which leads to
IndentationError. - Using a single equals sign (
=) for comparison instead of a double equals sign (==).=is for assignment,==is for checking if two values are equal.
Practice
Try these exercises to lock in what you just learned.
What's next?
You've learned how to make your programs smart enough to make decisions! Practice writing if statements with different conditions and combinations. Next, explore how to repeat actions using loops!