Package-Based Functions (math, random, pickle, and csv)

Package-Based Functions (math, random, pickle, and csv)

The next topic is Package-Based Functions for the following modules: math, random, pickle, and csv. Each module will have 10 programs showcasing some commonly used functions.


math Module Programs Collection

  1. Calculate the Square Root of a Number
    import math
    num = 16
    print("Square root of", num, "is:", math.sqrt(num))
    
  2. Find the Greatest Common Divisor (GCD)
    num1, num2 = 48, 18
    print("GCD of 48 and 18:", math.gcd(num1, num2))
    
  3. Calculate the Power of a Number
    base, exponent = 2, 5
    print(f"{base} raised to the power {exponent} is:", math.pow(base, exponent))
    
  4. Calculate the Cosine of an Angle (in radians)
    angle = math.radians(60)
    print("Cosine of 60 degrees:", math.cos(angle))
    
  5. Calculate the Floor of a Number
    num = 5.67
    print("Floor value of 5.67:", math.floor(num))
    
  6. Calculate the Ceiling of a Number
    num = 5.67
    print("Ceiling value of 5.67:", math.ceil(num))
    
  7. Calculate the Factorial of a Number
    num = 5
    print("Factorial of 5:", math.factorial(num))
    
  8. Convert Degrees to Radians
    degrees = 180
    print("Radians for 180 degrees:", math.radians(degrees))
    
  9. Find the Absolute Value Using fabs()
    num = -10.5
    print("Absolute value of -10.5:", math.fabs(num))
    
  10. Calculate Logarithm of a Number
    num = 100
    print("Logarithm of 100 with base 10:", math.log10(num))
    

random Module Programs Collection

  1. Generate a Random Integer Between Two Values
    import random
    print("Random integer between 1 and 10:", random.randint(1, 10))
    
  2. Generate a Random Floating-Point Number Between 0 and 1
    print("Random float between 0 and 1:", random.random())
    
  3. Choose a Random Element from a List
    fruits = ["apple", "banana", "cherry"]
    print("Random fruit:", random.choice(fruits))
    
  4. Generate a Random Even Number within a Range
    print("Random even number between 0 and 10:", random.randrange(0, 11, 2))
    
  5. Shuffle a List Randomly
    numbers = [1, 2, 3, 4, 5]
    random.shuffle(numbers)
    print("Shuffled list:", numbers)
    
  6. Generate a Random Number within a Specified Range Using uniform()
    print("Random float between 1 and 10:", random.uniform(1, 10))
    
  7. Simulate a Coin Toss
    result = "Heads" if random.randint(0, 1) == 1 else "Tails"
    print("Coin toss result:", result)
    
  8. Pick Multiple Random Elements from a List
    print("Random sample of 2 elements:", random.sample(fruits, 2))
    
  9. Generate Random Number with Gaussian Distribution
    print("Random number from Gaussian distribution:", random.gauss(0, 1))
    
  10. Generate a Secure Random Number
    print("Secure random number:", random.SystemRandom().randint(1, 100))
    

pickle Module Programs Collection

  1. Save a List to a File Using Pickle
    import pickle
    data = [1, 2, 3, 4, 5]
    with open("data.pkl", "wb") as file:
        pickle.dump(data, file)
    
  2. Load a List from a Pickled File
    with open("data.pkl", "rb") as file:
        data = pickle.load(file)
        print("Loaded data:", data)
    
  3. Save a Dictionary to a File
    person = {"name": "Alice", "age": 30}
    with open("person.pkl", "wb") as file:
        pickle.dump(person, file)
    
  4. Load a Dictionary from a Pickled File
    with open("person.pkl", "rb") as file:
        person = pickle.load(file)
        print("Loaded dictionary:", person)
    
  5. Pickle Multiple Objects to a File
    items = [1, "hello", {"a": 1, "b": 2}]
    with open("items.pkl", "wb") as file:
        pickle.dump(items, file)
    
  6. Load Multiple Objects from a Pickle File
    with open("items.pkl", "rb") as file:
        items = pickle.load(file)
        print("Loaded items:", items)
    
  7. Pickle an Object with a Custom Class
    class Person:
        def __init__(self, name, age):
            self.name = name
            self.age = age
    with open("custom.pkl", "wb") as file:
        pickle.dump(Person("Alice", 30), file)
    
  8. Unpickle an Object with a Custom Class
    with open("custom.pkl", "rb") as file:
        person = pickle.load(file)
        print("Loaded person:", person.name, person.age)
    
  9. Pickle and Unpickle Lists Using pickle.dumps() and pickle.loads()
    data = pickle.dumps([1, 2, 3])
    print("Serialized data:", data)
    print("Deserialized data:", pickle.loads(data))
    
  10. Check Pickle Version
    print("Pickle protocol version:", pickle.DEFAULT_PROTOCOL)
    

csv Module Programs Collection

  1. Write a List to a CSV File
    import csv
    data = [["Name", "Age"], ["Alice", 30], ["Bob", 25]]
    with open("people.csv", "w", newline="") as file:
        writer = csv.writer(file)
        writer.writerows(data)
    
  2. Read Data from a CSV File
    with open("people.csv", "r") as file:
        reader = csv.reader(file)
        for row in reader:
            print(row)
    
  3. Write a Dictionary to a CSV File
    data = [{"Name": "Alice", "Age": 30}, {"Name": "Bob", "Age": 25}]
    with open("people_dict.csv", "w", newline="") as file:
        writer = csv.DictWriter(file, fieldnames=["Name", "Age"])
        writer.writeheader()
        writer.writerows(data)
    
  4. Read Data from a CSV File as Dictionary
    with open("people_dict.csv", "r") as file:
        reader = csv.DictReader(file)
        for row in reader:
            print(row)
    
  5. Append Rows to an Existing CSV File
    new_data = [["Charlie", 35], ["Daisy", 40]]
    with open("people.csv", "a", newline="") as file:
        writer = csv.writer(file)
        writer.writerows(new_data)
    
  6. Write Data with Custom Delimiter
    data = [["Name", "Age"], ["Alice", 30], ["Bob", 25]]
    with open("people_semicolon.csv", "w", newline="") as file:
        writer = csv.writer(file, delimiter=';')
        writer.writerows(data)
    
  7. Read CSV with Custom Delimiter
    with open("people_semicolon.csv", "r") as file:
        reader = csv.reader(file, delimiter=';')
        for row in reader:
            print(row)
    
  8. Write Single Row to a CSV
    with open("single_row.csv", "w", newline="") as file:
        writer = csv.writer(file)
        writer.writerow(["Alice", 30])
    
  9. Check Number of Rows in a CSV
    with open("people.csv", "r") as file:
        reader = csv.reader(file)
        rows = list(reader)
        print("Number of rows:", len(rows))
    
  10. Read Only Specific Columns from a CSV
    with open("people.csv", "r") as file:
        reader = csv.reader(file)
        for row in reader:
            print("Name:",row[0])
    

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top
Contact Form Demo