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 decide which lines of code should 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
else
block runs.
Key Ideas to Remember
- Conditions are checked from top to bottom.
- Indentation shows which lines belong to each block.
- You can use multiple
elif
statements, but only oneif
and oneelse
.
Quiz
0 / 1
In Python, which keyword is used to check another condition after an initial if
?
if
else
elif
for
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help
Code Editor
Run
Generate
Execution Result