In Python, built-in modules provide a wide variety of functions that allow you to perform operations on numbers, handle files and directories, work with dates and times, and generate random data. Below is a breakdown of some of the most useful functions from the math
, os
, datetime
, and random
modules.
The math
module provides mathematical functions to perform operations like trigonometry, logarithms, and more.
x
.import math
result = math.sqrt(16) # Returns 4.0
print(result)
x
.import math
result = math.factorial(5) # Returns 120
print(result)
x
.import math
result = math.ceil(2.3) # Returns 3
print(result)
x
.import math
result = math.floor(2.7) # Returns 2
print(result)
import math
print(math.pi) # Returns 3.141592653589793
The os
module provides functions for interacting with the operating system, such as file manipulation and process management.
import os
print(os.getcwd()) # Returns the current working directory
import os
print(os.listdir('.')) # Returns a list of files in the current directory
import os
os.mkdir('new_directory') # Creates a directory named 'new_directory'
import os
os.remove('file_to_delete.txt') # Deletes the specified file
src
to dst
.import os
os.rename('old_name.txt', 'new_name.txt') # Renames the file
The datetime
module helps with manipulating dates and times.
import datetime
now = datetime.datetime.now()
print(now) # Returns the current date and time
datetime
object based on the provided format.import datetime
date_string = "2024-12-28"
date_object = datetime.datetime.strptime(date_string, "%Y-%m-%d")
print(date_object) # Converts the string to a datetime object
datetime
object to a string based on the specified format.import datetime
now = datetime.datetime.now()
formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")
print(formatted_date) # Formats the datetime object as a string
import datetime
today = datetime.date.today()
print(today) # Returns the current date (YYYY-MM-DD)
import datetime
delta = datetime.timedelta(days=5)
print(delta) # Prints a timedelta of 5 days
The random
module is used to generate random numbers and perform random operations.
[a, b]
.import random
random_int = random.randint(1, 10)
print(random_int) # Returns a random integer between 1 and 10
import random
colors = ['red', 'green', 'blue']
random_choice = random.choice(colors)
print(random_choice) # Returns a random color from the list
import random
random_float = random.random()
print(random_float) # Returns a random float between 0.0 and 1.0
import random
items = [1, 2, 3, 4, 5]
random.shuffle(items)
print(items) # Shuffles the list
k
unique elements chosen from the sequence.import random
sample = random.sample(range(1, 10), 3)
print(sample) # Returns 3 unique random numbers from the range 1-9
os.remove()
, be cautious as it permanently deletes files.random
module functions return different results each time they are called, so they are ideal for simulations, games, and testing.datetime
module is extremely useful when working with time-based applications like logging, scheduling, and calculating time differences.Objective: Get hands-on experience using functions from the math
, os
, datetime
, and random
modules to solve real-world problems.
Using the math
Module:
math.sqrt()
to calculate the square root of a number. Write a program that asks the user for a number and prints its square root.import math
number = float(input("Enter a number: "))
print(f"The square root of {number} is {math.sqrt(number)}")
math.factorial()
to compute the factorial of a number. Write a program to calculate the factorial of a number entered by the user.import math
num = int(input("Enter a number to calculate its factorial: "))
print(f"The factorial of {num} is {math.factorial(num)}")
Using the os
Module:
os.getcwd()
to print the current working directory. Write a program to display the path where the script is being run.import os
print(f"Current working directory: {os.getcwd()}")
os.rename()
to rename a file or directory. Write a program that renames a file from old_name.txt
to new_name.txt
.import os
os.rename("old_name.txt", "new_name.txt")
print("File renamed successfully.")
Using the datetime
Module:
datetime.datetime.now()
. Write a program to display the current date and time in a human-readable format.import datetime
now = datetime.datetime.now()
print(f"Current date and time: {now.strftime('%Y-%m-%d %H:%M:%S')}")
datetime
object using datetime.datetime.strptime()
. Write a program that converts a user-provided date string into a datetime
object and prints it.import datetime
date_str = input("Enter a date (YYYY-MM-DD): ")
date_obj = datetime.datetime.strptime(date_str, "%Y-%m-%d")
print(f"The datetime object is: {date_obj}")
Using the random
Module:
random.randint()
to generate a random integer between two numbers. Write a program to generate a random integer between 1 and 100.import random
random_num = random.randint(1, 100)
print(f"Random number between 1 and 100: {random_num}")
random.shuffle()
to shuffle a list of items. Write a program that shuffles a list of numbers and prints the shuffled list.import random
numbers = [1, 2, 3, 4, 5]
random.shuffle(numbers)
print(f"Shuffled list: {numbers}")