Today you'll learn the most important data structure and the most important code organization tool. Then you'll use everything you've learned to build a real, playable word-guessing game.
Open VS Code → H:\Pooja → create folder day6 → open terminal → cd H:\Pooja\day6
Module 01
The Big Picture
Before learning new things, let's see everything we've built so far — like a map of your knowledge.
📝 Recap Quiz
Which of these is used to MAKE A DECISION in code?
A for loop
B print()
C if / elif / else
D input()
Conditionals (if/elif/else) make decisions. Loops repeat. print shows output. input gets user input.
📝 Recap Quiz
What is a list in Python?
A A single value stored in a variable
B An ordered collection of multiple values in square brackets [ ]
C A way to repeat code
D A type of loop
A list stores multiple values in order, created with [ ]. You access items by index like my_list[0].
Module 02
Dictionaries — The Most Powerful Data Type
A list stores items by position number (index 0, 1, 2...). A dictionary stores items by name (a key you choose). This is incredibly useful.
🏠 Real-World Analogy
Think of an actual dictionary book. You look up a word (the key) and find its definition (the value). You don't look up "word number 4,372" — you look up the actual word "python" and find what it means.
Or think of a contact list on your phone. You don't search by "contact #47" — you search by name ("Mom") and find the phone number. The name is the key, the phone number is the value.
💡 Why Not Just Use a List?
You could store contact info in lists: names = ["Mom", "Dad"] and phones = ["555-1234", "555-5678"]. But this is fragile — you have to keep both lists perfectly aligned. If you delete a name from one list but forget the other, everything breaks.
With a dictionary, each piece of data is connected: contacts = {"Mom": "555-1234", "Dad": "555-5678"}. The name and number are linked. You can add, delete, or look up by name directly. This is faster, safer, and easier to understand. Many real-world problems naturally fit this "look up by name" pattern.
TASK 2.1Creating and Using a Dictionary
Create dict_basics.py:
PYTHONdict_basics.py
# A dictionary uses curly braces { } with key: value pairsstudent= {
"name": "Pooja",
"age": 20,
"city": "Mumbai",
"is_enrolled": True
}
# Access a value by its KEY (not by index number!)print(student["name"]) # Poojaprint(student["age"]) # 20# Add a new key-value pairstudent["grade"] ="A"print(student)
# Change an existing valuestudent["age"] =21# Check if a key existsprint("name"instudent) # Trueprint("email"instudent) # False# How many key-value pairs?print("Total keys:", len(student))
# Loop through a dictionaryforkeyinstudent:
print(key, "→", student[key])
💡 Values Can Be ANY Type — Including Lists and Other Dicts!
This is what makes dictionaries so powerful. A value can be an int, str, bool, list, or even another dictionary.
TASK 2.2Dictionary with List Values
PYTHONdict_nested.py
classroom= {
"teacher": "Ms. Sharma",
"subject": "Python",
"students": ["Alice", "Bob", "Charlie"],
"room_number": 204
}
print("Teacher:", classroom["teacher"])
print("Students:", classroom["students"])
print("First student:", classroom["students"][0])
# Add a new student to the list inside the dictclassroom["students"].append("Diana")
print("Updated:", classroom["students"])
📝 Quiz
d = {"a": 1, "b": 2, "c": 3} What is d["b"]?
A "b"
B 1
C 3
D 2
The key "b" maps to the value 2.
Module 03
Other Data Types — Tuples & None
Two more types you'll encounter that we haven't explicitly covered yet.
💡 Tuple — A List That Cannot Be Changed
A tuple is exactly like a list, except you cannot modify it after creation. No adding, removing, or changing items. Created with parentheses ( ):
A function is a named, reusable block of code that takes some input, does something, and optionally gives back a result. You've been using functions since Day 1 — print(), input(), len(), type() are all functions. Now you'll learn to create your own.
🏠 Real-World Analogy
A function is like a kitchen appliance. A blender takes input (fruits), does some processing (blending), and gives you output (smoothie). You don't need to know how the motor works — you just put stuff in and get stuff out. You can use the same blender many times with different fruits. Similarly, you write a function once and use it many times with different inputs.
💡 Why Use Functions?
1. Avoid repeating code. If you calculate tax in 10 places, write a calculate_tax() function once and call it 10 times. If the formula changes, you fix it in one place.
2. Give names to chunks of code.calculate_tax(price) is easier to understand than 5 lines of math. Functions make code readable.
3. Break big problems into small pieces. Instead of 200 lines in a row, you have small named functions that each do one thing well.
TASK 4.1Your First Function
Create func_basics.py:
PYTHONfunc_basics.py
# DEFINING a function (creating the recipe)defgreet():
print("Hello!")
print("Welcome to Python.")
# CALLING the function (using the recipe)greet()
greet() # call it again — reusable!
Output
Hello!
Welcome to Python.
Hello!
Welcome to Python.
def means "define a new function." The indented lines are the function's body — they only run when you call the function with greet(). Defining a function does NOT run it.
TASK 4.2Functions with Arguments (Inputs)
PYTHONfunc_args.py
# 'name' is a PARAMETER — a placeholder for the inputdefgreet(name):
print("Hello, "+name+"!")
# "Pooja" and "Alice" are ARGUMENTS — actual values you pass ingreet("Pooja") # name becomes "Pooja" inside the functiongreet("Alice") # name becomes "Alice" inside the function# Multiple parametersdefadd(a, b):
print(a+b)
add(3, 5) # 8add(10, 20) # 30
TASK 4.3Return Values — Getting Output from a Function
PYTHONfunc_return.py
# This function RETURNS a value instead of printing itdefadd(a, b):
result=a+breturnresult# sends the value BACK to whoever called this function# Store the return value in a variabletotal=add(10, 5)
print("Total:", total) # Total: 15# Use the return value DIRECTLY in an expressionprint("Double:", add(10, 5) *2) # Double: 30# Use it inside an if conditionifadd(3, 4) >5:
print("Sum is greater than 5")
# A function without return gives back Nonedefsay_hi():
print("Hi!")
x=say_hi()
print(x) # None — say_hi doesn't return anything
💡 Scope — What's Accessible Where
Variables created inside a function only exist inside that function. They cannot be seen or used outside. This is called scope.
def my_func(): secret = 42 — this variable only exists inside my_func
Variables created outside functions (at the top level) are accessible everywhere. But variables inside a function are private to that function. This prevents accidental conflicts — two functions can both have a variable called x without interfering with each other.
TASK 4.4Default Parameter Values
PYTHONfunc_default.py
# 'greeting' has a default value — it's optional when callingdefwelcome(name, greeting="Hello"):
print(greeting+", "+name+"!")
welcome("Pooja") # Hello, Pooja!welcome("Pooja", "Good morning") # Good morning, Pooja!welcome("Alice", "Hi") # Hi, Alice!
TASK 4.5Functions You Already Know Are Functions!
PYTHONfunc_builtins.py
# All of these are FUNCTIONS — they take input and give output:print("hi") # takes arguments, prints them. Returns None.n=len([1,2,3]) # takes a list, returns its length (3)t=type(42) # takes a value, returns its typex=int("25") # takes a string, returns an ints=input("? ") # takes a prompt, returns what user typedm=max(5, 9, 2) # takes numbers, returns the biggest# print() with multiple arguments and separator:print("a", "b", "c", sep="-") # a-b-c (sep changes the separator)print("no newline", end="") # doesn't add a newline at the endprint(" ← same line")
📝 Quiz
What is the output? def double(x): return x * 2
result = double(7) print(result + 1)
A 14
B 15
C 8
D Error
double(7) returns 14. That's stored in result. Then 14 + 1 = 15.
📝 Quiz
def mystery(a, b): print(a + b)
x = mystery(3, 4) print(x)
What does the last print show?
A 7
B 34
C None
D Error
mysteryprints 7 (you'll see it on screen), but it doesn't have a return statement. So it returns None. x is None.
✏️ Exercise — Write a Function
Complete this function that takes a list of numbers and returns the sum:
return — The blank is the return keyword. Without it, the function prints nothing meaningful and returns None.
Module 05
Build a Word Guessing Game!
Time to use everything you've learned: variables, strings, lists, dictionaries, loops, conditionals, and functions — all in one program. We'll build it step by step. Create a single file called word_game.py and add each step to it.
📌 How This Works
For each step below, add the code to the BOTTOM of word_game.py (unless told otherwise). Don't create new files — everything goes in the same file, building up piece by piece. After each step, save and run to test what you have so far.
STEP 1 — Import and Word List
Open word_game.py and type this at the very top. This sets up the word list and the tool for picking random things.
PYTHONword_game.py — Step 1 (top of file)
import random
# --- WORD LIST ---words= ["python", "rocket", "galaxy", "jungle", "puzzle",
"breeze", "wizard", "frozen", "castle", "beyond"]
import random loads Python's built-in random module. words is a list of 10 words the game will pick from.
STEP 2 — Helper Function: Pick a Random Word
Add this directly below Step 1:
PYTHONword_game.py — Step 2 (below Step 1)
# --- FUNCTION: Pick a random word ---defpick_word():
word= random.choice(words)
returnword
random.choice(words) picks one random word from the list. The function returns it.
STEP 3 — Function: Create the Hint (Show Some Letters)
Add this below Step 2. This function takes the secret word and reveals a few random letters, hiding the rest with _.
PYTHONword_game.py — Step 3 (below Step 2)
# --- FUNCTION: Create hint with some letters revealed ---defcreate_hint(word, num_revealed=2):
hint= ["_"] *len(word) # start with all blanks: ["_", "_", "_", ...]positions=list(range(len(word))) # [0, 1, 2, 3, ...]
random.shuffle(positions) # randomize the orderforiinrange(num_revealed):
pos=positions[i]
hint[pos] =word[pos] # reveal the letter at this positionreturn" ".join(hint) # join list into string: "p _ t _ o _"
For a word like "python", this might create p _ _ h _ _ — two letters revealed, rest hidden.
STEP 4 — Function: Display the Scoreboard
Add this below Step 3:
PYTHONword_game.py — Step 4 (below Step 3)
# --- FUNCTION: Show the score ---defshow_score(stats):
print("--- Score ---")
print("Correct:", stats["correct"])
print("Wrong :", stats["wrong"])
print("Streak :", stats["streak"])
print("-"*14)
This function takes a dictionary with the player's stats and displays them. We're using a dict to keep all the score data organized.
STEP 5 — The Main Game Loop
This is the biggest step — the actual game! Add this below Step 4. Read the comments carefully — they explain every line.
PYTHONword_game.py — Step 5 (below Step 4)
# === MAIN GAME ===print("===============================")
print(" WORD GUESSING GAME")
print("===============================")
print("Guess the word from the hint!")
print("Type 'quit' to stop playing.")
print()
# Stats dictionary — tracks the player's performancestats= {
"correct": 0,
"wrong": 0,
"streak": 0,
"best_streak": 0
}
max_wrong_per_word=3# allowed wrong guesses per wordplaying=True# controls the main game loopwhileplaying:
# Pick a new word and create a hintsecret=pick_word()
hint=create_hint(secret)
attempts=0solved=Falseprint("Hint:", hint)
print("("+str(len(secret)) +" letters)")
# Inner loop: keep guessing until solved or out of attemptswhileattempts<max_wrong_per_wordandnotsolved:
guess=input("Your guess: ").lower().strip()
ifguess=="quit":
playing=Falsesolved=True# exit inner loop tooelifguess==secret:
print("CORRECT!")
stats["correct"] =stats["correct"] +1stats["streak"] =stats["streak"] +1ifstats["streak"] >stats["best_streak"]:
stats["best_streak"] =stats["streak"]
solved=Trueelse:
attempts=attempts+1remaining=max_wrong_per_word-attemptsprint("Wrong!", remaining, "tries left.")
# After inner loop — did they fail?ifnotsolvedandplaying:
print("Out of tries! The word was:", secret)
stats["wrong"] =stats["wrong"] +1stats["streak"] =0# reset streakifplaying:
show_score(stats)
print()
# Game overprint()
print("=== GAME OVER ===")
print("Words guessed:", stats["correct"])
print("Words missed :", stats["wrong"])
print("Best streak :", stats["best_streak"])
print("Thanks for playing!")
STEP 6 — Save and Play!
Save the file (Ctrl + S) and run it:
Playing the game
PS H:\Pooja\day6>python word_game.py===============================
WORD GUESSING GAME
===============================
Guess the word from the hint!
Type 'quit' to stop playing.
Hint: _ o _ _ e _
(6 letters)
Your guess: rocketCORRECT!
--- Score ---
Correct: 1
Wrong : 0
Streak : 1
--------------
Hint: p _ _ _ _ e
(6 letters)
Your guess: puzzleCORRECT!
...
Play several rounds! Try getting words right, try getting them wrong, see the streak counter work. Type quit to see the final score.
📖 What Concepts Did This Game Use?
Variables — secret, attempts, playing, solved Strings — .lower(), .strip(), .join(), + concatenation Lists — words list, hint list, indexing, range() Dictionary — stats dict storing score, accessing with ["key"] Booleans — playing, solved, True/False Conditionals — if/elif/else for checking guess, checking quit Loops — while for main game loop and inner guess loop Functions — pick_word(), create_hint(), show_score() Import — import random, random.choice(), random.shuffle()
🎮
You Built a Real Game!
This isn't a tutorial exercise — it's a real, playable game with scoring, streaks, and replayability. You built it using every concept from this course. You're a programmer now.