⬅ Previous Next ➡

Conditional Statements

Decision Making: if Statement
  • if checks a condition.
  • If the condition is True, the block runs.
age = 18

if age >= 18:
    print("Eligible to vote")
Decision Making: if-else Statement
  • if-else provides two paths.
  • if runs when condition is True, else runs when False.
num = 7

if num % 2 == 0:
    print("Even")
else:
    print("Odd")
Decision Making: if-elif-else Ladder
  • Used when you have multiple conditions.
  • First True condition executes; remaining are skipped.
marks = 82

if marks >= 90:
    print("A+")
elif marks >= 80:
    print("A")
elif marks >= 70:
    print("B")
elif marks >= 60:
    print("C")
else:
    print("Fail")
Nested Conditions (if inside if)
  • Nested if means if inside another if.
  • Useful when second condition depends on first condition.
username = "admin"
password = "1234"

if username == "admin":
    if password == "1234":
        print("Login success")
    else:
        print("Wrong password")
else:
    print("Wrong username")
Ternary Operator (One-line if-else)
  • Ternary operator is a short form of if-else in one line.
num = 15
result = "Even" if num % 2 == 0 else "Odd"
print(result)

a = 10
b = 20
maximum = a if a > b else b
print("Max:", maximum)
Practical Example: Positive / Negative / Zero
  • Checks number type using if-elif-else.
n = int(input("Enter a number: "))

if n > 0:
    print("Positive")
elif n < 0:
    print("Negative")
else:
    print("Zero")
Practical Example: Leap Year Check
  • Leap year if divisible by 400
  • OR divisible by 4 but not divisible by 100
year = int(input("Enter year: "))

if (year % 400 == 0) or (year % 4 == 0 and year % 100 != 0):
    print("Leap Year")
else:
    print("Not a Leap Year")
Practical Example: Billing Discount (Ternary)
  • If amount >= 1000 → 10% discount, else 0 discount.
  • Uses ternary operator for discount.
amount = float(input("Enter total amount: "))

discount = amount * 0.10 if amount >= 1000 else 0
payable = amount - discount

print(f"Discount: {discount:.2f}")
print(f"Payable: {payable:.2f}")
⬅ Previous Next ➡