Python Programming

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 »

Prime Number Programs

Prime Number Programs

The next topic is Prime Number Programs, where we focus on writing programs to identify prime numbers and perform tasks related to prime numbers. We’ll start with Prime Factorization, which is finding the prime factors of a number. To meet your specific request, I will also include a program that executes a loop until the square of a prime factor. Prime Number Programs 1. Check If a Number is Prime Description: This program checks if a number is prime or not. # Program to check if a number is prime num = int(input("Enter a number: ")) if num > 1: for i in range(2, int(num / 2) + 1): if num % i == 0: print(f"{num} is not a prime number.") break else: print(f"{num} is a prime number.") else: print(f"{num} is not a prime number.") 2. Find Prime Factors of a Number Description: This program finds the prime factors of a given number. # Program to find prime factors of a number num = int(input("Enter a number: ")) i = 2 print(f"Prime factors of {num} are:") while i * i <= num: if num % i: i += 1 else: num //= i print(i, end=" ") if num > 1: print(num) 3. Loop Till the Square of the Prime Factor Description: This program loops through the prime factors and executes a loop until the square of the prime factor. # Program to loop until the square of the prime factor def prime_factors(n): factors = [] i = 2 while i * i <= n: if n % i == 0: factors.append(i) n //= i else: i += 1 if n > 1: factors.append(n) return factors def loop_until_square_of_prime_factor(n): factors = prime_factors(n) for factor in factors: print(f"\nExecuting loop for prime factor {factor}:") i = 1 # Loop until the square of the prime factor while i <= factor * factor: print(f"i = {i}") i += 1 num = int(input("Enter a number: ")) loop_until_square_of_prime_factor(num) Explanation Prime Factors Program: This program finds the prime factors of a number using a while loop. It divides the number by possible factors until we reach a prime number. Loop Until Square of Prime Factor: In this program, we first find the prime factors of the input number, and for each prime factor, we execute a loop that runs until the square of that prime factor. This fulfills your specific requirement. Let me know if you’d like to explore more prime number programs or move on to the next topic!

Prime Number Programs Read More »

Strings Program

Strings Program

The next topic is Strings in Python. Strings are one of the most commonly used data types in Python and are essential for handling textual data. In this section, we will explore various operations and methods that can be performed on strings in Python, including concatenation, slicing, formatting, and more. String Programs 1. Check If a String is a Palindrome Description: This program checks if a given string is a palindrome (reads the same backward as forward). # Program to check if a string is a palindrome string = input("Enter a string: ") if string == string[::-1]: print(f"'{string}’ is a palindrome.") else: print(f"'{string}’ is not a palindrome.") 2. Count Vowels in a String Description: This program counts the number of vowels in a given string. # Program to count vowels in a string string = input("Enter a string: ") vowels = "aeiouAEIOU" count = 0 for char in string: if char in vowels: count += 1 print(f"The number of vowels in ‘{string}’ is {count}.") 3. Reverse a String Description: This program reverses a given string. # Program to reverse a string string = input("Enter a string: ") reversed_string = string[::-1] print(f"The reversed string is: ‘{reversed_string}’") 4. Count the Frequency of Each Character in a String Description: This program counts how many times each character appears in a string. # Program to count the frequency of each character in a string string = input("Enter a string: ") frequency = {} for char in string: if char in frequency: frequency[char] += 1 else: frequency[char] = 1 print(f"Character frequency in ‘{string}’: {frequency}") 5. Convert All Characters to Uppercase Description: This program converts all characters in a string to uppercase. # Program to convert a string to uppercase string = input("Enter a string: ") uppercase_string = string.upper() print(f"The string in uppercase is: ‘{uppercase_string}’") 6. Convert All Characters to Lowercase Description: This program converts all characters in a string to lowercase. # Program to convert a string to lowercase string = input("Enter a string: ") lowercase_string = string.lower() print(f"The string in lowercase is: ‘{lowercase_string}’") 7. Find the Length of a String Description: This program finds the length of a string. # Program to find the length of a string string = input("Enter a string: ") length = len(string) print(f"The length of the string ‘{string}’ is {length}.") 8. Check if a Substring Exists in a String Description: This program checks if a given substring is present in a string. # Program to check if a substring exists in a string string = input("Enter a string: ") substring = input("Enter the substring to check: ") if substring in string: print(f"'{substring}’ exists in ‘{string}’.") else: print(f"'{substring}’ does not exist in ‘{string}’.") 9. Remove Whitespaces from a String Description: This program removes leading and trailing whitespaces from a string. # Program to remove whitespaces from a string string = input("Enter a string with spaces: ") trimmed_string = string.strip() print(f"The string without leading and trailing spaces is: ‘{trimmed_string}’") 10. Find the Position of a Substring Description: This program finds the position of the first occurrence of a substring. # Program to find the position of a substring string = input("Enter a string: ") substring = input("Enter the substring: ") position = string.find(substring) if position != -1: print(f"The substring ‘{substring}’ is found at position {position}.") else: print(f"The substring ‘{substring}’ is not found.") 11. Replace All Occurrences of a Substring in a String Description: This program replaces all occurrences of a substring with another string. # Program to replace all occurrences of a substring in a string string = input("Enter a string: ") old_substring = input("Enter the substring to replace: ") new_substring = input("Enter the new substring: ") new_string = string.replace(old_substring, new_substring) print(f"The new string is: ‘{new_string}’") 12. Check If a String Starts with a Specific Substring Description: This program checks if a string starts with a specific substring. # Program to check if a string starts with a specific substring string = input("Enter a string: ") substring = input("Enter the substring: ") if string.startswith(substring): print(f"'{string}’ starts with ‘{substring}’.") else: print(f"'{string}’ does not start with ‘{substring}’.") 13. Check If a String Ends with a Specific Substring Description: This program checks if a string ends with a specific substring. # Program to check if a string ends with a specific substring string = input("Enter a string: ") substring = input("Enter the substring: ") if string.endswith(substring): print(f"'{string}’ ends with ‘{substring}’.") else: print(f"'{string}’ does not end with ‘{substring}’.") 14. Find All Occurrences of a Substring Description: This program finds all occurrences of a substring in a string. # Program to find all occurrences of a substring in a string string = input("Enter a string: ") substring = input("Enter the substring: ") start = 0 while start < len(string): start = string.find(substring, start) if start == -1: break print(f"Found ‘{substring}’ at position {start}") start += 1 15. Join Elements of a List into a String Description: This program joins a list of strings into a single string. # Program to join elements of a list into a string list_of_strings = ["Python", "is", "great"] joined_string = " ".join(list_of_strings) print(f"The joined string is: ‘{joined_string}’") 16. Split a String into a List Description: This program splits a string into a list of words. # Program to split a string into a list string = input("Enter a string: ") split_list = string.split() print(f"The list of words is: {split_list}") 17. Check If All Characters in a String Are Digits Description: This program checks if all characters in a string are digits. # Program to check if all characters in a string are digits string = input("Enter a string: ") if string.isdigit(): print(f"'{string}’ contains only digits.") else: print(f"'{string}’ does not contain only digits.") 18. Convert a String to a List of Characters Description: This program converts a string into a list of characters. # Program to convert a string to a list of characters string = input("Enter a string: ") char_list = list(string) print(f"The list of characters is: {char_list}") 19. Find the Most Frequent Character in a String Description: This program

Strings Program Read More »

Type Casting Programs (5 Programs)

Type Casting Programs (5 Programs)

Type Casting Programs (5 Programs) Program 1: Convert String to Integer and Perform Arithmetic Operations Program: # Define a string representing an integer num_str = "25" # Convert the string to an integer num_int = int(num_str) # Perform arithmetic operations sum_value = num_int + 10 product = num_int * 3 print("Original String:", num_str) print("Converted to Integer:", num_int) print("Sum with 10:", sum_value) print("Product with 3:", product) Expected Output: Original String: 25 Converted to Integer: 25 Sum with 10: 35 Product with 3: 75 Program 2: Convert Integer to Float and Perform Division Program: # Define an integer integer_value = 15 # Convert integer to float float_value = float(integer_value) # Perform division with another float result = float_value / 4.0 print("Integer:", integer_value) print("Converted to Float:", float_value) print("Division Result (Float):", result) Expected Output: Integer: 15 Converted to Float: 15.0 Division Result (Float): 3.75 Program 3: Convert Float to String and Concatenate Program: # Define a float value float_val = 3.14159 # Convert float to string str_val = str(float_val) # Concatenate with another string concatenated = "Pi is approximately " + str_val print("Float Value:", float_val) print("Converted to String:", str_val) print("Concatenated String:", concatenated) Expected Output: Float Value: 3.14159 Converted to String: 3.14159 Concatenated String: Pi is approximately 3.14159 Program 4: Convert List to Set to Remove Duplicates Program: # Define a list with duplicate elements num_list = [1, 2, 2, 3, 4, 4, 5] # Convert list to set to remove duplicates num_set = set(num_list) print("Original List:", num_list) print("Converted to Set (Unique Values):", num_set) Expected Output: Original List: [1, 2, 2, 3, 4, 4, 5] Converted to Set (Unique Values): {1, 2, 3, 4, 5} Program 5: Convert Dictionary Keys and Values to Lists Program: # Define a dictionary with some key-value pairs student_grades = {"Alice": 88, "Bob": 92, "Charlie": 85} # Convert dictionary keys and values to separate lists keys_list = list(student_grades.keys()) values_list = list(student_grades.values()) print("Dictionary:", student_grades) print("Keys as List:", keys_list) print("Values as List:", values_list) Expected Output: Dictionary: {‘Alice’: 88, ‘Bob’: 92, ‘Charlie’: 85} Keys as List: [‘Alice’, ‘Bob’, ‘Charlie’] Values as List: [88, 92, 85]

Type Casting Programs (5 Programs) Read More »

Scroll to Top
Contact Form Demo