Python Course — Day 5

Filling the Gaps

Today we slow down and deeply understand everything that felt confusing. By the end of this lesson, the foundations will feel rock-solid.

Lab Modules

Mastering print()

The print() function has one job: show something in the terminal. But there are many different ways to use it. Let's learn every single one.

TASK 1.1All the Ways to Use print()

Create print_mastery.py and type every line. Run it and study the output carefully.

PYTHONprint_mastery.py
# === WAY 1: Print a string literal (text in quotes) === print("Hello, World!") # Output: Hello, World! # === WAY 2: Print a number directly === print(42) # Output: 42 # === WAY 3: Print a variable === name = "Pooja" print(name) # Output: Pooja (prints the VALUE inside the variable, not the word "name") # === WAY 4: Print MULTIPLE things separated by commas === age = 20 print("Age:", age) # Output: Age: 20 (Python automatically adds a space between comma-separated items) print("Name:", name, "Age:", age) # Output: Name: Pooja Age: 20 # === WAY 5: Print a calculation === print(10 + 5) # Output: 15 (Python calculates first, then prints the result) print("Sum:", 10 + 5) # Output: Sum: 15 # === WAY 6: Print using string concatenation (+) === print("Hello, " + name + "!") # Output: Hello, Pooja! (NO spaces added - you control everything) # === WAY 7: Print an empty line === print() # Output: (just a blank line) # === WAY 8: Print the type of something === print(type(name)) # Output: <class 'str'>

💡 Comma vs Plus — The Key Difference

Comma (,)print("Age:", 20)Age: 20
Automatically adds a space. Can mix any types (strings, numbers, booleans). This is the easiest and safest way.

Plus (+)print("Age: " + str(20))Age: 20
No automatic space. ALL items MUST be strings (so you need str() to convert numbers). Gives you full control over formatting.
📝 Quiz

What does print("Result:", 3 + 4) output?

A Result:3 + 4
B Result:7
C Result: 7
D Error
Python first calculates 3 + 4 = 7. Then print shows both items separated by a space: Result: 7.

Booleans & All the Operators

We've used int, float, and str. There's a fourth essential type: bool (boolean). It can only be one of two values: True or False. This is the type Python uses every time it makes a decision in an if statement.

TASK 2.1Booleans — True and False

Create booleans.py:

PYTHONbooleans.py
# Boolean values — only two possibilities is_sunny = True is_raining = False print(is_sunny) # True print(type(is_sunny)) # <class 'bool'> # Comparisons PRODUCE booleans print(10 > 5) # True print(10 == 5) # False print(3 != 7) # True (3 is NOT equal to 7) print("hello" == "hello") # True print("Hello" == "hello") # False (capital H ≠ lowercase h)

Every if statement works by evaluating its condition to True or False. When you write if age >= 18:, Python computes age >= 18 which becomes either True or False. If True, the indented block runs. If False, it's skipped.

💡 = vs == — This Is CRITICAL

=   Assignment — stores a value: x = 10 means "put 10 into x"

==   Comparison — checks if equal: x == 10 means "is x equal to 10?" and returns True or False

If you accidentally write if x = 5: (one equals) instead of if x == 5: (two equals), you'll get a SyntaxError. Single = is never allowed inside an if condition.
TASK 2.2All Operators in One Place

Create operators_all.py:

PYTHONoperators_all.py
a = 15 b = 4 # --- ARITHMETIC OPERATORS (do math) --- print("a + b =", a + b) # Addition → 19 print("a - b =", a - b) # Subtraction → 11 print("a * b =", a * b) # Multiplication → 60 print("a / b =", a / b) # Division → 3.75 (always float) print("a // b =", a // b) # Floor division → 3 (drops decimal) print("a % b =", a % b) # Modulo → 3 (remainder) print("a ** 2 =", a ** 2) # Power → 225 (15 squared) print() # --- COMPARISON OPERATORS (produce True/False) --- print("a == b:", a == b) # Equal? → False print("a != b:", a != b) # Not equal? → True print("a > b :", a > b) # Greater? → True print("a < b :", a < b) # Less? → False print("a >= b:", a >= b) # Greater or equal? → True print("a <= b:", a <= b) # Less or equal? → False print() # --- LOGICAL OPERATORS (combine True/False) --- print(True and True) # True (both must be True) print(True and False) # False print(True or False) # True (at least one True) print(not True) # False (flips the value)
📝 Quiz

What is 17 % 5?

A 2
B 3
C 3.4
D 12
% gives the remainder. 17 ÷ 5 = 3 remainder 2. So 17 % 5 = 2.

Data Structures — Explicitly

Let's be very clear about the syntax for strings, lists, and sets. Every bracket and quote matters.

💡 Strings: Single Quotes vs Double Quotes

In Python, single quotes 'hello' and double quotes "hello" are exactly the same thing. Both create a string. Use whichever you like, but be consistent.

When to use one over the other:
If your text contains a single quote: use double quotes outside → "it's sunny"
If your text contains double quotes: use single quotes outside → 'She said "hello"'
This avoids confusion about where the string starts and ends.
TASK 3.1Strings — Quotes Hands-On
PYTHONquotes.py
# Both are identical strings a = "Hello" b = 'Hello' print(a == b) # True — they're the same! # Use double quotes when text has a single quote c = "It's a beautiful day" print(c) # Use single quotes when text has double quotes d = 'She said "wow"' print(d)

💡 Lists Use Square Brackets [ ]

A list is created with square brackets [ ] and items are separated by commas:
my_list = [item1, item2, item3]

numbers = [10, 20, 30] — a list of integers
names = ["Alice", "Bob"] — a list of strings
empty_list = [] — a list with nothing in it
mixed = [1, "hello", 3.14, True] — lists can mix types

You can also create a list from other things: list("hello")['h', 'e', 'l', 'l', 'o']

💡 Sets Use Curly Braces { }

A set is like a list, but with two special rules: no duplicates and no order.
my_set = {item1, item2, item3}

colors = {"red", "green", "blue"}
nums = {1, 2, 2, 3, 3, 3} → becomes {1, 2, 3} (duplicates removed!)
empty_set = set() — NOT {} (that creates an empty dictionary, a different type)

Use a set when you care about unique values. Example: finding all unique words in a text.
TASK 3.2List vs Set — See the Difference
PYTHONlist_vs_set.py
# LIST — keeps duplicates, keeps order, uses [ ] my_list = ["apple", "banana", "apple", "cherry"] print("List:", my_list) print("List length:", len(my_list)) # SET — removes duplicates, no fixed order, uses { } my_set = {"apple", "banana", "apple", "cherry"} print("Set:", my_set) print("Set length:", len(my_set)) # Convert between them unique_fruits = list(my_set) # set → list unique_check = set(my_list) # list → set (removes duplicates) print("Unique from list:", unique_check)
📝 Quiz

What does len({1, 2, 2, 3, 3, 3}) return?

A 6
B 3
C Error
D 1
A set removes duplicates: {1, 2, 2, 3, 3, 3} becomes {1, 2, 3} — that's 3 unique items.

Variables, Naming & Memory

Let's understand exactly what happens inside the computer when you create a variable, and the rules for naming them.

💡 What Actually Happens When You Write x = 10

Remember from Day 0: your computer has RAM (fast, temporary memory). When your Python program runs, it uses RAM to store its variables.

When you write x = 10:
1. Python finds a small empty spot in RAM
2. It stores the value 10 in that spot
3. It sticks a label called x on that spot, so you can find it later

A variable is essentially a name tag on a location in RAM. When you write print(x), Python looks up the label "x", goes to that RAM location, reads the value (10), and shows it on screen.
YOUR CODE x = 10 creates RAM (Memory) x 10 empty empty

💡 Variables Are Only Available AFTER the Line They're Created

Python reads your code top to bottom, one line at a time. A variable doesn't exist until the line that creates it has been executed. You cannot use a variable above the line where it was created.
TASK 4.1Step-by-Step Execution

Create step_by_step.py. Before running, trace through it yourself line by line on paper:

PYTHONstep_by_step.py
1 a = 5 # Line 1: RAM → a = 5 2 b = 3 # Line 2: RAM → a = 5, b = 3 3 c = a + b # Line 3: c = 5 + 3 = 8. RAM → a=5, b=3, c=8 4 a = 10 # Line 4: a changes to 10. RAM → a=10, b=3, c=8 5 print(a, b, c) # Line 5: prints 10 3 8 # NOTE: c is still 8, NOT 13! c was calculated when a was 5. # Changing a later does NOT automatically update c.

💡 Variable Naming Rules

ALLOWED:
name age student_name score1 _private myVar

NOT ALLOWED:
1name — cannot start with a number
my name — cannot have spaces (use my_name instead)
my-name — hyphens not allowed (use underscores)
class for if print — these are Python keywords/built-ins, don't use them as variable names

CASE SENSITIVE: Name, name, and NAME are three completely different variables.
⚠️ Never Name a Variable After a Built-in

If you write list = [1, 2, 3], you've just replaced the built-in list() function with your variable. Now list() won't work anymore in your program. Same for str = "hello", print = 5, type = "admin", etc. Always use descriptive names like my_list, user_type, etc.

📝 Quiz

Which of these is a VALID variable name?

A 2nd_place
B my name
C for
D student_score
2nd_place starts with a number. my name has a space. for is a Python keyword. Only student_score follows all the rules.

Understanding Loops & Conditionals Deeply

Let's break down the exact anatomy of a for loop and understand every single word in the syntax.

💡 Anatomy of for i in range(1, 6):

Let's label every single part:
for i in range ( 1 , 6 ) : KEYWORD VARIABLE(you choose this name) KEYWORD FUNCTION thatgenerates numbers start, stop(1 to 5, not 6) COLON: required!starts the block The variable i is just a name YOU pick. You could call it num, x, count, anything.

💡 What Happens Each Time the Loop Runs (Each "Iteration")

When you write for i in range(1, 6):, here's exactly what happens:

Iteration 1: i gets the value 1 → the indented code runs with i=1
Iteration 2: i gets the value 2 → the indented code runs with i=2
Iteration 3: i gets the value 3 → the indented code runs with i=3
Iteration 4: i gets the value 4 → the indented code runs with i=4
Iteration 5: i gets the value 5 → the indented code runs with i=5
Done! No more values → loop ends → Python continues with the code after the loop.

The variable i is automatically updated every time the loop goes around. You don't need to change it yourself — the for loop does that for you.
TASK 5.1Watch i Change Each Iteration
PYTHONwatch_i.py
for i in range(1, 6): print("i is now:", i) print("Loop finished!") print() # The variable name doesn't have to be "i"! for fruit in ["apple", "banana", "cherry"]: print("fruit is now:", fruit)
Output
i is now: 1 i is now: 2 i is now: 3 i is now: 4 i is now: 5 Loop finished! fruit is now: apple fruit is now: banana fruit is now: cherry

💡 What Can Go Inside an if Condition?

The if condition can be anything that Python can evaluate to True or False:

if True: — always runs
if False: — never runs
if x > 5: — runs if the comparison is True
if name == "Pooja": — runs if name equals "Pooja"
if x: — runs if x is "truthy" (non-zero number, non-empty string)
if "hello": — runs! (non-empty string = True)
if "": — does NOT run (empty string = False)
if 0: — does NOT run (zero = False)
if 42: — runs! (any non-zero number = True)
if my_list: — runs if the list is not empty

Falsy values (treated as False): False, 0, 0.0, "", [], None
Everything else is Truthy (treated as True).
📝 Quiz

In for num in [10, 20, 30]:, which is the keyword and which is the variable?

A for=variable, in=variable, num=keyword
B for=keyword, num=keyword, in=keyword
C for=keyword, in=keyword, num=variable
D They're all keywords
for and in are Python keywords (built into the language — you can't change them). num is a variable name that YOU chose. It gets a new value from the list on each iteration.

The Complete Python Error Guide

Here is every common error you'll encounter, what it means, and exactly how to fix it. Create a file for each debug exercise, run it, and fix it.

1. SyntaxError

Python's grammar rule was broken — it can't even begin to understand the code.

🐛 Debug E1 — Missing quotes
PYTHONe1.py
msg = "Hello World print(msg)
Missing closing quote on line 1. Fix: msg = "Hello World"
🐛 Debug E1b — Missing colon
PYTHONe1b.py
if 5 > 3 print("yes")
Missing : at end of the if line. Fix: if 5 > 3:

2. IndentationError

The code inside a block (if, for, etc.) isn't indented, or the indentation is inconsistent.

🐛 Debug E2
PYTHONe2.py
for i in range(3): print(i) print("done")
Line 2 has no indentation, line 3 has indentation — inconsistent. Fix: indent line 2 with 4 spaces:     print(i)

3. NameError

You used a variable name that Python doesn't recognize — it was never created, or it's misspelled.

🐛 Debug E3
PYTHONe3.py
user_name = "Pooja" print("Hello,", User_name)
User_name (capital U) doesn't exist — only user_name (lowercase u) does. Python is case-sensitive. Fix: print("Hello,", user_name)

4. TypeError

You tried to do an operation with incompatible types (like adding a string and a number).

🐛 Debug E4
PYTHONe4.py
age = 25 print("I am " + age + " years old")
Can't + string and int. Fix: print("I am " + str(age) + " years old") or use comma: print("I am", age, "years old")

5. ValueError

The type is right but the value is wrong — like trying to convert non-numeric text to a number.

🐛 Debug E5
PYTHONe5.py
num = int("hello") print(num)
int("hello") fails because "hello" isn't a number. int() only works on numeric strings like int("42"). Fix depends on intent — if you want 0, use a try/except or check the value first.

6. IndexError

You tried to access a list position that doesn't exist.

🐛 Debug E6
PYTHONe6.py
items = ["a", "b", "c"] print(items[3])
List has 3 items at indices 0, 1, 2. Index 3 doesn't exist. Fix: items[2] for last item, or items[-1].

7. KeyError

You tried to access a dictionary key that doesn't exist. (We haven't covered dictionaries yet, but you should know this error.)

🐛 Debug E7
PYTHONe7.py
person = {"name": "Pooja", "age": 20} print(person["email"])
The key "email" doesn't exist in the dictionary. Only "name" and "age" exist. Fix: use an existing key or add the key first: person["email"] = "pooja@mail.com"

8. AttributeError

You tried to use a method that doesn't exist on that type.

🐛 Debug E8
PYTHONe8.py
x = 42 print(x.append(5))
.append() is a list method. x is an integer — integers don't have .append(). Fix: if you want a list, use x = [42] then x.append(5).

9. Logical Error (no crash!)

The code runs fine but gives the WRONG answer. The hardest type to find.

🐛 Debug E9 — Expected: average of 10, 20, 30 = 20.0
PYTHONe9.py
avg = 10 + 20 + 30 / 3 print("Average:", avg)
Division happens before addition (order of operations). 10 + 20 + (30/3) = 40.0, not 20.0. Fix: avg = (10 + 20 + 30) / 3

10. Input Type Error (very common!)

input() ALWAYS returns a string. If you do math on it without converting, you get wrong results or errors.

🐛 Debug E10 — Enter 5, expect 10, but get "55"
PYTHONe10.py
num = input("Number: ") doubled = num * 2 print(doubled)
input() returns "5" (string). "5" * 2 = "55" (string repetition). Fix: num = int(input("Number: "))

11. Infinite Loop

A while loop whose condition never becomes False. Press Ctrl+C to stop it.

🐛 Debug E11
PYTHONe11.py
x = 1 while x < 10: print(x)
x never changes, so x < 10 is always True. Fix: add x = x + 1 inside the loop.

12. Missing Parentheses

In Python 3, print is a function and MUST use parentheses.

🐛 Debug E12
PYTHONe12.py
print "Hello"
SyntaxError. In Python 3, print is a function — parentheses are required. Fix: print("Hello")

13. Overwriting Built-in Names

Using a built-in name as a variable destroys the built-in functionality.

🐛 Debug E13
PYTHONe13.py
list = [1, 2, 3] numbers = list(range(5)) print(numbers)
TypeError: 'list' object is not callable. Line 1 overwrote the built-in list() function with a variable. Now list(range(5)) tries to "call" your variable as a function. Fix: rename the variable: my_list = [1, 2, 3]

Pattern Printing — Thinking Like a Programmer

Patterns teach you to see the math hidden inside repetition. This is how programmers think: find the pattern, express it as a formula, and let a loop do the work.

TASK 7.1Step 1 — Print It the Hard Way First

Let's print this pattern. First, do it with individual print statements:

* ** *** **** *****
PYTHONpattern_hard.py
print("*") print("**") print("***") print("****") print("*****")

This works, but imagine printing 100 rows. There must be a better way. Let's find the pattern.

TASK 7.2Step 2 — Find the Pattern

Look at each row and count the stars:

📖 The Pattern Table

Row 1 → 1 star → "*" * 1
Row 2 → 2 stars → "*" * 2
Row 3 → 3 stars → "*" * 3
Row 4 → 4 stars → "*" * 4
Row 5 → 5 stars → "*" * 5

The pattern: Row number i has exactly i stars. The formula is simply: "*" * i
And i goes from 1 to 5. That's a loop!
TASK 7.3Step 3 — Use a Loop + Formula
PYTHONpattern_loop.py
for i in range(1, 6): print("*" * i)

Just 2 lines! And you can change 6 to 101 to print 100 rows. The loop + formula approach is infinitely scalable.

TASK 7.4Solved Example — Right-Aligned Triangle

Now let's do a harder pattern with spaces:

* ** *** **** *****

📖 Find the Formula

Total width = 5. For each row i (1 to 5):
Spaces = 5 - i    Stars = i

Row 1: 4 spaces, 1 star → " " * 4 + "*" * 1
Row 2: 3 spaces, 2 stars → " " * 3 + "*" * 2
Row 3: 2 spaces, 3 stars → " " * 2 + "*" * 3
Row 4: 1 space, 4 stars → " " * 1 + "*" * 4
Row 5: 0 spaces, 5 stars → " " * 0 + "*" * 5
PYTHONpattern_right.py
n = 5 for i in range(1, n + 1): spaces = " " * (n - i) stars = "*" * i print(spaces + stars)
TASK 7.5Your Turn — Print This Pyramid
* *** ***** ******* *********

Hints: For 5 rows, total width is 9 (2*5-1). For row i (1 to 5): Stars = 2*i - 1. Spaces = 5 - i. Use the same approach as the solved example above. Try for 3 minutes before revealing the answer!

n = 5
for i in range(1, n + 1):
    spaces = " " * (n - i)
    stars = "*" * (2 * i - 1)
    print(spaces + stars)
🧠

This Is How Programmers Think

The process is always the same: see the pattern → find the formula → write the loop. This skill transfers to everything in programming — not just star patterns.


Completion Checklist

🎯 I Can Now…

🏆

Your Foundations Are Now Rock-Solid!

Every concept that felt confusing should now feel clear. You understand not just what to type, but why it works. This deep understanding is what separates someone who can code from someone who just copies code. You're becoming a real programmer.