0% found this document useful (0 votes)
3 views14 pages

Python Functions for Math Operations

The document contains a series of Python programs, each with a specific objective and overview. Each program includes input handling, core logic, and output display, covering various topics such as digit summation, prime checking, simple interest calculation, anagram checking, LCM calculation, digit reversal, quadratic roots, merge sort, lambda functions, Pascal's triangle, and a logging decorator. The author of the document is Chinmay Kaushik, with a roll number provided.

Uploaded by

xolew98301
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views14 pages

Python Functions for Math Operations

The document contains a series of Python programs, each with a specific objective and overview. Each program includes input handling, core logic, and output display, covering various topics such as digit summation, prime checking, simple interest calculation, anagram checking, LCM calculation, digit reversal, quadratic roots, merge sort, lambda functions, Pascal's triangle, and a logging decorator. The author of the document is Chinmay Kaushik, with a roll number provided.

Uploaded by

xolew98301
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

PROGRAM- 23

Objective: Write a function that takes a number as input and returns the sum of its digits.

Overview: The provided Python code defines a function called sum_of_digits that calculates
the sum of the digits of a given number. Here's how it works:

1. Input Handling: The program prompts the user to enter a number using the input()
function.
2. Sum Calculation: The function sum_of_digits takes the number as input, converts it
into a string to process each digit individually, and sums up the integer value of each
digit using a generator expression.
3. Output: After computing the sum, the result is printed to the console.

Code:
def sum_of_digits(n):
return sum(int(digit) for digit in str(n))

number = int(input("Enter a number: "))


print(sum_of_digits(number))

print("Name: Chinmay Kaushik Roll No.: 02414802722")

Output:
PROGRAM- 24
Objective: Create a function that determines whether a given integer is prime or not.

Overview:

This Python program defines a function is_prime that checks whether a given integer is
prime. The function works by:

1. Input Handling: The user is prompted to input an integer.


2. Prime Check: The function first checks if the number is less than or equal to 1 (not
prime). Then, it loops through potential divisors from 2 to the square root of the number,
checking if the number is divisible by any of them. If it is divisible, it returns False
(not prime).
3. Output: The function returns True if the number is prime and False otherwise, and
the result is displayed to the user.

Code:
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True

number = int(input("Enter a number: "))


print(is_prime(number))

print("Name: Chinmay Kaushik Roll No.: 02414802722")

Output:
PROGRAM- 25
Objective: Write a python program using functions that calculates simple interest based on
principal, rate, and time.

Overview:

This Python program defines a function calculate_simple_interest to calculate the


simple interest based on the provided principal, rate, and time. Here's how it works:

1. Input Handling: The user is prompted to enter the principal amount, interest rate, and
time period.
2. Interest Calculation: The function calculates the simple interest using the formula:
Simple Interest=Principal×Rate×Time100\text{Simple Interest} =
\frac{\text{Principal} \times \text{Rate} \times
\text{Time}}{100}Simple Interest=100Principal×Rate×Time
3. Output: The calculated simple interest is then displayed to the user.

Code:
def calculate_simple_interest(principal, rate, time):
return (principal * rate * time) / 100

principal = float(input("Enter the principal amount: "))


rate = float(input("Enter the rate of interest: "))
time = float(input("Enter the time period: "))
interest = calculate_simple_interest(principal, rate, time)
print("Simple Interest is:", interest)

print("Name: Chinmay Kaushik Roll No.: 02414802722")

Output:
PROGRAM- 26
Objective: Write a python program using functions that calculates simple interest based on
principal, rate, and time.

Overview:

This Python program defines a function are_anagrams that checks if two strings are
anagrams of each other. Here's the process:

1. Input Handling: The program prompts the user to enter two strings.
2. Anagram Check: The function sorts both strings and compares them. If the sorted
versions of the strings are identical, the strings are anagrams.
3. Output: The result (True or False) is displayed to indicate whether the two strings
are anagrams.

Code:
def are_anagrams(str1, str2):
return sorted(str1) == sorted(str2)

str1 = input("Enter the first string: ")


str2 = input("Enter the second string: ")
print(are_anagrams(str1, str2))

print("Name: Chinmay Kaushik Roll No.: 02414802722")

Output:
PROGRAM- 27
Objective: Develop a function that calculates the LCM of two numbers.

Overview:

This Python program defines a function lcm to compute the Least Common Multiple of two
numbers. Here's how it works:

1. Input Handling: The program prompts the user to enter two integers.
2. LCM Calculation: The function finds the greater of the two numbers and checks if it
is divisible by both numbers. If not, it increments the number and checks again until
the LCM is found.
3. Output: The LCM of the two numbers is displayed to the user.

Code:
def lcm(a, b):
greater = max(a, b)
while True:
if greater % a == 0 and greater % b == 0:
return greater
greater += 1

num1 = int(input("Enter the first number: "))


num2 = int(input("Enter the second number: "))
print(lcm(num1, num2))

print("Name: Chinmay Kaushik Roll No.: 02414802722")

Output:
PROGRAM- 28
Objective: Write a function that reverses the digits of a given integer.
Overview:

This Python program defines a function reverse_number that reverses the digits of a given
integer. Here's how it works:

1. Input Handling: The program prompts the user to enter an integer.


2. Reversing the Digits: The function converts the integer into a string, uses Python's
slicing feature ([::-1]) to reverse the string, and then converts it back into an integer
to remove any leading zeros.
3. Output: The reversed integer is printed as the result.

Code:
def reverse_number(n):
return int(str(n)[::-1])

number = int(input("Enter a number: "))


print(reverse_number(number))

print("Name: Chinmay Kaushik Roll No.: 02414802722")

Output:
PROGRAM- 29
Objective: Write a Python program using functions that finds the roots of a quadratic
equation using the quadratic formula.
Overview:

This Python program defines a function quadratic_roots to find the roots of a quadratic
equation of the form ax2+bx+c=0ax^2 + bx + c = 0ax2+bx+c=0. Here's the breakdown:

1. Input Handling: The program prompts the user to input the coefficients aaa, bbb, and
ccc for the quadratic equation.
2. Quadratic Formula: The function calculates the discriminant (Δ\DeltaΔ) as
b2−4acb^2 - 4acb2−4ac, and then calculates the two roots using the quadratic
formula: x=−b±b2−4ac2ax = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}x=2a−b±b2−4ac It
uses [Link]() to handle both real and complex roots (if the discriminant is
negative).
3. Output: The roots of the quadratic equation are displayed. These could be real or
complex depending on the discriminant.

Code:
import cmath
def quadratic_roots(a, b, c):
discriminant = (b**2) - (4 * a * c)
root1 = (-b + [Link](discriminant)) / (2 * a)
root2 = (-b - [Link](discriminant)) / (2 * a)
return root1, root2
a = float(input("Enter coefficient a: "))
b = float(input("Enter coefficient b: "))
c = float(input("Enter coefficient c: "))
root1, root2 = quadratic_roots(a, b, c)
print("The roots of the equation are:", root1, "and", root2)
print("Name: Chinmay Kaushik Roll No.: 02414802722")

Output:
PROGRAM- 30
Objective: Implement Merge Sort Using Recursion

Overview:

This Python program implements the Merge Sort algorithm using recursion. Here's the
breakdown:

1. Input Handling: The program prompts the user to input a list of numbers (separated
by spaces).
2. Merge Sort Logic:
o The function merge_sort recursively divides the input array into two halves
until each half contains a single element.
o After splitting, it merges the halves back together in sorted order by comparing
the elements of the two halves.
o The merging process involves three pointers: i, j, and k to traverse the left half,
right half, and the original array respectively.
3. Output: The sorted array is returned and displayed after applying the merge sort.

Code:
def merge_sort(arr):
if len(arr) > 1:
mid = len(arr) // 2
left_half = arr[:mid]
right_half = arr[mid:]

merge_sort(left_half)
merge_sort(right_half)

i=j=k=0

while i < len(left_half) and j < len(right_half):


if left_half[i] < right_half[j]:
arr[k] = left_half[i]
i += 1
else:
arr[k] = right_half[j]
j += 1
k += 1

while i < len(left_half):


arr[k] = left_half[i]
i += 1
k += 1

while j < len(right_half):


arr[k] = right_half[j]
j += 1
k += 1

return arr

arr = list(map(int, input("Enter numbers separated by space: ").split()))


print("Sorted array:", merge_sort(arr))

print("Name: Chinmay Kaushik Roll No.: 02414802722")

Output:
PROGRAM- 31
Objective: Write a lambda function that returns the square of a given number.

Overview:

This Python program defines a lambda function named square that takes a number x as
input and returns its square by performing x ** 2.

1. Input Handling: The program prompts the user to enter a number.


2. Lambda Function: The lambda function square calculates the square of the input
number.
3. Output: The square of the entered number is printed to the console.

The lambda function is a compact way to define simple functions, and in this case, it's used to
compute the square of a number efficiently.

Code:
square = lambda x: x ** 2

number = int(input("Enter a number: "))


print("The square of the number is:", square(number))

Output:
PROGRAM- 32
Objective: Write a function to print Pascal’s triangle up to 'n' rows.

Overview:

This Python program defines a function print_pascals_triangle that prints Pascal's


Triangle up to 'n' rows. Here's the breakdown:

1. Input Handling: The program prompts the user to input the number of rows (n) they
want to print in Pascal's Triangle.
2. Pascal's Triangle Logic:
o Each row starts and ends with 1.
o Every other element is the sum of the two elements directly above it from the
previous row.
o The program uses a loop to generate each row and prints it with proper spacing
for formatting.
3. Output: The program prints each row of Pascal's Triangle, formatted with spaces for
alignment.

Code:
def print_pascals_triangle(n):
for i in range(n):
row = [1] * (i + 1) # Initialize each row with the correct number of 1's
for j in range(1, i):
row[j] = row[j - 1] + row[j] # Update the elements based on the previous row
print(" " * (n - i), *row) # Print each row with spaces for alignment
n = int(input("Enter the number of rows: "))
print_pascals_triangle(n)
print("Name: Chinmay Kaushik Roll No.: 02414802722")

Output:
PROGRAM- 33
Objective: Write a decorator function that logs when a function is called.

Overview:

 Input Handling:

 The program asks the user whether they want to add two numbers or greet a person.
 Based on the user's choice, the program either asks for two numbers to add or for a
name and age to greet.

 Decorator Function:

 The log_function_call decorator is used to log the details of the function call
(arguments and keyword arguments).

 Function Execution:

 Depending on the user's choice, the program will call the decorated add or greet
function.
 The wrapper function logs the function call and then executes the original function,
returning the result.

 Output:

 The program logs the function name, arguments, and keyword arguments each time
either the add or greet function is called, and then prints the result.

Code:
def log_function_call(func):
def wrapper(*args, **kwargs):
print(f"Function {func.__name__} was called with arguments {args} and keyword
arguments {kwargs}")
return func(*args, **kwargs)
return wrapper

@log_function_call
def add(a, b):
return a + b
@log_function_call
def greet(name, age):
return f"Hello, {name}. You are {age} years old."

choice = input("Do you want to add two numbers or greet a person? (add/greet):
").strip().lower()

if choice == "add":
a = float(input("Enter the first number: "))
b = float(input("Enter the second number: "))
print("Result of addition:", add(a, b))

elif choice == "greet":


name = input("Enter your name: ")
age = int(input("Enter your age: "))
print(greet(name, age))
else:
print("Invalid choice. Please choose either 'add' or 'greet'.")
print("Name: Chinmay Kaushik Roll No.: 02414802722")

Output:

You might also like