if, elif & else
Make your Python programs decide what to do using if, elif and else statements with comparisons and logical operators — with clear examples.
What you will learn
- Branch with if / elif / else
- Compare values
- Combine conditions
Making decisions
An if statement lets your program choose what to do based on a condition. You can offer several choices: if is the first question, elif (short for “else if”) adds more questions, and else is the fallback when nothing else matched. Python checks them top to bottom and runs only the first block whose condition is true.
marks = 72
if marks >= 75:
print("Grade A")
elif marks >= 50:
print("Grade B")
else:
print("Keep practising")Walking through it with marks set to 72: Python first asks is 72 ≥ 75? — no, so it skips that block. Next it asks is 72 ≥ 50? — yes, so it runs that line and prints Grade B. The moment one condition matches, Python stops checking the rest, so else is ignored. If marks were, say, 40, both questions would fail and the else block would print Keep practising. Notice each block is indented under its condition.
Note: Output: Grade B
Sometimes one test is not enough. Combine conditions with and, or, not (Python uses words, not symbols). and needs both sides true; or needs either side true; not flips true and false.
age = 20
if age >= 18 and age < 60:
print("Adult")This checks two things at once with and: is age at least 18? and is age under 60? Both must be true for the block to run. Since age is 20, both parts are true, so it prints Adult. If age were 70, the second part would fail and nothing would print.
Note: Output: Adult
Q. In Python, "else if" is written as:
✍️ Practice
- Print whether a number is positive, negative or zero.
- Build a grade calculator with if/elif/else.
🏠 Homework
- Ask the user’s age and print whether they can vote (18+).