0% found this document useful (0 votes)
19 views9 pages

Python Functions for Finance and Statistics

The document contains practical assignments that cover various programming tasks in Python, including calculating compound interest with nested functions, filtering even numbers using lambda, computing the area of a triangle, generating Fibonacci numbers, creating a custom statistics module, handling file reading errors, and implementing a custom exception for age validation. Each task is accompanied by code examples and their expected outputs. The assignments aim to enhance programming skills and understanding of Python features.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views9 pages

Python Functions for Finance and Statistics

The document contains practical assignments that cover various programming tasks in Python, including calculating compound interest with nested functions, filtering even numbers using lambda, computing the area of a triangle, generating Fibonacci numbers, creating a custom statistics module, handling file reading errors, and implementing a custom exception for age validation. Each task is accompanied by code examples and their expected outputs. The assignments aim to enhance programming skills and understanding of Python features.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Practical Assignment-2

Que.1. Implement a nested function that calculates compound


interest using non-local variables.
Ans-
def compound_interest_calculator(principal, rate, time):
interest = 0 # This will be modified by the nested function

def calculate():
nonlocal interest # Allows modifying variable from outer
function
amount = principal * (1 + rate/100) ** time
interest = amount - principal
return amount, interest

amount, interest = calculate()


return amount, interest

# Example usage
total_amount, total_interest = compound_interest_calculator(10000,
5, 2)
print("Total Amount:", total_amount)
print("Compound Interest:", total_interest)
Output-
Total Amount: 11025.0
Compound Interest: 1025.0

Que.2. Write a program using lambda to filter even numbers from a


list.
Ans-
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

even_numbers = list(filter(lambda x: x % 2 == 0, numbers))

print("Even numbers:", even_numbers)

Output-
Even numbers: [2, 4, 6, 8, 10]

Que.3. Write a program using lambda to find area of triangle.


Ans-
# Lambda function to calculate area of a triangle
area_triangle = lambda base, height: 0.5 * base * height

# Example
base = 10
height = 5
area = area_triangle(base, height)
print("Area of Triangle:", area)

Output-
Area of Triangle: 25.0

Que.4. Create a generator function to yield fibonacci numbers up to a


certain limit.
Ans-
def fibonacci(limit):
a, b = 0, 1
while a <= limit:
yield a
a, b = b, a + b

# Example usage
for num in fibonacci(50):
print(num)

Output-
0
1
1
2
3
5
8
13
21
34

Que.5. Develop a cutom python module with functions for basic


statistical operations(mean,median,mode)
Ans-
# [Link]

def mean(numbers):
return sum(numbers) / len(numbers)

def median(numbers):
numbers = sorted(numbers)
n = len(numbers)
mid = n // 2

if n % 2 == 0:
return (numbers[mid - 1] + numbers[mid]) / 2
else:
return numbers[mid]

def mode(numbers):
freq = {}
for num in numbers:
freq[num] = [Link](num, 0) + 1

max_count = max([Link]())
modes = [k for k, v in [Link]() if v == max_count]

if len(modes) == 1:
return modes[0]
return modes # returns list if more than one mode

Create another Python file (example: test_stats.py) and import your


module:
import mystats

data = [2, 4, 4, 6, 8, 4, 10]

print("Mean:", [Link](data))
print("Median:", [Link](data))
print("Mode:", [Link](data))
Output-

Mean: 5.428571428571429
Median: 4
Mode: 4

Que.6. Write a program to handle file reading errors and log them to
a seperate file.
Ans-
def read_file(filename):
try:
with open(filename, "r") as file:
data = [Link]()
print("File content:\n", data)

except FileNotFoundError as e:
log_error(str(e))
print("Error: File not found!")

except PermissionError as e:
log_error(str(e))
print("Error: Permission denied!")

except Exception as e:
log_error(str(e))
print("An unexpected error occurred.")

def log_error(message):
with open("error_log.txt", "a") as log:
[Link](message + "\n")

# Test the function


read_file("[Link]")

Output-
Error: File not found!
[Errno 2] No such file or directory: '[Link]'

Que.7. Create a custom exception class AgeException and use it to


validate user input.
Ans-
# Creating custom exception
class AgeException(Exception):
def __init__(self, message):
super().__init__(message)
def check_age():
try:
age = int(input("Enter your age: "))

if age < 0 or age > 120:


raise AgeException("Invalid age! Age must be between 0 and
120.")

print("Valid age entered:", age)

except AgeException as e:
print("Age Error:", e)

except ValueError:
print("Please enter a valid number for age.")

# Run the function


check_age()

Output-
Enter your age: 25
Valid age entered: 25s

You might also like