Conditional Statements (if, elif, else)
Sometimes your program needs to make decisions — just like you do.
- If your score is above 90, you get an A.
- If it’s above 80, you get a B.
- Otherwise, you try harder next time.
This is what conditional logic is all about.
How Python Makes Decisions
Python uses the keywords if
, elif
, and else
to control which lines of code get executed.
Let’s look at a simple example:
score = 85
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
else:
print("Grade: C or below")
What’s Happening Here?
- Python checks the first condition:
score >= 90
. It’s false, so it skips that block. - Then it checks the next:
score >= 80
. It’s true, so it prints "Grade: B". - It does not check further once a match is found.
- If none match, the
else
block is executed.
Key Ideas to Remember
- Conditions are evaluated top to bottom.
- Indentation (spacing) shows which lines belong to each block.
- You can use as many
elif
as needed, but only oneif
and oneelse
.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.