Python Course — Day 4

Conditionals, Lists & Loops

Today you'll teach your programs to make decisions, store collections of data, and repeat actions automatically. These three ideas power almost every program ever written.

Lab Modules

📌 Setup

Open VS Code → open H:\Pooja → create a new folder called day4. Open the integrated terminal (Ctrl + `) and navigate: cd H:\Pooja\day4. All files today go inside this folder.

Quick Recap — Day 3 Review

Let's make sure yesterday's concepts are solid before building on them. Answer these without looking back.

📝 Recap Quiz 1

What is the output of this code?
x = 10
x = x + 5
print(x)

A 10
B 15
C x + 5
D Error
x starts as 10. Then x = x + 5 takes the current value (10), adds 5, and stores 15 back into x.
📝 Recap Quiz 2

What is type("42")?

A int
B float
C str
D number
Anything inside quotes is a str (string), even if it looks like a number. "42" is text, 42 (no quotes) is an int.
📝 Recap Quiz 3

You run code and get: NameError: name 'scre' is not defined. What happened?

A You misspelled a variable name
B You forgot a quote
C You divided by zero
D Python crashed
NameError means Python doesn't recognize the variable name scre. You probably meant score. Always check spelling.
📝 Recap Quiz 4

What does "hello".upper() return?

A "hello"
B "Hello"
C Error
D "HELLO"
.upper() converts every letter to uppercase: "HELLO".

Conditionals — Teaching Programs to Decide

Think about any app you use. When you type a wrong password, it shows "Incorrect password." When you type the right one, it logs you in. Different things happen depending on a condition. That's what conditionals do.

🏠 Real-World Analogy

You make conditional decisions every day without thinking about it:

IF it's raining → take an umbrella
ELSE IF it's sunny → wear sunglasses
ELSE → just go outside normally

You check a condition (is it raining?), and depending on the answer (yes or no), you do different things. That's all if/elif/else does in Python — it lets the program choose what to do based on a condition.

💡 Why Do We Need Conditionals?

Without conditionals, a program would do the exact same thing every time — no matter what. Think of an ATM: it needs to check if you have enough balance before letting you withdraw money. A login page needs to check if your password is correct. A game needs to check if your health reached zero. Conditionals make programs smart — they can react differently to different situations.

TASK 2.1 Your First If Statement

Create if_basic.py:

PYTHONif_basic.py
age = 18 if age >= 18: print("You are an adult.") print("You can vote!") print("Program finished.")
Output
You are an adult. You can vote! Program finished.
  1. Type, save, run. Now change age to 15, save and run again. Notice that "You are an adult" and "You can vote" don't appear, but "Program finished" still does.
  2. The two print lines that are indented (pushed to the right) are inside the if block. They only run when the condition is True. The last print is NOT indented, so it always runs.

💡 Indentation — The Most Important Rule in Python

Notice how the two lines inside the if are pushed to the right by 4 spaces? That's called indentation. In Python, indentation is NOT optional — it's how Python knows which lines are "inside" the if block and which are outside.

Other programming languages use curly braces { } to group code. Python uses spaces. This forces your code to be visually clean and readable — you can always see the structure just by looking at the spacing.

Rule: Every line inside an if (or elif, else, loop, etc.) MUST be indented by the same amount (4 spaces is the standard). When you stop indenting, you're "outside" the block.

TASK 2.2 If / Else

Create if_else.py:

PYTHONif_else.py
password = input("Enter password: ") if password == "python123": print("Access granted!") print("Welcome back.") else: print("Wrong password!") print("Try again.")
  1. Run it and type python123 — you get the "Access granted" path.
  2. Run it again and type anything else — you get the "Wrong password" path.
  3. else catches everything that doesn't match the if condition. It's the "otherwise" branch.
TASK 2.3 If / Elif / Else — Multiple Conditions

Create grade.py:

PYTHONgrade.py
score = int(input("Enter your score (0-100): ")) if score >= 90: print("Grade: A") elif score >= 80: print("Grade: B") elif score >= 70: print("Grade: C") elif score >= 60: print("Grade: D") else: print("Grade: F")
  1. Run it with different scores: 95, 85, 72, 55. Notice how Python checks from top to bottom, and stops at the first match.
  2. elif means "else if" — check this condition only if all the ones above were False.
TASK 2.4 See an IndentationError

Create indent_error.py with this broken code:

PYTHONindent_error.py
x = 10 if x > 5: print("x is big")
  1. Run it. You'll get: IndentationError: expected an indented block after 'if' statement on line 3
  2. Python is telling you: "You wrote an if on line 3, but the next line isn't indented, so I don't know what's supposed to be inside the if block."
  3. Fix: Add 4 spaces before print on line 4 so it becomes: print("x is big"). In VS Code, you can also press Tab to indent.

💡 Comparison Operators

== equal to    != not equal to    > greater than    < less than    >= greater or equal    <= less or equal

Remember: = (one equals) is assignment (store a value). == (two equals) is comparison (check if equal).
📝 Quiz

What does this print if temp = 25?
if temp > 30:
    print("Hot")
elif temp > 20:
    print("Warm")
else:
    print("Cold")

A Hot
B Warm
C Cold
D Hot and Warm
25 is NOT > 30, so the first if is skipped. 25 IS > 20, so the elif matches. Python prints "Warm" and stops checking — it doesn't continue to else.

Lists — Storing Collections of Data

So far, every variable has held one value. But what if you need to store 10 student names? Or 50 test scores? You could make 50 separate variables, but that would be a nightmare. That's why lists exist.

🏠 Real-World Analogy

Think of a shopping list on paper. Instead of writing each item on a separate piece of paper (separate variables), you write them all on one list. You can add items, remove items, check how many items you have, and go through each item one by one. A Python list works exactly the same way.

💡 Why Do We Need Lists?

Think of apps you use: a to-do app stores a list of tasks. Your music player has a list of songs. Instagram shows a list of posts. Google search returns a list of results. Whenever an app deals with multiple items of the same kind, there's a list behind the scenes.

TASK 3.1 Without Lists vs. With Lists

Create list_why.py — see how painful life would be without lists:

PYTHONlist_why.py
# WITHOUT lists — storing 5 student names: student1 = "Alice" student2 = "Bob" student3 = "Charlie" student4 = "Diana" student5 = "Eve" print(student1, student2, student3, student4, student5) # Imagine doing this for 100 students... horrible! print() # WITH a list — all names in ONE variable: students = ["Alice", "Bob", "Charlie", "Diana", "Eve"] print(students)
TASK 3.2 Creating Lists and Accessing Items

Create list_basics.py:

PYTHONlist_basics.py
fruits = ["apple", "banana", "cherry", "date"] # Access items by position (index) — counting starts at 0! print(fruits[0]) # "apple" — first item print(fruits[1]) # "banana" — second item print(fruits[3]) # "date" — fourth item print(fruits[-1]) # "date" — last item (shortcut!) # How many items? print("Total fruits:", len(fruits))
⚠️ Indexing Starts at 0

The first item is at position [0], NOT [1]. This trips up beginners constantly. fruits[0] = "apple", fruits[1] = "banana", etc. This is called zero-based indexing and it's used in almost every programming language.

TASK 3.3 Modifying Lists

Create list_modify.py:

PYTHONlist_modify.py
tasks = ["buy milk", "do homework"] print("Start:", tasks) # Add an item to the end tasks.append("call mom") print("After append:", tasks) # Change an item tasks[0] = "buy eggs" print("After change:", tasks) # Remove an item tasks.remove("do homework") print("After remove:", tasks) # Check if something is in the list print("call mom" in tasks) # True print("go gym" in tasks) # False
📝 Quiz

colors = ["red", "green", "blue"]
What is colors[1]?

A "red"
B "blue"
C "green"
D Error
Index starts at 0: [0]="red", [1]="green", [2]="blue".

Loops — Repeating Actions

What if you want to print "Hello" 100 times? Or greet every student in a list? You could write 100 print statements, but that's insane. Loops let you repeat code automatically.

🏠 Real-World Analogy

Imagine a teacher calling attendance: "Alice?" ... "Bob?" ... "Charlie?" ... They're doing the same action (calling a name) for each student in the list. That's a loop — repeating an action for every item in a collection, or repeating an action a certain number of times.

TASK 4.1 Without Loops vs. With Loops

Create loop_why.py:

PYTHONloop_why.py
# WITHOUT a loop: print("Hello, Alice!") print("Hello, Bob!") print("Hello, Charlie!") print("Hello, Diana!") print() # WITH a loop — same result, much cleaner: names = ["Alice", "Bob", "Charlie", "Diana"] for name in names: print("Hello, " + name + "!")

Both produce the same output. But if you had 1000 names, the loop version is still just 3 lines. The non-loop version would be 1000 lines.

TASK 4.2 For Loop with range()

Create loop_range.py:

PYTHONloop_range.py
# Print numbers 1 to 5 for i in range(1, 6): print(i) print("---") # range(5) means 0, 1, 2, 3, 4 (starts at 0, stops BEFORE 5) for i in range(5): print("Repetition", i)

range(1, 6) generates: 1, 2, 3, 4, 5 (starts at 1, stops before 6). range(5) generates: 0, 1, 2, 3, 4.

TASK 4.3 While Loop

Create loop_while.py:

PYTHONloop_while.py
# Keep asking until they type "quit" command = "" while command != "quit": command = input("Type something (or 'quit' to exit): ") print("You typed:", command) print("Goodbye!")

while loops keep repeating as long as the condition is True. Once command equals "quit", the condition becomes False and the loop stops.

TASK 4.4 Loop + List + Conditional — All Together

Create combo.py:

PYTHONcombo.py
scores = [85, 42, 91, 67, 55, 78] print("Pass/Fail Report:") for score in scores: if score >= 60: print(score, "→ PASS") else: print(score, "→ FAIL")

Notice the indentation: the if/else is indented inside the for loop, and the print statements are indented inside the if/else. Two levels of indentation = 8 spaces.

📝 Quiz

How many times does this print?
for i in range(3):
    print("Hi")

A 1
B 2
C 4
D 3
range(3) generates 0, 1, 2 — that's 3 values, so the loop runs 3 times.

Conditionals — Practice & Debugging

10 exercises: 5 programming + 5 debugging. Create a new file for each one.

🚀 Programming Exercises

C1Even or Odd

Write a program that asks the user for a number and prints whether it's even or odd. (Hint: a number is even if number % 2 == 0. The % operator gives the remainder.)

number = int(input("Enter a number: "))
if number % 2 == 0:
    print("Even")
else:
    print("Odd")
C2Ticket Price

Write a program: ask for user's age. If age < 5 → "Free", age 5-17 → "Child ticket: $5", age 18-64 → "Adult ticket: $10", age 65+ → "Senior ticket: $7".

age = int(input("Enter age: "))
if age < 5:
    print("Free")
elif age <= 17:
    print("Child ticket: $5")
elif age <= 64:
    print("Adult ticket: $10")
else:
    print("Senior ticket: $7")
✏️ C3 — Fill in the Blank

Complete this so it prints "Positive", "Negative", or "Zero":

PYTHONex_c3.py
num = int(input("Number: ")) if num > 0: print("Positive") ??? num < 0: print("Negative") ???: print("Zero")
First blank: elif — second blank: else
📝 C4 — Predict the Output

x = 15
if x > 20:
    print("A")
elif x > 10:
    print("B")
elif x > 5:
    print("C")

A A
B B
C B and C
D C
15 is NOT > 20 → skip. 15 IS > 10 → print "B" and stop. Even though 15 > 5 is also true, elif stops at the first match.
C5Simple Login

Write a program that asks for username and password. If username is "admin" AND password is "1234" → "Login successful". Otherwise → "Invalid credentials". (Hint: use and to combine conditions: if a == "x" and b == "y":)

user = input("Username: ")
pw = input("Password: ")
if user == "admin" and pw == "1234":
    print("Login successful")
else:
    print("Invalid credentials")

🐛 Debug Exercises

🐛 CD1 — IndentationError
PYTHONcd1.py
temp = 35 if temp > 30: print("It's hot!")
IndentationError on line 3. The print needs to be indented (4 spaces) to be inside the if block. Fix:     print("It's hot!")
🐛 CD2 — SyntaxError
PYTHONcd2.py
age = 20 if age >= 18 print("Adult")
SyntaxError — missing colon : at the end of line 2. Every if, elif, else, for, while line MUST end with :. Fix: if age >= 18:
🐛 CD3 — Assignment vs Comparison
PYTHONcd3.py
color = "red" if color = "blue": print("Sky color!")
SyntaxError on line 2. Used = (assignment) instead of == (comparison). Fix: if color == "blue":
🐛 CD4 — Logic Bug

Expected: score 75 should print "B", but it prints "C". Find the logic error.

PYTHONcd4.py
score = 75 if score >= 90: print("A") elif score >= 80: print("B") elif score >= 60: print("C") elif score >= 70: print("B")
Logic error — wrong order. The check >= 60 comes before >= 70. Since 75 >= 60 is True, Python prints "C" and stops, never reaching the 70 check. Fix: put higher thresholds first: swap the >= 60 and >= 70 lines.
🐛 CD5 — Mixed Indentation
PYTHONcd5.py
x = 10 if x > 5: print("big") print("number")
IndentationError — inconsistent indentation. Line 3 has 4 spaces, line 4 has 5 spaces. All lines in the same block must have the exact same indentation. Fix: make line 4 also have exactly 4 spaces.

Lists — Practice & Debugging

10 exercises: 5 programming + 5 debugging.

🚀 Programming Exercises

L1Favorite Foods

Create a list of 4 favorite foods. Print the entire list, print the first item, print the last item, and print how many items are in the list.

foods = ["pizza", "biryani", "pasta", "momos"]
print(foods)
print("First:", foods[0])
print("Last:", foods[-1])
print("Total:", len(foods))
L2Shopping List Manager

Start with items = ["milk", "bread"]. Add "eggs" to the list, then remove "bread", then change the first item to "almond milk". Print the list after each change.

items = ["milk", "bread"]
items.append("eggs")
print(items)
items.remove("bread")
print(items)
items[0] = "almond milk"
print(items)
✏️ L3 — Fill in the Blank

Complete this so it adds "grape" to the list and prints the total count:

PYTHONex_l3.py
fruits = ["apple", "banana"] fruits.???("grape") print("Count:", ???(fruits))
First blank: append — Second blank: len
📝 L4 — Predict the Output

nums = [10, 20, 30]
nums.append(40)
nums[0] = 99
print(nums)

A [10, 20, 30, 40]
B [99, 20, 30, 40]
C [99, 20, 30]
D [10, 20, 30, 99]
append(40) adds 40 at the end: [10,20,30,40]. Then [0] = 99 changes the first item: [99,20,30,40].
L5Sum of a List

Create a list numbers = [10, 20, 30, 40, 50]. Use a for loop to calculate the total sum. Print "Sum: 150".

numbers = [10, 20, 30, 40, 50]
total = 0
for n in numbers:
    total = total + n
print("Sum:", total)

🐛 Debug Exercises

🐛 LD1 — IndexError
PYTHONld1.py
colors = ["red", "green", "blue"] print(colors[3])
IndexError: list index out of range. The list has 3 items at indices 0, 1, 2. Index [3] doesn't exist. Fix: colors[2] for the last item, or colors[-1].
🐛 LD2 — Wrong Method
PYTHONld2.py
items = ["pen", "book"] items.add("eraser") print(items)
AttributeError: list has no method 'add'. The correct method for lists is .append(), not .add(). Fix: items.append("eraser").
🐛 LD3 — TypeError
PYTHONld3.py
nums = [1, 2, 3] print("Count: " + len(nums))
TypeError. len(nums) returns an int (3), and you can't + a string with an int. Fix: print("Count: " + str(len(nums))) or simpler: print("Count:", len(nums)).
🐛 LD4 — Missing Brackets
PYTHONld4.py
animals = "cat", "dog", "bird" print(animals[0])
Not a crash, but wrong type. Without square brackets [], Python creates a tuple (a different type), not a list. It still works with indexing, but you can't use .append() etc. Fix: animals = ["cat", "dog", "bird"].
🐛 LD5 — ValueError
PYTHONld5.py
fruits = ["apple", "banana"] fruits.remove("cherry") print(fruits)
ValueError: list.remove(x): x not in list. You can't remove "cherry" because it's not in the list. Fix: check first: if "cherry" in fruits: then fruits.remove("cherry"), or remove an item that actually exists.

Loops — Practice & Debugging

10 exercises: 5 programming + 5 debugging.

🚀 Programming Exercises

LP1Multiplication Table

Ask the user for a number. Print its multiplication table from 1 to 10. Example for 5: 5 x 1 = 5, 5 x 2 = 10, etc.

num = int(input("Enter a number: "))
for i in range(1, 11):
    print(num, "x", i, "=", num * i)
LP2Count Vowels

Given word = "programming", use a loop to count how many vowels (a, e, i, o, u) are in the word. Print the count.

word = "programming"
count = 0
for letter in word:
    if letter in "aeiou":
        count = count + 1
print("Vowels:", count)
✏️ LP3 — Fill in the Blank

Complete this so it prints numbers 1 to 5:

PYTHONex_lp3.py
for i in range(???, ???): print(i)
range(1, 6) — starts at 1, stops before 6, giving: 1, 2, 3, 4, 5.
📝 LP4 — Predict the Output

total = 0
for n in [2, 4, 6]:
    total = total + n
print(total)

A 6
B 246
C 12
D 0
Loop: total = 0+2 = 2, then 2+4 = 6, then 6+6 = 12. Final: 12.
LP5Find the Largest

Given numbers = [34, 78, 12, 95, 56]. Use a loop to find and print the largest number. (Don't use the built-in max() function — do it manually with a loop and an if statement.)

numbers = [34, 78, 12, 95, 56]
biggest = numbers[0]
for n in numbers:
    if n > biggest:
        biggest = n
print("Largest:", biggest)

🐛 Debug Exercises

🐛 LPD1 — IndentationError
PYTHONlpd1.py
for i in range(3): print(i)
IndentationError. The print must be indented inside the for block. Fix:     print(i)
🐛 LPD2 — Infinite Loop

Warning: this will run forever. Press Ctrl + C to stop it!

PYTHONlpd2.py
count = 0 while count < 5: print(count)
Infinite loop. count never changes — it's always 0, so count < 5 is always True. Fix: add count = count + 1 inside the loop (indented).
🐛 LPD3 — Off-by-One

Expected: print 1 to 10. Actual: prints 1 to 9.

PYTHONlpd3.py
for i in range(1, 10): print(i)
Off-by-one error. range(1, 10) goes 1 through 9 (stops before 10). Fix: range(1, 11) to include 10.
🐛 LPD4 — SyntaxError
PYTHONlpd4.py
names = ["Alice", "Bob"] for name in names print("Hi,", name)
SyntaxError — missing colon. Fix: for name in names: (add : at the end).
🐛 LPD5 — Logic Bug

Expected: print the sum of all numbers. Actual: prints only the last number.

PYTHONlpd5.py
numbers = [5, 10, 15] for n in numbers: total = n print("Sum:", total)
Logic bug. total = n replaces total with n each time instead of adding to it. Also, total needs to be initialized before the loop. Fix: add total = 0 before the loop, and change line 3 to total = total + n.

Completion Checklist

🎯 I Can Now…

🏆

You've Unlocked the Core of Programming!

Conditionals, lists, and loops are the backbone of nearly every program ever written. A game? Loops + conditionals. A social media feed? Lists + loops. A chatbot? Conditionals + loops. You now have the tools to build real things. Next time we'll learn about functions — reusable blocks of code — and start building more complex projects.