Ex-03 to 05
Ex-03 to 05
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)
# 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.
# 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
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