Essential Functions from Python Modules

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.

math Module

The math module provides mathematical functions to perform operations like trigonometry, logarithms, and more.

Common Methods:

  • math.sqrt(x): Returns the square root of x.
import math
result = math.sqrt(16)  # Returns 4.0
print(result)
  • math.factorial(x): Returns the factorial of a number x.
import math
result = math.factorial(5)  # Returns 120
print(result)
  • math.ceil(x): Returns the smallest integer greater than or equal to x.
import math
result = math.ceil(2.3)  # Returns 3
print(result)
  • math.floor(x): Returns the largest integer less than or equal to x.
import math
result = math.floor(2.7)  # Returns 2
print(result)
  • math.pi: Constant representing the value of pi.
import math
print(math.pi)  # Returns 3.141592653589793

os Module

The os module provides functions for interacting with the operating system, such as file manipulation and process management.

Common Methods:

  • os.getcwd(): Returns the current working directory.
import os
print(os.getcwd())  # Returns the current working directory
  • os.listdir(path): Returns a list of files and directories in the specified path.
import os
print(os.listdir('.'))  # Returns a list of files in the current directory
  • os.mkdir(path): Creates a new directory at the specified path.
import os
os.mkdir('new_directory')  # Creates a directory named 'new_directory'
  • os.remove(path): Removes the file at the specified path.
import os
os.remove('file_to_delete.txt')  # Deletes the specified file
  • os.rename(src, dst): Renames a file or directory from src to dst.
import os
os.rename('old_name.txt', 'new_name.txt')  # Renames the file

datetime Module

The datetime module helps with manipulating dates and times.

Common Methods:

  • datetime.datetime.now(): Returns the current local date and time.
import datetime
now = datetime.datetime.now()
print(now)  # Returns the current date and time
  • datetime.datetime.strptime(date_string, format): Converts a string to a 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.datetime.strftime(format): Converts a 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
  • datetime.date.today(): Returns the current local date.
import datetime
today = datetime.date.today()
print(today)  # Returns the current date (YYYY-MM-DD)
  • datetime.timedelta(days, hours, minutes): Represents a duration (difference between two dates or times).
import datetime
delta = datetime.timedelta(days=5)
print(delta)  # Prints a timedelta of 5 days

random Module

The random module is used to generate random numbers and perform random operations.

Common Methods:

  • random.randint(a, b): Returns a random integer in the inclusive range [a, b].
import random
random_int = random.randint(1, 10)
print(random_int)  # Returns a random integer between 1 and 10
  • random.choice(sequence): Returns a random element from a non-empty sequence.
import random
colors = ['red', 'green', 'blue']
random_choice = random.choice(colors)
print(random_choice)  # Returns a random color from the list
  • random.random(): Returns a random floating-point number between 0.0 and 1.0.
import random
random_float = random.random()
print(random_float)  # Returns a random float between 0.0 and 1.0
  • random.shuffle(sequence): Shuffles the elements of a sequence in place.
import random
items = [1, 2, 3, 4, 5]
random.shuffle(items)
print(items)  # Shuffles the list
  • random.sample(sequence, k): Returns a list of 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

Important Notes

  • Always remember to import the necessary module before using the functions.
  • While using os.remove(), be cautious as it permanently deletes files.
  • The random module functions return different results each time they are called, so they are ideal for simulations, games, and testing.
  • The datetime module is extremely useful when working with time-based applications like logging, scheduling, and calculating time differences.
Task

Practice: Using Functions from Different Modules

Objective: Get hands-on experience using functions from the math, os, datetime, and random modules to solve real-world problems.

  1. Using the math Module:

    • Use 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)}")
    
    • Use 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)}")
    
  2. Using the os Module:

    • Use 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()}")
    
    • Use 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.")
    
  3. Using the datetime Module:

    • Get the current date and time using 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')}")
    
    • Convert a string to a 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}")
    
  4. Using the random Module:

    • Use 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}")
    
    • Use 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}")
    

Copyright © 2025 Devship. All rights reserved.

Made by imParth