Python modules are files containing Python definitions and statements. They are used to organize code and avoid code duplication.
import math
result = math.sqrt(25)
print(result) # Output: 5.0
print(math.pi) # Output: 3.141592653589793
from math import sqrt
result = sqrt(16)
print(result) # Output: 4.0
Import only the needed function, reducing code clutter.
import math as m
result = m.cos(math.pi)
print(result) # Output: -1.0
from math import pi, cos, floor
print(pi)
print(cos(pi))
print(floor(3.14)) # Output: 3
Save the following code as `my_module.py`:
#my_module.py
def greet(name):
print(f"Hello, {name}!")
Then, in your main script:
import my_module
my_module.greet("Anam") # Output: Hello, Anam!
import random
random_number = random.randint(1, 10)
print(random_number)
random_choice = random.choice(["apple", "banana", "cherry"])
print(random_choice)
import datetime
current_time = datetime.datetime.now()
print(current_time)