Conditional Statements in Python (if, else, elif) with Examples
π Python Conditional
Statements Explained
if · if-else · if-elif-else · Nested if · Short if · Real-Life Examples
A conditional statement in Python is used to make decisions in a program. It checks a condition and runs a specific block of code only if that condition is True. If the condition is False, Python skips that block or runs an alternative. Conditional statements make programs smart and responsive to inputs.
The if statement is the most basic conditional statement. It checks a condition — if True, the code block inside runs. If False, Python skips it completely. The if statement uses a colon : at the end and the code inside must be indented (4 spaces). Indentation is mandatory in Python — missing it causes an IndentationError. The if statement checks only one condition at a time and runs the block only once when the condition is met.
age = 20 if age >= 18: print("You are an adult.")
marks = 40 if marks >= 50: print("Passed!") # marks = 40, NOT >= 50 → nothing printed
The if-else adds an alternative path when the condition is False. When if is True, the if block runs. When False, the else block runs instead. One of the two blocks always executes — never both, never neither. This makes if-else perfect for binary decisions like pass/fail, yes/no, or login/deny. The else keyword takes no condition — it handles all False cases automatically from the if above it.
marks = 75 if marks >= 50: print("Passed!") else: print("Failed!")
num = 7 if num % 2 == 0: print(num, "is Even") else: print(num, "is Odd")
The elif (else if) is used to check multiple conditions one by one. Python checks the first if — if True it runs that block and skips the rest. If False, it checks the next elif. This continues until a True condition is found. If none match, the final else runs. You can use as many elif blocks as needed. This is the standard way to handle multiple choices like grades, menus, or categories in Python programs.
marks = 72 if marks >= 90: print("Grade: A+") elif marks >= 80: print("Grade: A") elif marks >= 70: print("Grade: B") elif marks >= 60: print("Grade: C") else: print("Grade: F")
A nested if is an if statement written inside another if. It checks a second condition only after the first condition is already True. The outer if runs first — if True, Python enters and then checks the inner if. This is useful for multi-level decisions like checking age first then gender, or verifying username then password. Proper indentation is critical — each inner level must be indented further to the right.
age = 20 has_id = True if age >= 18: print("Age OK.") if has_id: print("You can vote!") else: print("No ID. Cannot vote.") else: print("Too young to vote.")
You can vote!
The short if — also called the ternary operator — lets you write a complete if-else in just one single line. It is used when the condition and result are simple. The syntax puts the true value first, then the condition with if, then the false value with else. It is not suitable for complex logic but is very useful for quick assignments. It makes code compact, clean, and easy to read for simple decisions.
age = 20 status = "Adult" if age >= 18 else "Minor" print(status)
a = 15 b = 22 big = a if a > b else b print("Bigger:", big)
num = 8 print("Even" if num % 2 == 0 else "Odd")
print()These are the most important rules you must always remember when using conditional statements in Python.
# ✅ Correct if True: print("OK!") # ❌ Wrong — causes IndentationError # if True: # print("Error!")
# ✅ Correct if x > 5: # ← colon needed! print("Yes") # ❌ Wrong — SyntaxError # if x > 5 # print("Yes")
# Falsy: 0, "", [], {}, None, False if 0: print("runs") # ← never runs if 1: print("runs!") # ← always runs
if name == "Ali":Here are real-world scenarios showing how conditional statements are used in actual Python programs.
balance = 5000 withdraw = 3000 if withdraw <= balance: balance -= withdraw print("Withdrawn!") print("Balance:", balance) else: print("Insufficient balance!")
Balance: 2000
username = "admin" password = "1234" if username == "admin" and password == "1234": print("Login successful!") else: print("Wrong credentials.")
temp = 38 if temp >= 40: print("Very Hot!") elif temp >= 30: print("Hot day.") elif temp >= 20: print("Pleasant.") else: print("Cold day.")
total = 1500 if total >= 2000: discount = 20 elif total >= 1000: discount = 10 else: discount = 0 print(f"Discount: {discount}%") pay = total - (total * discount // 100) print(f"Pay: {pay}")
Pay: 1350
✅ Every if/elif needs a colon :
✅ Code inside must be indented
✅ Use == to compare, not =
✅ Only the first True condition ever runs
Comments
Post a Comment