Conditional Statements (if, elif, else)
Sometimes your program needs to make decisions, just like you do in real life:
- 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 the essence of conditional logic.
How Python Makes Decisions
Python uses the keywords if, elif, and else to control which parts of your code run.
Here's a simple example:
Conditional Statements
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 isfalse, so that block is skipped. - Then it checks the next condition:
score >= 80. It istrue, so it printsGrade: B. - Once a condition is met, Python does not check the others.
- If none are true, the
elseblock runs.
Key Ideas to Remember
- Conditions are checked from top to bottom.
- Indentation shows which lines belong to each block.
- You can use multiple
elifstatements, but only oneifand oneelse.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.