3 - PROGRAMS USING FUNCTIONS
Exp - 3(a) - To write a Python program using Function with parameters and return to design a
Simple Calculator.
# User input
def add(a, b):
num1 = float(input("Enter first number: "))
return a + b
operator = input("Enter operation (+, -, *, /, //):
")
def subtract(a, b):
num2 = float(input("Enter second number: "))
return a - b
# Performing operation
def multiply(a, b):
if operator == '+':
return a * b
print("Result:", add(num1, num2))
elif operator == '-':
def divide(a, b):
print("Result:", subtract(num1, num2))
if b == 0:
elif operator == '*':
return "Error! Division by zero."
print("Result:", multiply(num1, num2))
return a / b
elif operator == '/':
print("Result:", divide(num1, num2))
def floor_division(a, b):
elif operator == '//':
if b == 0:
print("Result:", floor_division(num1, num2))
return "Error! Division by zero."
else:
return a // b
print("Invalid operator!")
Exp - 3(b) - To write a Python program using Function without parameters to calculate the power
of a given number with negative or positive base value.
def power():
# Taking input inside the function
print(f"{x}^{y} = {result}")
x = float(input("Enter base (x): "))
y = int(input("Enter exponent (y): "))
# Calling the function
power()
result = x ** y # Exponentiation using '**'
operator
Exp - 3(c) - To write a Python program using Function with actual parameters to calculate the
Volume of Cuboids.
def volume_of_cuboid(length=1, width=1,
# Calling the function with different sets of
height=1):
arguments
volume = length * width * height # Volume
volume_of_cuboid(5, 3, 2)
formula
volume_of_cuboid(7, 4)
print(f"Volume of Cuboid (Length={length},
volume_of_cuboid(10)
Width={width}, Height={height}) = {volume}
volume_of_cuboid()
cubic units")
Exp - 3(d) - To write a Python program using Function with arguments is unnamed and positional
to calculate the Simple Interest.
def simple_interest(*args):
SI = (P * R * T) / 100 # Simple Interest formula
if len(args) < 3:
print(f"Simple Interest for Principal {P}, Rate
print("Error: Please provide Principal, Rate,
{R}%, Time {T} years = {SI}")
and Time!")
# Calling the function with different sets of
return
arguments
simple_interest(1000, 5, 2)
P = args[0] # Principal amount
simple_interest(5000, 3.5, 4)
R = args[1] # Rate of interest
simple_interest(2000, 7)
T = args[2] # Time in years
Exp - 3(e) - To write a Python program using Function with named arguments to calculate the
Simple Interest.
def simple_interest(**kwargs):
if "principal" not in kwargs or "rate" not in T = kwargs["time"]
kwargs or "time" not in kwargs: SI = (P * R * T) / 100
print("Error: Please provide 'principal', 'rate', print(f"Simple Interest: {SI}")
and 'time' as keyword arguments!")
return # Calling the function with named arguments
simple_interest(principal=1500, rate=4, time=2)
P = kwargs["principal"]
R = kwargs["rate"]
Exp - 3(f) - To write a Python program to calculate the Area of a Circle by Calling Function.
# Function to calculate the area of a circle volume = base_area * height
def calculate_circle_area(radius): print(f"Volume of Cylinder (Radius={radius},
pi=3.14 Height={height}) = {volume:.2f} cubic units")
return pi * radius ** 2
# Calling the function
# Function to calculate the volume of a cylinder calculate_cylinder_volume(3, 5) # Example 1
(Calls calculate_circle_area) calculate_cylinder_volume(7, 10) # Example 2
def calculate_cylinder_volume(radius, height):
base_area = calculate_circle_area(radius)
# Calls another function
Exp - 3(g) - To write a Python program to calculate the Factorial of a given number using Recursion
Function.
# Function to calculate factorial using recursion
def factorial(n): # Check if input is valid (Non-negative)
if n == 0 or n == 1: # Base case if num < 0:
return 1 print("Factorial is not defined for negative
else: numbers.")
return n * factorial(n - 1) # Recursive call else:
# Input from the user print(f"Factorial of {num} is {factorial(num)}")
num = int(input("Enter a number: "))
Exp - 3(h) - To write a Python program to find the Largest of Three Numbers Using Lambda
Function.
# Lambda function to find the largest of three numbers
largest = lambda a, b, c: max(a, b, c)
# Taking user input
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
num3 = int(input("Enter third number: "))
# Using the lambda function
result = largest(num1, num2, num3)
# Display the result
print(f"The largest number among {num1}, {num2}, and {num3} is {result}")
4 - PROGRAMS USING STRINGS
Exp - 4(a) - To write a Python program for manipulating the Strings with basic string operations.
# Basic String Operations in Python
# 6. Membership check
check_word = "Python"
# 1. Getting user input
print(f"Is '{check_word}' in the string? {'Yes' if
text = input("Enter a string: ")
check_word in text else 'No'}")
# 2. Find the length of the string
# 7. String comparison
print(f"Length of the string: {len(text)}")
other_string = input("Enter another string for
comparison: ")
# 3. String concatenation
if text == other_string:
extra_text = " - Python Programming"
print("Both strings are equal.")
concatenated_string = text + extra_text
elif text > other_string:
print(f"Concatenated String:
print(f"'{text}' is lexicographically greater than
{concatenated_string}")
'{other_string}'.")
else:
# 4. String repetition
print(f"'{text}' is lexicographically smaller than
print(f"Repeated String: {text * 2}")
'{other_string}'.")
# 5. String slicing
# 8. Convert to uppercase and lowercase
print(f"First 5 characters: {text[:5]}")
print(f"Uppercase: {text.upper()}")
print(f"Last 5 characters: {text[-5:]}")
print(f"Lowercase: {text.lower()}")
print(f"Middle part: {text[2:8]}")
# 9. Capitalize first letter
print(f"Capitalized: {text.capitalize()}")
Exp - 4(b) - To write a Python program to implement different Strings Functions and Methods.
# Take input string # 8. Check if the string is alphanumeric, digit, or
text = input("Enter a string: ") space
print(f"Is the string alphanumeric?
# 1. Length of the string {text.isalnum()}")
print(f"Length of the string: {len(text)}") print(f"Is the string a digit? {text.isdigit()}")
print(f"Is the string whitespace?
# 2. Convert to uppercase and lowercase {text.isspace()}")
print(f"Uppercase: {text.upper()}")
print(f"Lowercase: {text.lower()}") # 9. Split the string into words
words = text.split()
# 3. Capitalize the first letter of the string print(f"Words in the string: {words}")
print(f"Capitalized: {text.capitalize()}") # 10. Join words into a single string
joined_text = " ".join(words)
# 4. Replace substring print(f"Joined string: {joined_text}")
old_substring = input("Enter substring to
replace: ") # 11. Reverse the string
new_substring = input("Enter new substring: ") reversed_text = text[::-1]
replaced_text = text.replace(old_substring, print(f"Reversed string: {reversed_text}")
new_substring)
print(f"String after replacement: # 12. String formatting example
{replaced_text}") name = "Alice"
age = 30
# 5. Count occurrences of a substring print(f"My name is {name} and I am {age}
count_substring = input("Enter a substring to years old.")
count occurrences: ")
count = text.count(count_substring) # 13. String slicing (example: take first 3
print(f"Occurrences of '{count_substring}': characters)
{count}") sliced_text = text[:3]
print(f"Sliced string (first 3 characters):
# 6. Find a substring {sliced_text}")
find_substring = input("Enter a substring to
find: ") # 14. String stripping (remove leading/trailing
find_index = text.find(find_substring) spaces)
if find_index != -1: stripped_text = text.strip()
print(f"Substring '{find_substring}' found at print(f"Stripped string: {stripped_text}")
index {find_index}")
else: # 15. Check if all characters are uppercase
print(f"Substring '{find_substring}' not print(f"Is the string all uppercase?
found") {text.isupper()}")
# 7. Check if the string starts/ends with a given # 16. Check if all characters are lowercase
substring print(f"Is the string all lowercase?
starts_with = input("Enter a substring to check {text.islower()}")
if it starts with: ")
ends_with = input("Enter a substring to check # 17. Convert string to title case (capitalize
if it ends with: ") each word)
print(f"Starts with '{starts_with}': title_text = text.title()
{text.startswith(starts_with)}") print(f"Title case: {title_text}")
print(f"Ends with '{ends_with}':
{text.endswith(ends_with)}")
Exp - 4(c) - To write a Python program using a function to check if the string is a palindrome or not.
# Function to check if a string is a palindrome
def is_palindrome(text): # Call function and display result
return text == text[::-1] # Check if the string is if is_palindrome(string):
equal to its reverse print("It's a palindrome!")
else:
# Take user input print("Not a palindrome.")
string = input("Enter a string: ")
5 - LISTS, TUPLES, AND DICTIONARIES
Exp - 5(a) - To write a Python program to implement List operations.
# Creating a list with different data types
print("After Pop:", mixed_list)
mixed_list = [10, 3.14, "Hello", True, 42,
"Python"]
# 6. Finding an index of an element
index = mixed_list.index(3.14)
# 1. Display the list
print(f"Index of 3.14: {index}")
print("Original List:", mixed_list)
# 7. Reverse the list
# 2. Add an element to the list
mixed_list.reverse()
mixed_list.append(False)
print("Reversed List:", mixed_list)
print("After Append:", mixed_list)
# 8. Slicing the list (Extract first 3 elements)
# 3. Insert an element at a specific position
print("Sliced List (First 3 elements):",
mixed_list.insert(2, "Inserted Item") # Insert at
mixed_list[:3])
index 2
print("After Insert:", mixed_list)
# 9. Checking membership in the list
print("Is 'Python' in the list?", "Python" in
# 4. Remove an element
mixed_list)
mixed_list.remove("Hello") # Removes first
occurrence of "Hello"
# 10. Looping through the list
print("After Remove:", mixed_list)
print("Looping through the list:")
for item in mixed_list:
# 5. Pop an element (removes last element)
print(item, type(item)) # Print each item with
popped_element = mixed_list.pop()
its type
print(f"Popped Element: {popped_element}")
Exp - 5(b) - To write a Python program to Remove all Duplicates in the List.
# Example list with duplicates
numbers = [10, 20, 30, 10, 40, 20, 50, 30, 60]
# List to store unique elements
unique_numbers = []
# Loop through the original list
for item in numbers:
if item not in unique_numbers: # Check if item is not already in unique_numbers
unique_numbers.append(item)
# Print the result
print("Original List:", numbers)
print("List after Removing Duplicates:", unique_numbers)
Exp - 5(c) - To write a Python program to create a new list using filter () that has only positive
values.
# Define function to check if the number is
positive num_list = [10, -20, 30, -40, 50, -60, 70, -80, 90, -
def is_positive(x): 100]
if x >= 0: # Using filter with the is_positive function to get
return True positive numbers
return False positive_list = list(filter(is_positive, num_list))
# Example list with both positive and negative # Print the result
numbers print("Positive Values List =", positive_list)
Exp - 5(d) - To write a Python program using map() function to generate a list of squares from a
given list of numbers.
def square(x):
return x ** 2
numbers = [1, 2, 3, 4, 5]
squares = list(map(square, numbers))
print(squares)
Exp - 5(e) - To use the reduce() function from Python's functools module to find the largest value
in a list.
from functools import reduce
numbers = [3, 7, 2, 8, 5, 10, 6]
# Using reduce() to find the largest number
largest = reduce(lambda x, y: x if x > y else y, numbers)
# Print the result
print(largest)
Exp - 5(f) - To write a Python program to add the 3*3 matrix using Nested List.
# Define two 3×3 matrices
matrix1 = [[1, 2, 3], # Perform matrix addition using nested loops
[4, 5, 6], for i in range(3): # Loop through rows
[7, 8, 9]] for j in range(3): # Loop through columns
matrix2 = [[9, 8, 7], result[i][j] = matrix1[i][j] + matrix2[i][j]
[6, 5, 4],
[3, 2, 1]] # Print the result matrix
# Initialize a 3×3 result matrix with zeros print("Sum of the matrices:")
result = [[0, 0, 0], for row in result:
[0, 0, 0], print(row)
[0, 0, 0]]
Exp - 5(g) - To write a Python program to implement Tuple operations and methods.
# 6. Checking Membership
print("\nIs 3 in tuple:", 3 in t)
# 1. Creating a Tuple print("Is 10 in tuple:", 10 in t)
t = (1, 2, 3, 4, 5) print("\n\nIndex of 3:", t.index(3))
print("Tuple:", t) print("Count of 2:", t.count(2))
# 2. Accessing Elements # 7. Iterating Over a Tuple
print("\nFirst Element:", t[0]) print("\nIterating over the tuple:")
print("Last Element:", t[-1]) for item in t:
# 3. Slicing a Tuple print(item, end=" ")
print("\nFirst three elements:", t[:3]) # 8. Finding Index & Count of an Element
print("Last two elements:", t[-2:]) t = (1, 2, 3, 2, 4, 2, 5)
# 4. Tuple Length # 9. Converting a Tuple to a List and Vice Versa
print("\nTuple Length:", len(t)) list_from_tuple = list(t)
# 5. Concatenation & Repetition print("\nList from Tuple:", list_from_tuple)
t1 = (1, 2, 3) tuple_from_list = tuple(list_from_tuple)
t2 = (4, 5, 6) print("Tuple from List:", tuple_from_list)
# Concatenation # 10. Tuple Unpacking
t3 = t1 + t2 t = (10, 20, 30)
print("\nConcatenated Tuple:", t3) a, b, c = t
# Repetition print("\nUnpacked Values:", a, b, c)
t4 = t1 * 2 # 11. Finding Maximum, Minimum, and Sum
print("Repeated Tuple:", t4) print("\nMax:", max(t))
print("Min:", min(t))
print("Sum:", sum(t))
Exp - 5(h) - to create a Python program that allows users to enter, manage, and analyze student
grades
# Student Grades Application
if grades:
highest = max(grades)
# Function to add student grades
lowest = min(grades)
def add_grades():
return highest, lowest
grades = ()
else:
while True:
return None, None
grade = input("Enter grade (or type 'done' to
finish): ")
# Main Application
if grade.lower() == 'done':
print("Student Grades Management")
break
try:
# Add grades for a student
grades += (float(grade),) # Add the grade
grades = add_grades()
to the tuple
except ValueError:
# Calculate the average, highest, and lowest
print("Please enter a valid number.")
grades
average = calculate_average(grades)
return grades
highest, lowest = find_highest_lowest(grades)
# Function to calculate the average grade
# Display the results
def calculate_average(grades):
if grades:
if grades:
print("\nGrades:", grades)
average = sum(grades) / len(grades)
print("Average Grade:", average)
return average
print("Highest Grade:", highest)
else:
print("Lowest Grade:", lowest)
return None
else:
print("\nNo grades entered.")=" ")
# Function to find the highest and lowest grade
print()
def find_highest_lowest(grades):
Exp - 5(i) - To write a Python program to implement Dictionary operations and methods.
# Dictionary Operations and Methods print("\nIterating over dictionary keys:")
for key in my_dict:
# 1. Creating a Dictionary print(key)
my_dict = {
"name": "John", print("\nIterating over dictionary values:")
"age": 25, for value in my_dict.values():
"job": "Engineer" print(value)
}
print("\nIterating over dictionary items (key-
print("Initial Dictionary:", my_dict) value pairs):")
for key, value in my_dict.items():
# 2. Accessing Values by Key print(key, ":", value)
print("\nAccessing 'name':", my_dict["name"])
print("Accessing 'age':", my_dict.get("age")) # 9. Using the clear() Method to Empty the
Dictionary
# 3. Adding or Updating a Key-Value Pair my_dict.clear() # Clears the dictionary
my_dict["age"] = 26 # Update value for key print("\nDictionary after clear():", my_dict)
"age"
my_dict["city"] = "New York" # Add a new key- # 10. Copying a Dictionary
value pair my_dict = {"name": "Alice", "age": 30, "city":
print("\nUpdated Dictionary:", my_dict) "London"}
copy_dict = my_dict.copy() # Creates a shallow
# 4. Removing a Key-Value Pair copy
del my_dict["job"] # Remove "job" key print("\nOriginal Dictionary:", my_dict)
print("\nDictionary after removing 'job':", print("Copied Dictionary:", copy_dict)
my_dict)
# 11. Using fromkeys() to Create a New
# 5. Using pop() to Remove an Item and Return Dictionary from a Sequence of Keys
its Value keys = ["name", "age", "city"]
removed_value = my_dict.pop("city", "Not new_dict = dict.fromkeys(keys, "Unknown")
Found") # Returns 'Not Found' if key doesn't print("\nNew Dictionary using fromkeys():",
exist new_dict)
print("\nRemoved Value:", removed_value)
print("Dictionary after pop:", my_dict) # 12. Using update() Method to Merge Two
Dictionaries
# 6. Using popitem() to Remove and Return Last another_dict = {"job": "Designer", "age": 35}
Key-Value Pair my_dict.update(another_dict) # Merges
last_item = my_dict.popitem() # Removes the another_dict into my_dict
last inserted item print("\nDictionary after update():", my_dict)
print("\nLast Removed Item:", last_item)
print("Dictionary after popitem:", my_dict) # 13. Using setdefault() to Get a Key's Value or
Insert it with a Default Value
# 7. Checking if a Key Exists value = my_dict.setdefault("city", "Unknown")
print("\nIs 'name' a key in the dictionary?", print("\nValue for 'city':", value) # Will return
"name" in my_dict) the existing value if the key exists
print("Is 'job' a key in the dictionary?", "job" in print("Dictionary after setdefault():", my_dict)
my_dict)
# 14. Using items() to Get All Items as Tuples
# 8. Iterating Over Keys, Values, and Items print("\nAll items as tuples:", my_dict.items())
Exp - 5(j) - To write a Python program to calculate the total marks of students from their individual
subject scores stored in a dictionary, and to identify the topper
# Dictionary to store student marks in 5 subjects
# Find the topper (student with the highest total
marks = {
marks)
"Alice": {"Math": 90, "Science": 85, "English":
topper = None
88, "History": 92, "Computer": 95},
top_score = -1
"Bob": {"Math": 78, "Science": 80, "English":
85, "History": 75, "Computer": 90},
# Loop through total_marks to find the student
"Charlie": {"Math": 88, "Science": 76,
with the highest total marks
"English": 90, "History": 80, "Computer": 85},
for student, total in total_marks.items():
"David": {"Math": 95, "Science": 92, "English":
if total > top_score:
90, "History": 88, "Computer": 96}
top_score = total
}
topper = student
# Dictionary to store total marks of each student
# Display results
total_marks = {}
print("\nTotal Marks of Students:")
# Calculate total marks for each student
for student, total in total_marks.items():
for student in marks:
print(f"{student}: {total}")
total_marks[student] =
sum(marks[student].values()) # Sum all subject
print(f"\nTopper: {topper}, Score: {top_score}")
marks