Python Course — Day 7

Files, Modules & The Real World

Today you'll learn to read and write files, organize code into multiple files, install packages other developers wrote, and manage project environments like a professional.

Lab Modules

📌 Setup

VS Code → H:\Pooja → create day7 → terminal → cd H:\Pooja\day7

Deep Recap — Functions & Dicts

Before we move forward, let's make two of the most important concepts rock-solid.

💡 Functions Have Two Parts: Definition and Call

1. Definition — creating the recipe (def). This does NOT run the code inside.
2. Call — using the recipe (writing the function name with parentheses). This RUNS the code.

A function is a mini-program inside your program. It takes input (parameters), does processing (the body), and gives output (return). Just like your whole program follows Input → Process → Output, each function does the same thing on a smaller scale.
TASK 1.1Function Recap — Definition vs Call
PYTHONfunc_recap.py
# DEFINITION — this creates the function, does NOT run it yet def calculate_tax(price, rate=0.1): tax = price * rate total = price + tax return total # CALL — this runs the function and gets the result result = calculate_tax(100) # uses default rate 0.1 print("Total:", result) # 110.0 result2 = calculate_tax(200, 0.18) # custom rate print("Total:", result2) # 236.0

💡 Variable Scope — Where Does a Variable Live?

Not all variables are the same. Where you create a variable determines where it can be used. This is called scope. There are two kinds of variables based on where they are created:
🏠 Real-World Analogy

Think of a house with rooms. Items placed in the living room (the main area) can be seen by everyone — that's a global variable. Items placed inside a bedroom (a function) are private to that room — those are local variables. When you leave the bedroom (the function finishes), everything in that room disappears. But the living room items stay.

💡 Local Variables — Created Inside a Function

A variable created inside a function is called a local variable. It only exists while the function is running. Once the function finishes, the variable is gone — destroyed. No code outside the function can see it or use it. Parameters (the inputs in the parentheses) are also local variables.

💡 Global Variables — Created Outside All Functions

A variable created outside any function (at the "top level" of your file) is called a global variable. It exists for the entire lifetime of the program. Functions CAN read global variables (look at them), but they cannot change them by default.
TASK 1.2See Local vs Global in Action

Create scope_demo.py. Read the comments carefully, then run it:

PYTHONscope_demo.py
# --- GLOBAL VARIABLE (created outside any function) --- greeting = "Hello" # this lives for the whole program def my_function(): # --- LOCAL VARIABLE (created inside a function) --- secret = "I am local" # only exists inside this function print(greeting) # CAN read global variable — OK print(secret) # CAN use local variable — OK my_function() print(greeting) # CAN use global — OK # print(secret) # CANNOT use local from outside — NameError! # Uncomment the line above to see the error yourself.
Output
Hello I am local Hello
  1. Run the code as-is and see the output.
  2. Now uncomment the print(secret) line (remove the #). Save and run again. You'll get: NameError: name 'secret' is not defined. This proves secret only exists inside the function.
  3. Comment it back to fix the error.
TASK 1.3Parameters Are Local Too
PYTHONscope_params.py
def double(number): # 'number' is local to this function result = number * 2 # 'result' is also local return result answer = double(5) # answer = 10, this is global print(answer) # 10 — works fine, 'answer' is global # print(number) # NameError — 'number' was local to double() # print(result) # NameError — 'result' was local to double()

The parameter number and the variable result inside double() are both local. They're born when the function starts, and they die when the function ends. But the return value gets sent back and stored in answer, which is global.

📝 Quiz — Scope

What happens when you try to use a local variable outside its function?

A It prints None
B It prints 0
C NameError — Python doesn't know that variable exists
D It works normally
Local variables are destroyed when the function finishes. Trying to access them outside gives NameError because Python has no record of that name anymore.

💡 Can a Function Modify a Global Variable?

By default, no. A function can read a global variable but cannot change it. If you try to assign to a global name inside a function, Python creates a new local variable with the same name instead — it doesn't touch the global one.

Python does have a global keyword that lets you override this and modify the global variable from inside a function. But this is considered bad practice. Let's see both approaches:
TASK 1.4Modifying Global — Bad vs Good Approach
PYTHONglobal_vs_return.py
# ===== BAD APPROACH: using 'global' keyword ===== counter = 0 def increment_bad(): global counter # "I want to modify the GLOBAL counter" counter = counter + 1 increment_bad() print(counter) # 1 — it works, but HOW did counter change? Not obvious! # The problem: if you have 10 functions all using 'global counter', # any one of them could change it at any time. Finding bugs = nightmare. print() # ===== GOOD APPROACH: use parameters + return ===== def increment_good(value): return value + 1 counter = 0 counter = increment_good(counter) # CLEAR: counter goes in, new value comes out print(counter) # 1 — same result, but you can SEE exactly what's happening # Reading this line, you KNOW counter is being updated. No mystery.
⚠️ Rule of Thumb

Functions should get data IN through parameters and send data OUT through return. Avoid using the global keyword. If you see yourself needing it, rethink your design — almost always there's a cleaner way using parameters and return values. Professional programmers avoid global in nearly all cases.

📝 Quiz

Why is using global inside a function a bad practice?

A It causes a SyntaxError
B Any function can change the variable secretly, making bugs hard to find
C It makes the program slower
D Python doesn't support global variables
It works, but when any function can secretly modify a variable, tracing bugs becomes a nightmare. The good approach: pass values in through parameters and return values out — explicit and predictable.

💡 Dictionary Recap — A Realistic Example

Think of a car listing website. Each car has properties: brand, model, year, price. A dictionary is perfect for this:
TASK 1.5Dict of a Car, List of Dicts, List of Lists
PYTHONdata_patterns.py
# --- A single car as a dictionary --- car = {"brand": "Toyota", "model": "Corolla", "year": 2022, "price": 15000} print(car["brand"], car["model"]) # Toyota Corolla # --- A LIST OF DICTS (most common real-world pattern!) --- cars = [ {"brand": "Toyota", "model": "Corolla", "price": 15000}, {"brand": "Honda", "model": "Civic", "price": 18000}, {"brand": "Tesla", "model": "Model 3", "price": 35000}, ] print("\nAll cars:") for c in cars: print(c["brand"], c["model"], "- $" + str(c["price"])) # --- Compare: List of Lists (harder to understand) --- cars_list = [ ["Toyota", "Corolla", 15000], ["Honda", "Civic", 18000], ] # cars_list[0][2] = 15000... but WHAT is index 2? Price? Year? # With dicts: cars[0]["price"] = 15000 — much clearer!

💡 Looping Patterns — List vs Dict

These are the patterns you'll use hundreds of times:
TASK 1.6Looping Patterns
PYTHONloop_patterns.py
# --- LOOPING OVER A LIST --- fruits = ["apple", "banana", "cherry"] # Pattern 1: loop over items directly for fruit in fruits: print(fruit) # Pattern 2: loop with index for i in range(len(fruits)): print(i, "→", fruits[i]) print() # --- LOOPING OVER A DICTIONARY --- person = {"name": "Pooja", "age": 20, "city": "Mumbai"} # Pattern 1: loop over keys for key in person: print(key, "=", person[key]) # Pattern 2: loop over key-value pairs together for key, value in person.items(): print(key, "=", value) # Pattern 3: loop over values only for value in person.values(): print(value)
📝 Quiz

Why is using global inside a function a bad practice?

A It causes a SyntaxError
B Any function can change the variable secretly, making bugs hard to find
C It makes the program slower
D Python doesn't support global variables
It works, but when any function can secretly modify a variable, tracing bugs becomes a nightmare. Better to pass values in and return values out — explicit and predictable.

Understanding File Types

Programs don't just live in the terminal — they read and write files. Let's understand what kinds of files exist and how Python can work with them.

💡 Two Categories of Files

Text files — contain human-readable text. You can open them in Notepad and see the content. Examples: .txt, .csv, .py, .html, .json. Python can read these directly.

Binary files — contain data encoded in a way only specific programs understand. Opening them in Notepad shows gibberish. Examples: .jpg, .mp3, .mp4, .pdf, .xlsx. Python needs special libraries (third-party code) to work with these.

The key idea: all files can be read and written by Python. For text files, Python handles it natively. For binary files, you install a package (someone else's code) that knows how to interpret that format. We'll learn about packages in Module 5.
📝 Quiz

Which of these is a text file that Python can read directly?

A notes.csv
B photo.jpg
C song.mp3
D report.pdf
CSV files are plain text (comma-separated values). JPG, MP3, and PDF are binary formats that need special libraries.

Reading & Writing Text Files and CSVs

Let's learn to read and write the two most common text-based file types.

🏠 Real-World Analogy

Working with a file is like working with a physical notebook:
1. Open the notebook (open())
2. Read from it or Write to it
3. Close the notebook when done

Python uses the with open() pattern, which automatically closes the file for you — like a bookmark that closes the notebook when you walk away.

TASK 3.1Writing a Text File
PYTHONwrite_file.py
# "w" = write mode (creates the file, or overwrites if it exists) with open("notes.txt", "w") as file: file.write("Line 1: Hello from Python!\n") file.write("Line 2: I can write files!\n") file.write("Line 3: This is amazing.\n") print("File written! Check notes.txt in your folder.")

📖 Breaking Down Every Part

with — starts a "managed block" that auto-closes the file when done
open("notes.txt", "w") — opens (or creates) a file named "notes.txt" in write mode
as file — gives the opened file a variable name file (you choose this name)
: — starts the indented block (just like if and for)
file.write("text") — writes text to the file
\n — a special character meaning "new line" (like pressing Enter)
TASK 3.2Reading a Text File
PYTHONread_file.py
# "r" = read mode (default — just reads, doesn't change the file) with open("notes.txt", "r") as file: content = file.read() # reads the ENTIRE file as one string print(content) print("--- Line by line ---") # Reading line by line (more useful for processing) with open("notes.txt", "r") as file: for line in file: clean_line = line.strip() # remove \n from end print(">", clean_line)
TASK 3.3Useful Example — Word Counter
PYTHONword_count.py
with open("notes.txt", "r") as file: text = file.read() word_count = len(text.split()) # .split() breaks text into words char_count = len(text) line_count = text.count("\n") print("Words:", word_count) print("Characters:", char_count) print("Lines:", line_count)
TASK 3.4Working with CSV Files

CSV = Comma-Separated Values. It's the simplest format for tabular data (like a spreadsheet). First, create a CSV file:

PYTHONcsv_write.py
import csv # Write a CSV file with open("students.csv", "w", newline="") as file: writer = csv.writer(file) writer.writerow(["Name", "Age", "Grade"]) # header row writer.writerow(["Pooja", 20, "A"]) writer.writerow(["Alice", 22, "B"]) writer.writerow(["Bob", 19, "A"]) print("CSV written!")

Now read it back:

PYTHONcsv_read.py
import csv with open("students.csv", "r") as file: reader = csv.reader(file) for row in reader: print(row) # each row is a list: ["Pooja", "20", "A"]
🐛 Debug — FileNotFoundError
PYTHONdebug_file.py
with open("data.txt", "r") as f: print(f.read())
FileNotFoundError: data.txt doesn't exist. You must either create the file first, or check if it exists. Fix: create data.txt first, or use "w" mode to write before reading.

Modules & Imports — Splitting Code

As programs grow, putting everything in one file becomes messy. Modules let you split code into multiple files and reuse it.

💡 What Is a Module?

A module is just a .py file that contains functions, variables, or classes. When you write import csv, you're importing a module (a file called csv.py) that someone wrote. You can create your own modules too — any .py file can be imported by another .py file.
TASK 4.1Create Your Own Module

Create two files in your day7 folder:

PYTHONmy_helpers.py — file #1
# This file is a MODULE — it contains reusable functions def greet(name): return "Hello, " + name + "!" def add(a, b): return a + b PI = 3.14159
PYTHONmain.py — file #2
# This file USES the module import my_helpers print(my_helpers.greet("Pooja")) # Hello, Pooja! print(my_helpers.add(10, 5)) # 15 print(my_helpers.PI) # 3.14159
  1. Create both files. Run python main.py (not my_helpers.py).
  2. Notice: import my_helpers makes everything from my_helpers.py accessible with the my_helpers. prefix.
TASK 4.2Different Import Styles
PYTHONimport_styles.py
# Style 1: import the whole module import my_helpers print(my_helpers.greet("A")) # Style 2: import specific things (no prefix needed!) from my_helpers import greet, add print(greet("B")) # Style 3: import with a shorter nickname import my_helpers as mh print(mh.greet("C")) # Style 4: import everything (not recommended — pollutes namespace) from my_helpers import * print(greet("D"))

💡 Why Split Into Multiple Files?

1. Organization — keep related functions together (e.g., math_helpers.py, file_helpers.py)
2. Reusability — import the same module in many programs
3. Collaboration — different people can work on different files
4. Readability — smaller files are easier to understand
📝 Quiz

What does from math_utils import add do?

A Creates a file called math_utils.py
B Imports everything from math_utils
C Imports only the add function, usable as add() without prefix
D Runs the math_utils.py file
from X import Y brings just Y from module X into your code. You can use add() directly without writing math_utils.add().

Pip — Installing Packages

You've been using Python's built-in modules (random, csv). But there are hundreds of thousands of packages written by other programmers that you can download and use for free.

💡 What Is a Package?

A package is a collection of code that someone else wrote, tested, and shared for anyone to use. Instead of writing code to handle image processing from scratch, you install a package like Pillow that already does it. Packages are stored on PyPI (Python Package Index) — a website at pypi.org — like an app store for Python code.

pip is the command-line tool that downloads and installs packages from PyPI to your computer. It's like an app store you use from the terminal.
TASK 5.1Essential Pip Commands
PowerShell
# Check pip is installed PS> pip --version pip 24.0 from ... (python 3.12) # Install a package (example: requests — for making web requests) PS> pip install requests Downloading requests-2.31.0 ... Successfully installed requests-2.31.0 # See all installed packages PS> pip list Package Version ---------- ------- pip 24.0 requests 2.31.0 ... # Get info about a specific package PS> pip show requests # Uninstall a package PS> pip uninstall requests # Search for packages → go to https://pypi.org and search there
TASK 5.2Install and Use a Package
  1. In the terminal: pip install cowsay
  2. Create use_package.py:
PYTHONuse_package.py
import cowsay cowsay.cow("I was installed with pip!")
  1. Run: python use_package.py. You'll see a cow made of text characters saying your message!
  2. This package was written by someone else, uploaded to PyPI, and you installed it with one command. That's the power of pip.

💡 How to Find the Right Package

1. Go to pypi.org and search for what you need (e.g., "excel", "email", "image resize")
2. Look at the download count — popular packages are usually more reliable
3. Check the documentation — good packages have clear instructions
4. Install it with pip install package-name
5. Import it in your code and use it
📝 Quiz

What does pip install pandas do?

A Creates a file called pandas.py
B Opens the pandas website
C Runs a pandas program
D Downloads the pandas package from PyPI and installs it on your computer
pip install downloads code from PyPI (the Python Package Index) and installs it so you can import it in your programs.

Virtual Environments — Project Isolation

As a programmer, you'll work on multiple projects. Each project may need different packages or different versions. Virtual environments keep them separate so they don't conflict.

🏠 Real-World Analogy

Imagine you have three art projects. One needs oil paints, one needs watercolors, one needs colored pencils. If you dump all supplies into one box, it's chaos — and oil paint might ruin the watercolors. So you give each project its own supply box. That's a virtual environment — a separate, isolated set of packages for each project.

💡 Why Not Just Install Everything Globally?

Problem: Project A needs requests version 2.25. Project B needs requests version 2.31. If you install globally, only one version exists. One project breaks.

Solution: Each project gets its own virtual environment with its own packages. Project A's environment has version 2.25. Project B's has 2.31. They never interfere.
TASK 6.1Create a Virtual Environment
PowerShell
# Step 1: Make sure you're in your project folder PS> cd H:\Pooja\day7 # Step 2: Create a virtual environment called "venv" PS H:\Pooja\day7> python -m venv venv # This creates a folder called "venv" with its own Python + pip inside # Wait a few seconds... # Step 3: Check — a new "venv" folder appeared PS H:\Pooja\day7> ls venv Include Lib Scripts pyvenv.cfg

python -m venv venv means: "Python, run the venv module to create a virtual environment in a folder called venv." The folder name can be anything, but venv is the convention.

TASK 6.2Activate the Virtual Environment
PowerShell
# Activate the virtual environment PS H:\Pooja\day7> .\venv\Scripts\Activate # Notice: the prompt changes! It now shows (venv) at the start: (venv) PS H:\Pooja\day7> _ # Now any pip install goes ONLY into this virtual environment (venv) PS> pip install cowsay Successfully installed cowsay-6.1 # Check what's installed in THIS environment (venv) PS> pip list Package Version -------- ------- cowsay 6.1 pip 24.0

The (venv) in the prompt tells you the virtual environment is active. Everything you install now is private to this project.

TASK 6.3Run Your Code Inside the Environment
PowerShell
# With (venv) active, run your Python files normally: (venv) PS H:\Pooja\day7> python use_package.py _______________________________ | I was installed with pip! | =============================== \ \ ^__^ (oo)\_______ (__)\ )\/\ ||----w | || ||
TASK 6.4Deactivate and Switch Projects
PowerShell
# Deactivate the current environment (venv) PS H:\Pooja\day7> deactivate PS H:\Pooja\day7> _ # Notice: (venv) is gone. You're back to the global Python. # To work on a DIFFERENT project: PS> cd H:\Pooja\other_project PS H:\Pooja\other_project> .\venv\Scripts\Activate (venv) PS H:\Pooja\other_project> python main.py # Each project has its own venv folder with its own packages!
🌟 The Professional Workflow

1. Create a project folder
2. Create a virtual environment: python -m venv venv
3. Activate it: .\venv\Scripts\Activate
4. Install packages: pip install package-name
5. Write and run your code
6. When switching projects: deactivate → go to other project → activate its environment

This is exactly how professional Python developers work every day.

📝 Quiz

Why do we use virtual environments?

A They make Python run faster
B Different projects can have different package versions without conflicts
C They protect against viruses
D They're required to use Python
Virtual environments isolate each project's packages. Project A can use version 2.0 of a library while Project B uses version 3.0, without any conflict.
📝 Quiz

How do you know a virtual environment is active?

A The terminal turns green
B Python opens a special window
C The prompt shows (venv) at the beginning
D A notification pops up
When activated, the terminal prompt starts with (venv) — that's your visual indicator that you're working inside the virtual environment.

Completion Checklist

🎯 I Can Now…

🏆

You're Thinking Like a Professional!

You can now read files, organize code, install other people's code, and manage project environments. These aren't just "beginner" skills — this is the exact workflow professional developers use daily. You're building real-world capabilities.