Python Modules

1) Import Built-in Module

Import the math module and print the value of Ο€ (math.pi).


2) Using math Functions

Import math and use sqrt() to compute the square root of a number entered by the user.


3) Alias a Module

Import math as m and use it to compute cos(0).


4) Import Specific Function

From math, import only factorial and use it to compute factorial of a number.


5) Random Number Generation

Import the random module and print a random integer between 1 and 10.


6) Random Choice

Ask the user to input 5 items separated by spaces; use random.choice() to pick one at random.


7) Module from Standard Library

Import the datetime module and print the current date.


8) Time Module

Import time and print the current timestamp using time.time().


9) Help on Module

Use help() to print documentation for math.sqrt.

(This can be run interactively.)


10) Create Your Own Module

Create a file mymath.py with a function add(a, b) that returns the sum. Then import and use it.


11) Multiple Function Module

Extend mymath.py to also include multiply(a, b) and use both functions in another file.


12) Module with Default Argument

In your module, write greet(name, msg="Hello") and use it.


13) Import All Functions

Use:

and call both functions without module prefix.


14) Nested Module Call

In a second file, import your own module twice (alias one import) and call its functions.


15) Circular Import (Understanding Scope)

Create two modules that import each other; run and observe the error.

(This helps understand import behavior.)


16) Use os Module

Import the os module and print the current working directory using os.getcwd().


17) Use math with Loops

Use math.ceil() and math.floor() on a list of decimals.


18) Random Shuffle

Ask user for a list of 5 items and shuffle them using random.shuffle().


19) Module with Global Variables

In your custom module, define a variable VERSION = 1. Import it and print it.


20) Module Reload

Use the importlib.reload() function to reload your own module after changing it.


πŸ“ Concepts Covered

Concept
What You Practice

Importing Modules

import math

Aliasing

import math as m

From-Import

from math import sqrt

Built-in Modules

random, time, datetime, os

Custom Modules

Create & use your own .py

Reloading Modules

Using importlib.reload()


πŸ“Œ Example Template

Using math

Simple mymath.py Module


canvil: 333f6c7d-6876-4f7e-b6ad-1bdb2233f5c1

Last updated