Loading

Making Decisions with if/else

Every auto driver in Kerala makes decisions all day. If the road ahead is flooded, take the bypass. If the bypass is also jammed, go via the main road. If everything is jammed, sit and wait. Python makes decisions the same way — using if, elif, and else.

Simple if — One Condition

Python — basic if statement
temperature = 38

if temperature > 37.5:
    print("You have a fever. Please rest.")

Notice the colon after the condition and the indentation (4 spaces or 1 tab) before the print. Python uses indentation to define what belongs inside the if block. This is not optional — Python will throw an error if the indentation is missing or inconsistent.

if / else — Two Paths

Python — if/else
marks = 35 if marks >= 40: print("Result: PASS") else: print("Result: FAIL") print("Supplementary exam required.")

if / elif / else — Multiple Paths

Like a grade system: above 90 is A+, above 80 is A, above 70 is B, and so on. For more than two choices, use elif (short for "else if").

Python — grade calculator with if/elif/else
percentage = 76

if percentage >= 90:
    grade = "A+"
elif percentage >= 80:
    grade = "A"
elif percentage >= 70:
    grade = "B"
elif percentage >= 60:
    grade = "C"
elif percentage >= 40:
    grade = "D"
else:
    grade = "F"

print("Your grade is:", grade)   # Your grade is: B
Key Idea

Python checks conditions from top to bottom and stops at the first one that is True. So you must write your conditions from most specific to least specific. If you wrote percentage >= 40 first, everyone would get grade D — because 76 is indeed >= 40, and Python would stop there without checking the others.

Nested if — Conditions Inside Conditions

Python — nested if (lab eligibility check)
attendance = 82 marks = 55 lab_fee_paid = True if attendance >= 75: if marks >= 40: if lab_fee_paid: print("Eligible for lab exam") else: print("Pay lab fee first") else: print("Marks too low for lab") else: print("Attendance shortage — not eligible")
Try This

Write a program that checks if a number entered by the user is positive, negative, or zero. Use num = int(input("Enter a number: ")) to get input. Then use if/elif/else to print the correct message.

Common Mistake — Indentation

Python is very strict about indentation. Mix tabs and spaces and Python will crash with an IndentationError. Pick one (4 spaces is the standard) and stick to it. VS Code and most editors handle this automatically if you configure them correctly.

while Loops — Do It Until Done

You set your phone alarm for 6 AM. It rings. You hit snooze. It rings again. You hit snooze again. This keeps going until you actually get up and turn it off. That is a while loop — it repeats as long as a condition is True.

Python — basic while loop (countdown)
count = 5 while count > 0: print("Countdown:", count) count = count - 1 # or: count -= 1 print("Launched!")

Each time the loop runs, it checks: is count > 0? If yes, run the indented block. If no, exit the loop and continue. This is why reducing count inside the loop is critical — without it, the condition never becomes False.

Common Mistake — Infinite Loop

If the condition in a while loop never becomes False, your program runs forever. Your computer's fan will spin up, the program will freeze, and you will have to force-quit it. Always make sure something inside the loop changes the condition variable. Press Ctrl+C to stop a runaway loop.

break and continue — Loop Controls

  • break — immediately exit the loop, even if the condition is still True
  • continue — skip the rest of this iteration and go back to the top of the loop
Python — break and continue
# Sum numbers until the user types 0 total = 0 while True: # Loop forever... until break num = int(input("Enter number (0 to stop): ")) if num == 0: break # Exit the loop when user enters 0 if num < 0: print("Negative — skipping") continue # Skip negatives, go back to input total += num # total = total + num print("Total:", total)
Try This

Write a while loop that keeps asking the user to guess a secret number (say, 42). If they guess wrong, print "Too high" or "Too low". When they guess correctly, print "Correct!" and break out of the loop. Count how many guesses it took.

for Loops — Going Through a List

Imagine a teacher calling out names from the attendance register — one by one, in order, until every name has been called. A for loop does exactly this: it goes through each item in a sequence, does something with it, then moves to the next one.

for with range()

range(n) generates numbers from 0 to n-1. range(1, 11) gives 1 to 10. range(1, 11, 2) gives 1, 3, 5, 7, 9 (step of 2).

Python — for loop with range (multiplication table)
number = 7 print(f"Multiplication table of {number}:") for i in range(1, 11): result = number * i print(f" {number} x {i} = {result}")

for with a List

Python — for loop through a list
students = ["Ananya", "Biju", "Chitra", "Dev", "Esha"] for student in students: print("Present:", student)

enumerate() — Index + Value Together

Sometimes you need both the position (index) and the value. enumerate() gives you both.

Python — enumerate
subjects = ["Maths", "Physics", "Chemistry", "English"] for index, subject in enumerate(subjects, start=1): print(f" {index}. {subject}")

Nested Loops — Loop Inside a Loop

Like a cricket tournament: for each team (outer loop), play against every other team (inner loop). Use carefully — nested loops can get slow with large data.

Python — nested loops (pattern)
for row in range(1, 6): # rows 1 to 5 for col in range(1, row+1): # columns: 1 up to current row print("*", end=" ") # end=" " prevents newline print() # newline after each row # Output: # * # * * # * * * # * * * * # * * * * *
Try This

Given a list of student marks: marks = [78, 92, 55, 88, 64, 71, 45], use a for loop to find: (1) the highest mark, (2) the lowest mark, (3) the average mark. Do not use Python's built-in max(), min(), or sum() — calculate manually using the loop.

Lists — Storing Multiple Things

A shopping list keeps all your items in one place, in order. You can add something you forgot, cross off something you already bought, or check how many items are left. Python's list works exactly like that — ordered, changeable, and can hold any data type.

Python — creating and accessing lists
# Create a list marks = [88, 72, 95, 60, 78] # Access by index (starts at 0) print(marks[0]) # 88 — first item print(marks[2]) # 95 — third item print(marks[-1]) # 78 — last item (negative index counts from end) # Modify an item marks[1] = 75 # Change second item from 72 to 75 print(marks) # [88, 75, 95, 60, 78]

Useful List Operations

Python — common list methods
subjects = ["Maths", "Physics", "Chemistry"] subjects.append("English") # Add to end print(subjects) # ['Maths', 'Physics', 'Chemistry', 'English'] subjects.remove("Chemistry") # Remove by value print(subjects) # ['Maths', 'Physics', 'English'] print(len(subjects)) # 3 — number of items print(sorted(subjects)) # Alphabetically sorted (doesn't change original) # Loop through the list: for subject in subjects: print("-", subject)

Finding the Average — A Practical Example

Python — average marks calculator
marks = [78, 92, 55, 88, 64, 71, 45] total = 0 for m in marks: total = total + m average = total / len(marks) print(f"Total: {total}") print(f"Number of subjects: {len(marks)}") print(f"Average: {average:.2f}") # :.2f means 2 decimal places
Key Idea — f-strings

An f-string (formatted string) lets you embed variables directly inside a string. Write an f before the opening quote, then put variables inside curly braces: f"Hello {name}, you scored {score}%". Much cleaner than concatenating strings with +.

Practical Project: Simple ATM Machine

Time to combine everything from this page — and everything from Python 101 — into one program. We will build a console-based ATM that lets you check your balance, deposit money, withdraw money, and exit. It uses a while loop for the menu and if/elif/else for decisions.

Python — Simple ATM Machine
# Simple ATM Machine # Demonstrates: while loops, if/elif/else, variables, f-strings balance = 5000.00 # Starting balance (in rupees) print("=" * 35) print(" Welcome to Quadratech Bank ATM") print("=" * 35) while True: # Keep showing menu until user exits print("\nWhat would you like to do?") print(" 1. Check Balance") print(" 2. Deposit Money") print(" 3. Withdraw Money") print(" 4. Exit") choice = input("\nEnter choice (1-4): ") if choice == "1": print(f"\nCurrent Balance: Rs. {balance:.2f}") elif choice == "2": amount = float(input("Enter deposit amount: Rs. ")) if amount <= 0: print("Invalid amount. Please enter a positive value.") else: balance = balance + amount print(f"Rs. {amount:.2f} deposited successfully.") print(f"New Balance: Rs. {balance:.2f}") elif choice == "3": amount = float(input("Enter withdrawal amount: Rs. ")) if amount <= 0: print("Invalid amount.") elif amount > balance: print("Insufficient balance!") print(f"Available balance: Rs. {balance:.2f}") else: balance = balance - amount print(f"Rs. {amount:.2f} withdrawn successfully.") print(f"Remaining Balance: Rs. {balance:.2f}") elif choice == "4": print("\nThank you for using Quadratech ATM. Goodbye!") break # Exit the while loop else: print("Invalid choice. Please enter 1, 2, 3, or 4.")

Run this program and actually try it — deposit some money, try withdrawing more than the balance, try entering invalid choices. See how the while True with break pattern creates a clean menu loop, and how elif chains handle every possible input.

Try This — Extend the ATM

Add a PIN check feature. Before the menu appears, ask the user to enter a PIN (say, 1234). Give them 3 attempts. If they get it wrong 3 times, print "Card blocked. Contact your bank." and exit. If they get it right, show the menu as normal. Hint: you will need a for loop with range(3) and a break when the PIN is correct.

← Previous
Python 101: Variables & Types
Next →
Python 103: Functions & Modules