Python Programming

Iterative Programs (For, While, Nested Loop)

Iterative Programs (For, While, Nested Loop)

The next topic is the For Loop. The for loop in Python is used to iterate over a sequence (like a list, tuple, dictionary, set, or string) or other iterable objects. This loop allows us to execute a block of code multiple times based on the length of the sequence or specified range. Below are 10 programs that demonstrate different uses of the For Loop in Python. For Loop Programs 1. Print Numbers from 1 to 10 Description: This program uses a for loop to print numbers from 1 to 10. # Program to print numbers from 1 to 10 for i in range(1, 11): print(i) 2. Print Even Numbers within a Range Description: Prints even numbers between 1 and 20 using a for loop with a step of 2. # Program to print even numbers from 1 to 20 for i in range(2, 21, 2): print(i) 3. Calculate the Sum of First N Natural Numbers Description: This program calculates the sum of the first n natural numbers. # Program to calculate the sum of first n natural numbers n = int(input("Enter a number: ")) sum_n = 0 for i in range(1, n + 1): sum_n += i print("Sum of first", n, "natural numbers is:", sum_n) 4. Display Multiplication Table Description: Displays the multiplication table of a number entered by the user. # Program to display the multiplication table num = int(input("Enter a number: ")) for i in range(1, 11): print(f"{num} x {i} = {num * i}") 5. Print Each Character of a String Description: Iterates over each character of a string and prints it on a new line. # Program to print each character of a string text = input("Enter a string: ") for char in text: print(char) 6. Find the Factorial of a Number Description: Computes the factorial of a number using a for loop. # Program to find the factorial of a number num = int(input("Enter a number: ")) factorial = 1 for i in range(1, num + 1): factorial *= i print("Factorial of", num, "is:", factorial) 7. Calculate the Sum of Elements in a List Description: This program calculates the sum of elements in a list using a for loop. # Program to calculate the sum of elements in a list numbers = [10, 20, 30, 40, 50] sum_numbers = 0 for num in numbers: sum_numbers += num print("Sum of list elements:", sum_numbers) 8. Display Only Positive Numbers from a List Description: Filters and displays only the positive numbers from a list of integers. # Program to display only positive numbers from a list numbers = [-10, 15, -30, 45, 0, 50] for num in numbers: if num > 0: print(num) 9. Print Fibonacci Series up to N Terms Description: Generates the Fibonacci series up to n terms. # Program to print Fibonacci series up to n terms n_terms = int(input("Enter the number of terms: ")) a, b = 0, 1 for i in range(n_terms): print(a, end=" ") a, b = b, a + b 10. Count Vowels in a String Description: Counts and displays the number of vowels in a given string. # Program to count vowels in a string text = input("Enter a string: ") vowels = "aeiouAEIOU" count = 0 for char in text: if char in vowels: count += 1 print("Number of vowels:", count) Explanation Each For Loop program showcases different ways to use for loops to iterate over numbers, lists, and strings. The for loop structure is versatile and allows us to perform various operations based on the elements or indexes of the sequence, which makes it essential for performing repeated tasks. The next topic is the While Loop. The while loop in Python repeatedly executes a block of code as long as the condition specified is True. This loop is useful when the number of iterations is not known beforehand, and we want the loop to continue until a certain condition is met. Below are 10 programs that demonstrate different uses of the While Loop in Python. While Loop Programs 1. Print Numbers from 1 to 10 Description: This program uses a while loop to print numbers from 1 to 10. # Program to print numbers from 1 to 10 using while loop i = 1 while i <= 10: print(i) i += 1 2. Sum of Natural Numbers Description: Calculates the sum of first n natural numbers using a while loop. # Program to calculate the sum of first n natural numbers using while loop n = int(input("Enter a number: ")) sum_n = 0 i = 1 while i <= n: sum_n += i i += 1 print("Sum of first", n, "natural numbers is:", sum_n) 3. Print Even Numbers Between 1 and 20 Description: Prints even numbers between 1 and 20 using a while loop. # Program to print even numbers from 1 to 20 using while loop i = 2 while i <= 20: print(i) i += 2 4. Reverse a Number Description: Reverses a number entered by the user using a while loop. # Program to reverse a number using while loop num = int(input("Enter a number: ")) reverse = 0 while num > 0: digit = num % 10 reverse = reverse * 10 + digit num = num // 10 print("Reversed number:", reverse) 5. Count Down from 10 to 1 Description: A countdown from 10 to 1 using a while loop. # Program to count down from 10 to 1 using while loop i = 10 while i > 0: print(i) i -= 1 6. Print Multiplication Table of a Number Description: Prints the multiplication table of a number entered by the user. # Program to print multiplication table using while loop num = int(input("Enter a number: ")) i = 1 while i <= 10: print(f"{num} x {i} = {num * i}") i += 1 7. Check for Prime Number Description: This program checks whether a number is prime using a while loop. # Program to check if a number is prime using while

Iterative Programs (For, While, Nested Loop) Read More »

Lists, Tuples, Dictionaries, and Sets

Lists, Tuples, Dictionaries, and Sets

The next topic is Lists, Tuples, Dictionaries, and Sets in Python. These are the core data structures used to store collections of data in Python, and each has its own unique characteristics and use cases. We will explore each of these data structures, along with their operations, methods, and common use cases. Lists, Tuples, Dictionaries, and Sets 1. Lists in Python A list is an ordered, mutable collection of items. Lists are widely used to store sequences of data and can hold any type of data, including numbers, strings, and other objects. Example: Create a List and Perform Operations # Creating a list my_list = [1, 2, 3, 4, 5] print("Original List:", my_list) # Append an item to the list my_list.append(6) print("After appending 6:", my_list) # Insert an item at a specific position my_list.insert(2, 7) print("After inserting 7 at index 2:", my_list) # Remove an item from the list my_list.remove(3) print("After removing 3:", my_list) # Pop an item from the list (removes the last item) popped_item = my_list.pop() print("Popped item:", popped_item) print("List after pop:", my_list) # Accessing elements using indexing print("Element at index 2:", my_list[2]) 2. Tuples in Python A tuple is similar to a list, but it is immutable, meaning you cannot change its elements once it is created. Tuples are typically used to store related pieces of data. Example: Create a Tuple and Perform Operations # Creating a tuple my_tuple = (1, 2, 3, 4, 5) print("Original Tuple:", my_tuple) # Accessing elements using indexing print("Element at index 3:", my_tuple[3]) # Trying to modify a tuple (will cause an error) # my_tuple[2] = 6 # This will raise a TypeError 3. Dictionaries in Python A dictionary is an unordered collection of key-value pairs. Dictionaries are useful for storing data in the form of a map or a lookup table, where each key is associated with a specific value. Example: Create a Dictionary and Perform Operations # Creating a dictionary my_dict = {‘name’: ‘John’, ‘age’: 25, ‘city’: ‘New York’} print("Original Dictionary:", my_dict) # Accessing values using keys print("Value associated with key ‘name’:", my_dict[‘name’]) # Adding a new key-value pair my_dict[’email’] = ‘john@example.com’ print("After adding email:", my_dict) # Updating a value for a key my_dict[‘age’] = 26 print("After updating age:", my_dict) # Removing a key-value pair del my_dict[‘city’] print("After removing ‘city’:", my_dict) 4. Sets in Python A set is an unordered collection of unique elements. Sets are useful for removing duplicates from a collection and performing set operations like union, intersection, and difference. Example: Create a Set and Perform Operations # Creating a set my_set = {1, 2, 3, 4, 5} print("Original Set:", my_set) # Adding an element to the set my_set.add(6) print("After adding 6:", my_set) # Removing an element from the set my_set.remove(3) print("After removing 3:", my_set) # Set operations: union, intersection another_set = {4, 5, 6, 7} print("Union of sets:", my_set | another_set) print("Intersection of sets:", my_set & another_set) 5. List Operations List slicing: Extract parts of the list using slicing. List comprehension: A concise way to create lists. Example: List Slicing and Comprehension # List slicing my_list = [1, 2, 3, 4, 5] print("Sliced list (index 1 to 3):", my_list[1:4]) # List comprehension squared_list = [x ** 2 for x in my_list] print("Squared List using comprehension:", squared_list) 6. Tuple Operations Tuples are commonly used for returning multiple values from a function or for storing fixed data. Example: Unpacking Tuple Values # Tuple unpacking my_tuple = (1, 2, 3) a, b, c = my_tuple print("Unpacked values:", a, b, c) 7. Dictionary Operations Dictionaries are very versatile and allow you to map values to keys. Example: Dictionary Operations # Check if a key exists if ‘name’ in my_dict: print("Key ‘name’ exists.") # Getting a value with a default if key does not exist print("Value for key ’email’:", my_dict.get(’email’, ‘Not Found’)) 8. Set Operations Sets support mathematical set operations, such as union, intersection, and difference, which are useful in many scenarios like removing duplicates and finding common or unique elements. Example: Set Operations # Union and intersection set1 = {1, 2, 3} set2 = {3, 4, 5} print("Union of set1 and set2:", set1 | set2) print("Intersection of set1 and set2:", set1 & set2) 9. Nested Lists, Tuples, Dictionaries, and Sets These data structures can be nested, meaning you can store one inside another. For example, you can have a list of tuples, or a dictionary of lists. Example: Nested Data Structures # List of tuples list_of_tuples = [(1, ‘apple’), (2, ‘banana’), (3, ‘cherry’)] print("List of tuples:", list_of_tuples) # Dictionary with lists as values dict_with_lists = {‘fruits’: [‘apple’, ‘banana’, ‘cherry’], ‘vegetables’: [‘carrot’, ‘potato’]} print("Dictionary with lists:", dict_with_lists) # Set of tuples set_of_tuples = {(1, ‘apple’), (2, ‘banana’)} print("Set of tuples:", set_of_tuples) Explanation Lists are versatile and mutable collections used to store ordered data. Tuples are immutable sequences, useful for fixed collections of items. Dictionaries allow you to store data in key-value pairs, providing efficient lookups by key. Sets are collections of unique items and are used for mathematical set operations, ensuring no duplicate elements. Let me know if you’d like to dive deeper into any of these data structures or move on to the next topic!

Lists, Tuples, Dictionaries, and Sets Read More »

Nested Functions

Nested Functions

Programs for Nested Functions Program 1: Basic Nested Function for Greeting def greet(name): """Outer function that defines a nested greeting function.""" def display_message(): """Inner function to create a greeting message.""" return f"Hello, {name}!" return display_message() # Example usage print(greet("Alice")) Expected Output: Hello, Alice! Program 2: Nested Function for Calculating Factorial def calculate_factorial(n): """Outer function to calculate factorial using an inner recursive function.""" def factorial(x): if x == 1: return 1 else: return x * factorial(x – 1) return factorial(n) # Example usage print("Factorial of 5:", calculate_factorial(5)) Expected Output: Factorial of 5: 120 Program 3: Nested Function to Calculate Area and Perimeter of a Rectangle def rectangle_properties(length, width): """Outer function to calculate area and perimeter using nested functions.""" def area(): return length * width def perimeter(): return 2 * (length + width) return f"Area: {area()}, Perimeter: {perimeter()}" # Example usage print(rectangle_properties(5, 3)) Expected Output: Area: 15, Perimeter: 16 Program 4: Nested Function to Find Maximum of Three Numbers def find_maximum(a, b, c): """Outer function to find the maximum of three numbers using a nested function.""" def maximum(x, y): return x if x > y else y return maximum(a, maximum(b, c)) # Example usage print("Maximum of 3, 7, and 5:", find_maximum(3, 7, 5)) Expected Output: Maximum of 3, 7, and 5: 7 Program 5: Nested Function with Conditional Logic (Palindrome Checker) def is_palindrome(word): """Outer function to check if a word is a palindrome.""" def reverse(w): return w[::-1] return word == reverse(word) # Example usage print("Is ‘radar’ a palindrome?", is_palindrome("radar")) print("Is ‘hello’ a palindrome?", is_palindrome("hello")) Expected Output: Is ‘radar’ a palindrome? True Is ‘hello’ a palindrome? False These examples demonstrate various uses of nested functions, from recursive calculations to helper functions for performing specific tasks within a larger function.

Nested Functions Read More »

Applications of Lambda Functions

Applications of Lambda Functions

Applications of Lambda Functions – Programs Program 1: Sorting a List of Tuples Based on the Second Element # List of tuples data = [(1, ‘apple’), (3, ‘banana’), (2, ‘cherry’), (4, ‘date’)] # Sort based on the second element in each tuple sorted_data = sorted(data, key=lambda x: x[1]) print("Sorted by second element:", sorted_data) Expected Output: Sorted by second element: [(1, ‘apple’), (3, ‘banana’), (2, ‘cherry’), (4, ‘date’)] Program 2: Using Lambda with map to Calculate Squares of a List of Numbers # List of numbers numbers = [1, 2, 3, 4, 5] # Apply lambda with map to square each number squared_numbers = list(map(lambda x: x ** 2, numbers)) print("Squared Numbers:", squared_numbers) Expected Output: Squared Numbers: [1, 4, 9, 16, 25] Program 3: Using Lambda with filter to Get Names Longer Than 5 Characters # List of names names = ["Alice", "Bob", "Charlie", "David", "Edward"] # Filter names longer than 5 characters long_names = list(filter(lambda name: len(name) > 5, names)) print("Names longer than 5 characters:", long_names) Expected Output: Names longer than 5 characters: [‘Charlie’, ‘Edward’] Program 4: Using Lambda with reduce to Calculate Product of List Elements from functools import reduce # List of numbers numbers = [1, 2, 3, 4, 5] # Reduce to calculate the product of all elements product = reduce(lambda x, y: x * y, numbers) print("Product of all elements:", product) Expected Output: Product of all elements: 120 Program 5: Lambda Function to Find the Maximum of Two Numbers # Lambda to find the maximum of two numbers max_value = lambda x, y: x if x > y else y # Example usage print("Max of 10 and 20:", max_value(10, 20)) Expected Output: Max of 10 and 20: 20

Applications of Lambda Functions Read More »

Implementation of Lambda Function within a Function

Implementation of Lambda Function within a Function

Programs for Lambda Functions within Functions Program 1: Function with a Lambda Expression for Customizable Mathematical Operations def math_operation(x, y, operation): """Perform a mathematical operation on two numbers using a lambda function.""" return operation(x, y) # Example usage add = lambda x, y: x + y subtract = lambda x, y: x – y print("Addition Result:", math_operation(5, 3, add)) print("Subtraction Result:", math_operation(5, 3, subtract)) Expected Output: Addition Result: 8 Subtraction Result: 2 Program 2: Function to Apply a Discount Using a Lambda Expression def apply_discount(price, discount): """Applies a discount using a lambda expression.""" calculate_discount = lambda p, d: p * (1 – d / 100) return calculate_discount(price, discount) # Example usage print("Price after 10% discount:", apply_discount(200, 10)) print("Price after 20% discount:", apply_discount(300, 20)) Expected Output: Price after 10% discount: 180.0 Price after 20% discount: 240.0 Program 3: Function to Return a Customized Greeting Using a Lambda def personalized_greeting(name, greeting): """Generates a personalized greeting.""" return greeting(name) # Lambda function for the greeting hello = lambda name: f"Hello, {name}!" good_morning = lambda name: f"Good morning, {name}!" # Example usage print(personalized_greeting("Alice", hello)) print(personalized_greeting("Bob", good_morning)) Expected Output: Hello, Alice! Good morning, Bob! Program 4: Function That Generates Power Functions Using Lambda def power_function(n): """Returns a lambda function to raise a number to the power of n.""" return lambda x: x ** n # Example usage square = power_function(2) cube = power_function(3) print("Square of 4:", square(4)) print("Cube of 3:", cube(3)) Expected Output: Square of 4: 16 Cube of 3: 27 Program 5: Lambda Function for Conditional Text Transformation def text_transformer(text, transform_type): """Applies a text transformation based on the provided lambda function.""" transformations = { "uppercase": lambda x: x.upper(), "lowercase": lambda x: x.lower(), "titlecase": lambda x: x.title() } return transformations[transform_type](text) # Example usage print(text_transformer("Hello World", "uppercase")) print(text_transformer("Hello World", "lowercase")) print(text_transformer("hello world", "titlecase")) Expected Output: HELLO WORLD hello world Hello World These examples demonstrate how lambda functions can be incorporated within other functions for dynamic and customized behavior. Let me know if you’d like to proceed with the next topic!

Implementation of Lambda Function within a Function Read More »

Lambda Functions - Programs

Lambda Functions – Programs

Lambda Functions – Programs Program 1: Simple Lambda Function for Addition # Lambda function for adding two numbers add = lambda x, y: x + y # Example usage result = add(5, 3) print("Addition Result:", result) Expected Output: Addition Result: 8 Program 2: Lambda Function for Multiplication # Lambda function for multiplying two numbers multiply = lambda x, y: x * y # Example usage result = multiply(4, 7) print("Multiplication Result:", result) Expected Output: Multiplication Result: 28 Program 3: Lambda Function with Conditional Logic (Even or Odd Check) # Lambda function to check if a number is even or odd check_even_odd = lambda x: "Even" if x % 2 == 0 else "Odd" # Example usage print("10 is:", check_even_odd(10)) print("15 is:", check_even_odd(15)) Expected Output: 10 is: Even 15 is: Odd Program 4: Lambda Function for Calculating Square of a Number # Lambda function for squaring a number square = lambda x: x ** 2 # Example usage print("Square of 6:", square(6)) Expected Output: Square of 6: 36 Program 5: Lambda Function for Filtering Even Numbers from a List # List of numbers numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # Using lambda function with filter to get even numbers even_numbers = list(filter(lambda x: x % 2 == 0, numbers)) print("Even Numbers:", even_numbers) Expected Output: Even Numbers: [2, 4, 6, 8, 10]

Lambda Functions – Programs Read More »

Creating Your Own Module

Creating Your Own Module

Programs for Creating and Using a Custom Module Step 1: Create a Custom Module (mymodule.py) Create a file named mymodule.py with the following functions. # mymodule.py def add(a, b): """Returns the sum of two numbers.""" return a + b def subtract(a, b): """Returns the difference between two numbers.""" return a – b def multiply(a, b): """Returns the product of two numbers.""" return a * b def divide(a, b): """Returns the quotient of two numbers, if b is not zero.""" if b != 0: return a / b else: return "Cannot divide by zero" def factorial(n): """Returns the factorial of a number.""" if n == 0: return 1 else: return n * factorial(n – 1) def greet(name): """Returns a greeting message.""" return f"Hello, {name}!" Save this code as mymodule.py. We’ll now import and use it in different programs. Program 1: Import and Use the add and subtract Functions import mymodule # Using the add function result_add = mymodule.add(5, 3) print("Addition Result:", result_add) # Using the subtract function result_subtract = mymodule.subtract(10, 4) print("Subtraction Result:", result_subtract) Expected Output: Addition Result: 8 Subtraction Result: 6 Program 2: Import and Use the multiply and divide Functions import mymodule # Using the multiply function result_multiply = mymodule.multiply(7, 6) print("Multiplication Result:", result_multiply) # Using the divide function result_divide = mymodule.divide(42, 7) print("Division Result:", result_divide) Expected Output: Multiplication Result: 42 Division Result: 6.0 Program 3: Use the factorial Function import mymodule # Using the factorial function num = 5 result_factorial = mymodule.factorial(num) print(f"Factorial of {num}:", result_factorial) Expected Output: Factorial of 5: 120 Program 4: Use the greet Function import mymodule # Using the greet function name = "Alice" greeting = mymodule.greet(name) print(greeting) Expected Output: Hello, Alice! Program 5: Use All Functions Together in a Comprehensive Program import mymodule # Calling all functions print("Addition:", mymodule.add(10, 5)) print("Subtraction:", mymodule.subtract(10, 5)) print("Multiplication:", mymodule.multiply(10, 5)) print("Division:", mymodule.divide(10, 5)) print("Factorial of 4:", mymodule.factorial(4)) print("Greeting:", mymodule.greet("Charlie")) Expected Output: Addition: 15 Subtraction: 5 Multiplication: 50 Division: 2.0 Factorial of 4: 24 Greeting: Hello, Charlie! Program 6: Import Specific Functions Directly from mymodule import add, greet # Directly calling add and greet without prefix print("Addition:", add(3, 9)) print(greet("Bob")) Expected Output: Addition: 12 Hello, Bob! Program 7: Use Aliases for Functions import mymodule as mm # Calling functions with module alias print("Multiplication (Alias):", mm.multiply(4, 7)) print("Division (Alias):", mm.divide(35, 5)) Expected Output: Multiplication (Alias): 28 Division (Alias): 7.0 Program 8: Use factorial with Larger Input import mymodule # Calculating factorial of a larger number print("Factorial of 7:", mymodule.factorial(7)) Expected Output: Factorial of 7: 5040 Program 9: Error Handling with divide import mymodule # Attempt division by zero result = mymodule.divide(5, 0) print("Division Result:", result) Expected Output: Division Result: Cannot divide by zero Program 10: Conditional Import and Use try: import mymodule # Only execute if the module is present print("Factorial of 3:", mymodule.factorial(3)) except ImportError: print("Module ‘mymodule’ not found.") Expected Output (if module is present): Factorial of 3: 6 These programs demonstrate using a custom module, with expected outputs provided for each example.

Creating Your Own Module Read More »

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 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 »

Built-in Functions in Python

Built-in Functions in Python

Built-in Functions (20 Programs) Program 1: abs() – Absolute Value of a Number Program: def absolute_value(num): """Return the absolute value of a number.""" return abs(num) # Test the function print("Absolute value of -10:", absolute_value(-10)) print("Absolute value of 5:", absolute_value(5)) Expected Output: Absolute value of -10: 10 Absolute value of 5: 5 Program 2: all() – Check if All Elements in List are True Program: def check_all_true(values): """Check if all elements in the list are True.""" return all(values) # Test the function print("All elements True:", check_all_true([True, True, True])) print("All elements True:", check_all_true([True, False, True])) Expected Output: All elements True: True All elements True: False Program 3: any() – Check if Any Element in List is True Program: def check_any_true(values): """Check if any element in the list is True.""" return any(values) # Test the function print("Any element True:", check_any_true([False, False, True])) print("Any element True:", check_any_true([False, False, False])) Expected Output: Any element True: True Any element True: False Program 4: ascii() – Return ASCII Representation of a String Program: def get_ascii_representation(text): """Get ASCII representation of a string.""" return ascii(text) # Test the function print("ASCII representation:", get_ascii_representation("Python ©")) Expected Output: ASCII representation: ‘Python \xa9’ Program 5: bin() – Convert Integer to Binary Program: def to_binary(num): """Convert an integer to binary.""" return bin(num) # Test the function print("Binary of 10:", to_binary(10)) print("Binary of 25:", to_binary(25)) Expected Output: Binary of 10: 0b1010 Binary of 25: 0b11001 Program 6: bool() – Convert Value to Boolean Program: def to_boolean(value): """Convert a value to boolean.""" return bool(value) # Test the function print("Boolean of 0:", to_boolean(0)) print("Boolean of ‘Hello’:", to_boolean("Hello")) Expected Output: Boolean of 0: False Boolean of ‘Hello’: True Program 7: chr() – Convert Unicode Code to Character Program: def unicode_to_char(code): """Convert Unicode code to character.""" return chr(code) # Test the function print("Character for 97:", unicode_to_char(97)) print("Character for 65:", unicode_to_char(65)) Expected Output: Character for 97: a Character for 65: A Program 8: divmod() – Quotient and Remainder of Division Program: def quotient_remainder(a, b): """Get quotient and remainder of division.""" return divmod(a, b) # Test the function print("Quotient and remainder of 10 / 3:", quotient_remainder(10, 3)) print("Quotient and remainder of 20 / 6:", quotient_remainder(20, 6)) Expected Output: Quotient and remainder of 10 / 3: (3, 1) Quotient and remainder of 20 / 6: (3, 2) Program 9: enumerate() – Enumerate List Items with Index Program: def enumerate_list(items): """Enumerate items in a list with their index.""" return list(enumerate(items)) # Test the function print("Enumerated list:", enumerate_list(["apple", "banana", "cherry"])) Expected Output: Enumerated list: [(0, ‘apple’), (1, ‘banana’), (2, ‘cherry’)] Program 10: eval() – Evaluate a Python Expression Program: def evaluate_expression(expression): """Evaluate a Python expression.""" return eval(expression) # Test the function print("Evaluation of ‘3 + 5’:", evaluate_expression("3 + 5")) print("Evaluation of ‘2 * 6’:", evaluate_expression("2 * 6")) Expected Output: Evaluation of ‘3 + 5’: 8 Evaluation of ‘2 * 6’: 12 Program 11: filter() – Filter Even Numbers from a List Program: def filter_even(numbers): """Filter even numbers from a list.""" return list(filter(lambda x: x % 2 == 0, numbers)) # Test the function print("Even numbers:", filter_even([1, 2, 3, 4, 5, 6])) Expected Output: Even numbers: [2, 4, 6] Program 12: float() – Convert Value to Float Program: def to_float(value): """Convert a value to float.""" return float(value) # Test the function print("Float of 5:", to_float(5)) print("Float of ‘3.14’:", to_float("3.14")) Expected Output: Float of 5: 5.0 Float of ‘3.14’: 3.14 Program 13: format() – Format Number with 2 Decimal Places Program: def format_number(num): """Format a number to 2 decimal places.""" return format(num, ".2f") # Test the function print("Formatted number:", format_number(3.14159)) print("Formatted number:", format_number(7.88888)) Expected Output: Formatted number: 3.14 Formatted number: 7.89 Program 14: hex() – Convert Integer to Hexadecimal Program: def to_hexadecimal(num): """Convert an integer to hexadecimal.""" return hex(num) # Test the function print("Hexadecimal of 255:", to_hexadecimal(255)) print("Hexadecimal of 16:", to_hexadecimal(16)) Expected Output: Hexadecimal of 255: 0xff Hexadecimal of 16: 0x10 Program 15: input() – Take User Input (for Interactive Testing) Program: def get_user_input(): """Get input from the user.""" user_input = input("Enter a message: ") return f"You entered: {user_input}" # Run in an interactive environment to see output. Output will depend on user input. Program 16: len() – Length of a List Program: def list_length(lst): """Return the length of a list.""" return len(lst) # Test the function print("Length of list:", list_length([1, 2, 3, 4])) Expected Output: Length of list: 4 Program 17: max() – Maximum of Three Numbers Program: def find_maximum(a, b, c): """Find the maximum of three numbers.""" return max(a, b, c) # Test the function print("Maximum of (3, 7, 5):", find_maximum(3, 7, 5)) Expected Output: Maximum of (3, 7, 5): 7 Program 18: min() – Minimum of Three Numbers Program: def find_minimum(a, b, c): """Find the minimum of three numbers.""" return min(a, b, c) # Test the function print("Minimum of (3, 7, 5):", find_minimum(3, 7, 5)) Expected Output: Minimum of (3, 7, 5): 3 Program 19: round() – Round a Number to Specified Digits Program: def round_number(num, digits): """Round a number to specified digits.""" return round(num, digits) # Test the function print("Rounded number:", round_number(3.14159, 2)) Expected Output: Rounded number: 3.14 Program 20: sorted() – Sort a List in Ascending Order Program: def sort_list(lst): """Sort a list in ascending order.""" return sorted(lst) # Test the function print("Sorted list:", sort_list([3, 1, 4, 2])) Expected Output: Sorted list: [1, 2, 3, 4]

Built-in Functions in Python Read More »

Pattern Programs

Pattern Programs

The next topic is Pattern Programs. Pattern programs are a great way to demonstrate the power of loops and how they can be used to create visually interesting outputs. The concept of nested loops is often used in pattern printing, and different types of patterns help reinforce the understanding of loops, conditions, and formatting in Python. Here are 20 different Pattern Programs in Python to explore. Pattern Programs 1. Right-Angled Triangle Pattern of Stars Description: Prints a right-angled triangle of stars. # Program to print a right-angled triangle pattern using stars n = int(input("Enter the number of rows: ")) for i in range(n): for j in range(i + 1): print("*", end="") print() 2. Inverted Right-Angled Triangle Pattern of Stars Description: Prints an inverted right-angled triangle pattern of stars. # Program to print an inverted right-angled triangle pattern using stars n = int(input("Enter the number of rows: ")) for i in range(n, 0, -1): for j in range(i): print("*", end="") print() 3. Pyramid Pattern of Stars Description: Prints a pyramid pattern using stars. # Program to print a pyramid pattern of stars n = int(input("Enter the number of rows: ")) for i in range(1, n + 1): print(" " * (n – i) + "*" * (2 * i – 1)) 4. Diamond Pattern of Stars Description: Prints a diamond shape using stars. # Program to print diamond pattern of stars n = int(input("Enter the number of rows for the upper half: ")) # Upper half of the diamond for i in range(1, n + 1): print(" " * (n – i) + "*" * (2 * i – 1)) # Lower half of the diamond for i in range(n – 1, 0, -1): print(" " * (n – i) + "*" * (2 * i – 1)) 5. Number Pyramid Pattern Description: Prints a number pyramid. # Program to print number pyramid pattern n = int(input("Enter the number of rows: ")) for i in range(1, n + 1): print(" " * (n – i) + " ".join(str(j) for j in range(1, i + 1))) 6. Inverted Number Pyramid Description: Prints an inverted number pyramid. # Program to print an inverted number pyramid pattern n = int(input("Enter the number of rows: ")) for i in range(n, 0, -1): print(" " * (n – i) + " ".join(str(j) for j in range(1, i + 1))) 7. Square Pattern of Numbers Description: Prints a square pattern using numbers. # Program to print a square pattern of numbers n = int(input("Enter the size of the square: ")) for i in range(1, n + 1): for j in range(1, n + 1): print(i, end=" ") print() 8. Hollow Square Pattern Description: Prints a hollow square using stars. # Program to print a hollow square pattern n = int(input("Enter the size of the square: ")) for i in range(n): for j in range(n): if i == 0 or i == n – 1 or j == 0 or j == n – 1: print("*", end="") else: print(" ", end="") print() 9. Floyd’s Triangle Description: Prints Floyd’s Triangle with consecutive numbers. # Program to print Floyd’s Triangle n = int(input("Enter the number of rows: ")) num = 1 for i in range(1, n + 1): for j in range(1, i + 1): print(num, end=" ") num += 1 print() 10. Butterfly Pattern Description: Prints a butterfly pattern using stars. # Program to print butterfly pattern using stars n = int(input("Enter the number of rows: ")) # Upper part of the butterfly for i in range(1, n + 1): print("*" * i + " " * (2 * (n – i)) + "*" * i) # Lower part of the butterfly for i in range(n, 0, -1): print("*" * i + " " * (2 * (n – i)) + "*" * i) 11. Hollow Triangle Pattern Description: Prints a hollow triangle pattern using stars. # Program to print hollow triangle pattern n = int(input("Enter the number of rows: ")) for i in range(1, n + 1): for j in range(1, i + 1): if j == 1 or j == i or i == n: print("*", end="") else: print(" ", end="") print() 12. Zigzag Pattern Description: Prints a zigzag pattern using stars. # Program to print zigzag pattern using stars n = int(input("Enter the number of rows: ")) for i in range(n): for j in range(n): if (i + j) % 2 == 0: print("*", end="") else: print(" ", end="") print() 13. Pascal’s Triangle Description: Prints Pascal’s Triangle. # Program to print Pascal’s Triangle n = int(input("Enter the number of rows: ")) for i in range(n): num = 1 for j in range(i + 1): print(num, end=" ") num = num * (i – j) // (j + 1) print() 14. Right-Angled Triangle of Numbers Description: Prints a right-angled triangle with numbers. # Program to print a right-angled triangle of numbers n = int(input("Enter the number of rows: ")) for i in range(1, n + 1): for j in range(1, i + 1): print(j, end="") print() 15. Right-Angled Triangle of Alphabets Description: Prints a right-angled triangle with alphabets. # Program to print a right-angled triangle of alphabets n = int(input("Enter the number of rows: ")) for i in range(n): for j in range(i + 1): print(chr(65 + j), end="") print() 16. Inverted Triangle of Stars Description: Prints an inverted triangle using stars. # Program to print an inverted triangle of stars n = int(input("Enter the number of rows: ")) for i in range(n, 0, -1): print("*" * i) 17. Hollow Diamond Pattern Description: Prints a hollow diamond shape using stars. # Program to print hollow diamond pattern n = int(input("Enter the number of rows for the upper half: ")) # Upper half of the diamond for i in range(1, n + 1): print(" " * (n – i) + "*" + " " * (2 * i – 3) + "*" * (i > 1)) # Lower half of the diamond for i in range(n –

Pattern Programs Read More »

Scroll to Top
Contact Form Demo