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 Calculate the Square Root of a Number import math num = 16 print(“Square root of”, num, “is:”, math.sqrt(num)) Find the Greatest Common Divisor (GCD) num1, num2 = 48, 18 print(“GCD of 48 and 18:”, math.gcd(num1, num2)) Calculate the Power of a Number base, exponent = 2, 5 print(f”{base} raised to the power {exponent} is:”, math.pow(base, exponent)) Calculate the Cosine of an Angle (in radians) angle = math.radians(60) print(“Cosine of 60 degrees:”, math.cos(angle)) Calculate the Floor of a Number num = 5.67 print(“Floor value of 5.67:”, math.floor(num)) Calculate the Ceiling of a Number num = 5.67 print(“Ceiling value of 5.67:”, math.ceil(num)) Calculate the Factorial of a Number num = 5 print(“Factorial of 5:”, math.factorial(num)) Convert Degrees to Radians degrees = 180 print(“Radians for 180 degrees:”, math.radians(degrees)) Find the Absolute Value Using fabs() num = -10.5 print(“Absolute value of -10.5:”, math.fabs(num)) Calculate Logarithm of a Number num = 100 print(“Logarithm of 100 with base 10:”, math.log10(num)) random Module Programs Collection Generate a Random Integer Between Two Values import random print(“Random integer between 1 and 10:”, random.randint(1, 10)) Generate a Random Floating-Point Number Between 0 and 1 print(“Random float between 0 and 1:”, random.random()) Choose a Random Element from a List fruits = [“apple”, “banana”, “cherry”] print(“Random fruit:”, random.choice(fruits)) Generate a Random Even Number within a Range print(“Random even number between 0 and 10:”, random.randrange(0, 11, 2)) Shuffle a List Randomly numbers = [1, 2, 3, 4, 5] random.shuffle(numbers) print(“Shuffled list:”, numbers) Generate a Random Number within a Specified Range Using uniform() print(“Random float between 1 and 10:”, random.uniform(1, 10)) Simulate a Coin Toss result = “Heads” if random.randint(0, 1) == 1 else “Tails” print(“Coin toss result:”, result) Pick Multiple Random Elements from a List print(“Random sample of 2 elements:”, random.sample(fruits, 2)) Generate Random Number with Gaussian Distribution print(“Random number from Gaussian distribution:”, random.gauss(0, 1)) Generate a Secure Random Number print(“Secure random number:”, random.SystemRandom().randint(1, 100)) pickle Module Programs Collection 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) Load a List from a Pickled File with open(“data.pkl”, “rb”) as file: data = pickle.load(file) print(“Loaded data:”, data) Save a Dictionary to a File person = {“name”: “Alice”, “age”: 30} with open(“person.pkl”, “wb”) as file: pickle.dump(person, file) Load a Dictionary from a Pickled File with open(“person.pkl”, “rb”) as file: person = pickle.load(file) print(“Loaded dictionary:”, person) Pickle Multiple Objects to a File items = [1, “hello”, {“a”: 1, “b”: 2}] with open(“items.pkl”, “wb”) as file: pickle.dump(items, file) Load Multiple Objects from a Pickle File with open(“items.pkl”, “rb”) as file: items = pickle.load(file) print(“Loaded items:”, items) 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) 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) 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)) Check Pickle Version print(“Pickle protocol version:”, pickle.DEFAULT_PROTOCOL) csv Module Programs Collection 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) Read Data from a CSV File with open(“people.csv”, “r”) as file: reader = csv.reader(file) for row in reader: print(row) 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) 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) 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) 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) Read CSV with Custom Delimiter with open(“people_semicolon.csv”, “r”) as file: reader = csv.reader(file, delimiter=’;’) for row in reader: print(row) Write Single Row to a CSV with open(“single_row.csv”, “w”, newline=””) as file: writer = csv.writer(file) writer.writerow([“Alice”, 30]) 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)) 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])
Package-Based Functions (math, random, pickle, and csv) Read More »