🟢 Beginner · Lesson 08
if, elif and else Statements
Decision Making
Programs often need to choose what to do based on a condition. The if statement runs a block only when its condition is True.
if / elif / else Syntax
Python – syntax
if condition1:
# runs if condition1 is True
elif condition2:
# runs if condition1 False and condition2 True
else:
# runs if all above are False- Each condition ends with a colon
:. - The block under it is indented (4 spaces).
elif= "else if"; you can have many.elseis optional.
Program 1: Pass or Fail
Python – passfail.py
marks = int(input("Enter marks: "))
if marks >= 33:
print("Result: PASS")
else:
print("Result: FAIL")Enter marks: 45
Result: PASS
If marks is 33 or more, the first block runs; otherwise the else block runs.
Program 2: Largest of Three Numbers
Python – largest.py
a = int(input("a: "))
b = int(input("b: "))
c = int(input("c: "))
if a >= b and a >= c:
print("Largest is", a)
elif b >= c:
print("Largest is", b)
else:
print("Largest is", c)a: 5
b: 9
c: 2
Largest is 9
- First check if
abeats both others. - If not,
elif b >= cdecides between b and c. - Otherwise
cis largest.
Program 3: Grade Calculator
Python – grade.py
pct = float(input("Enter percentage: "))
if pct >= 90:
grade = "A+"
elif pct >= 75:
grade = "A"
elif pct >= 60:
grade = "B"
elif pct >= 33:
grade = "C"
else:
grade = "Fail"
print("Grade:", grade)Enter percentage: 82
Grade: A
Python checks each elif top to bottom and stops at the first true one — so order matters (highest first).
Program 4: Positive, Negative or Zero
Python – signcheck.py
n = int(input("Enter a number: "))
if n > 0:
print("Positive")
elif n < 0:
print("Negative")
else:
print("Zero")Enter a number: -4
Negative
Nested if
An if can sit inside another if for two-level decisions.
Python – nested.py
age = int(input("Age: "))
if age >= 18:
has_id = input("Have ID? (yes/no): ")
if has_id == "yes":
print("Allowed to vote")
else:
print("Bring your ID")
else:
print("Too young to vote")Common Mistakes
- Using
=instead of==in the condition. - Forgetting the colon
:. - Wrong indentation inside the block.
- Putting
elifconditions in the wrong order.
Practice Tasks
- Check whether a number is even or odd.
- Take a year and check if it is a leap year.
- Ask a person's age and print child / teen / adult / senior.
- Take three sides and check if they can form a triangle.
Summary
ifruns a block when its condition is True.elifadds more choices;elseis the fallback.- Conditions need a colon and an indented block.
eliforder matters — check from highest/most-specific first.
💻 Live Code Editor
This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.