Student Activity
Student Activity Guide:
1) Creating and Using Modules
Write a Python module that contains a simple function.
Import the module in another script and use the function.
Example Code:
my_module.py
def greet(name):
return f"Hello, {name}!"main.py
import my_module
print(my_module.greet("Alice"))Student Exercise: Create a module with multiple functions and import it in another script.
2) Importing and Using Built-in Modules
Explore Python's built-in modules like
mathandrandom.Use the
datetimemodule to display the current date and time.
Example Code:
import math
print(math.sqrt(16)) # Output: 4.0
import random
print(random.randint(1, 10)) # Random number between 1 and 10
from datetime import datetime
print(datetime.now())Student Exercise: Use the os module to list all files in a directory.
3) Structuring Python Projects with Packages
Create a package with multiple modules and use them.
Organize project files into logical directories.
Example Code:
project/
project/
├── mypackage/
│ ├── __init__.py
│ ├── module1.py
│ ├── module2.py
├── main.pymodule1.py
def function1():
return "Function from module1"module2.py
def function2():
return "Function from module2"main.py
from mypackage import module1, module2
print(module1.function1())
print(module2.function2())Student Exercise: Create a Python package with two modules and import functions from them.
4) Virtual Environments and Dependency Management
Set up a virtual environment using
venv.Install and manage dependencies using
pip.
Example Code:
# Create a virtual environment
python -m venv myenv
# Activate the virtual environment
# Windows:
myenv\Scripts\activate
# macOS/Linux:
source myenv/bin/activate
# Install dependencies
pip install requests numpy
# Freeze dependencies
pip freeze > requirements.txt
# Install dependencies from file
pip install -r requirements.txtStudent Exercise: Create a virtual environment, install some packages, and generate a requirements.txt file.
Last updated