Python
Python Course, Day 6

Dictionaries, Functions & Your First Game

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.

Lab Modules

📌 Setup

Open VS Code → H:\Pooja → create folder day6 → open terminal → cd H:\Pooja\day6

The Big Picture

Before learning new things, let's see everything we've built so far, like a map of your knowledge.

Your Python Knowledge Map INPUT input() OUTPUT print() DATA TYPES int float str bool list set VARIABLES name = value OPERATORS + - * / == > < CONDITIONALS if / elif / else LOOPS for / while TODAY WE ADD dict, Dictionaries tuple, None def, Functions Word Guessing Game!
📝 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].

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 pairs student = { "name": "Pooja", "age": 20, "city": "Mumbai", "is_enrolled": True } # Access a value by its KEY (not by index number!) print(student["name"]) # Pooja print(student["age"]) # 20 # Add a new key-value pair student["grade"] = "A" print(student) # Change an existing value student["age"] = 21 # Check if a key exists print("name" in student) # True print("email" in student) # False # How many key-value pairs? print("Total keys:", len(student)) # Loop through a dictionary for key in student: 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 dict classroom["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.

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 ( ):

colors = ("red", "green", "blue")
print(colors[0])"red", indexing works!
colors[0] = "yellow"TypeError! Can't modify.

Use tuples when you have data that should never change, like days of the week, coordinates, or RGB color values.

💡 None, The "Nothing" Value

None is a special value that means "no value" or "nothing here". It's its own type (NoneType).

result = None, "result doesn't have a value yet"
print(type(None))<class 'NoneType'>

You'll see None often with functions that don't return anything. For now, just know it exists and means "empty/nothing."
TASK 3.1Try Tuples and None
PYTHONother_types.py
# TUPLE days = ("Mon", "Tue", "Wed", "Thu", "Fri") print(days[0]) # Mon print(len(days)) # 5 print(type(days)) # <class 'tuple'> # days[0] = "Sunday" # Uncomment to see TypeError! # NONE answer = None print(answer) # None print(answer == None) # True (but prefer: answer is None) # Complete type summary: print(type(42)) # int print(type(3.14)) # float print(type("hi")) # str print(type(True)) # bool print(type([1,2])) # list print(type((1,2))) # tuple print(type({1,2})) # set print(type({"a":1})) # dict print(type(None)) # NoneType

Functions, Reusable Blocks of Code

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) def greet(): 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 input def greet(name): print("Hello, " + name + "!") # "Pooja" and "Alice" are ARGUMENTS, actual values you pass in greet("Pooja") # name becomes "Pooja" inside the function greet("Alice") # name becomes "Alice" inside the function # Multiple parameters def add(a, b): print(a + b) add(3, 5) # 8 add(10, 20) # 30
TASK 4.3Return Values, Getting Output from a Function
PYTHONfunc_return.py
# This function RETURNS a value instead of printing it def add(a, b): result = a + b return result # sends the value BACK to whoever called this function # Store the return value in a variable total = add(10, 5) print("Total:", total) # Total: 15 # Use the return value DIRECTLY in an expression print("Double:", add(10, 5) * 2) # Double: 30 # Use it inside an if condition if add(3, 4) > 5: print("Sum is greater than 5") # A function without return gives back None def say_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

print(secret), NameError! secret doesn't exist here.

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 calling def welcome(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 type x = int("25") # takes a string, returns an int s = input("? ") # takes a prompt, returns what user typed m = 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 end print(" ← 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
mystery prints 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:

PYTHONexercise
def total(numbers): result = 0 for n in numbers: result = result + n ??? result print(total([10, 20, 30]))
return, The blank is the return keyword. Without it, the function prints nothing meaningful and returns None.

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 --- def pick_word(): word = random.choice(words) return word

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 --- def create_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 order for i in range(num_revealed): pos = positions[i] hint[pos] = word[pos] # reveal the letter at this position return " ".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 --- def show_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 performance stats = { "correct": 0, "wrong": 0, "streak": 0, "best_streak": 0 } max_wrong_per_word = 3 # allowed wrong guesses per word playing = True # controls the main game loop while playing: # Pick a new word and create a hint secret = pick_word() hint = create_hint(secret) attempts = 0 solved = False print("Hint:", hint) print("(" + str(len(secret)) + " letters)") # Inner loop: keep guessing until solved or out of attempts while attempts < max_wrong_per_word and not solved: guess = input("Your guess: ").lower().strip() if guess == "quit": playing = False solved = True # exit inner loop too elif guess == secret: print("CORRECT!") stats["correct"] = stats["correct"] + 1 stats["streak"] = stats["streak"] + 1 if stats["streak"] > stats["best_streak"]: stats["best_streak"] = stats["streak"] solved = True else: attempts = attempts + 1 remaining = max_wrong_per_word - attempts print("Wrong!", remaining, "tries left.") # After inner loop, did they fail? if not solved and playing: print("Out of tries! The word was:", secret) stats["wrong"] = stats["wrong"] + 1 stats["streak"] = 0 # reset streak if playing: show_score(stats) print() # Game over print() 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: rocket CORRECT! --- Score --- Correct: 1 Wrong : 0 Streak : 1 -------------- Hint: p _ _ _ _ e (6 letters) Your guess: puzzle CORRECT! ...

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.


Completion Checklist

🎯 I Can Now…