0% found this document useful (0 votes)
14 views

Python Lab Assingnment

The document contains a series of Python lab assignments that cover various programming tasks, including calculating simple and compound interest, determining areas and costs, classifying geometric shapes, and checking attendance for exams. Each assignment provides input prompts, sample outputs, and code snippets to illustrate the solutions. The tasks range from basic arithmetic operations to more complex logic involving conditions and functions.

Uploaded by

sudipkghs3
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)
14 views

Python Lab Assingnment

The document contains a series of Python lab assignments that cover various programming tasks, including calculating simple and compound interest, determining areas and costs, classifying geometric shapes, and checking attendance for exams. Each assignment provides input prompts, sample outputs, and code snippets to illustrate the solutions. The tasks range from basic arithmetic operations to more complex logic involving conditions and functions.

Uploaded by

sudipkghs3
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
You are on page 1/ 53

PYTHON LAB ASSIGNMENT 1

Q1.Todetermine the simple interest of a given amount of money at a


given rate of interest for a given period in years.
Ans.
Input:principal = float(input("Enter the principal amount: "))
rate = float(input("Enter the rate of simple interest (in %): "))
time = float(input("Enter the time period (in years): "))
simple_interest=(principal*rate*time)/100
print(f"The Simple Interest is: {simple_interest:.2f}")
Output:
Enter the principal amount: 6000
Enter the rate of interest (in %): 8
Enter the time period (in years): 65
The Simple Interest is: 31200.00

Q2.To determine the area of the walls of a rectangular room and hence
the cost of its painting on the basis of charge per square unit.
Ans.
Input: length = float(input("Enter the length of the room (in units):
"))
width = float(input("Enter the width of the room (in units): "))
height = float(input("Enter the height of the room (in units): "))
cost_per_unit = float(input("Enter the cost of painting per square
unit: "))
wall_area = 2 * (length * height + width * height)
total_cost = area * cost_per_unit
print(f"Total wall area to be painted: {wall_area:.2f} square units")
print(f"The total cost of painting the room: {painting_cost:.2f}
currency units")

Output:
Enter the length of the room (in units): 80
Enter the width of the room (in units): 87
Enter the height of the room (in units): 67
Enter the cost of painting per square unit: 6
Total wall area to be painted: 22378.00 square units
The total cost of painting the room: 134268.00 currency units

Q3.To determine the compound interest of a given amount of money at a


given rate of interest for a given period of years.
Ans.
Input:
principal = float(input("Enter the principal amount: "))
rate = float(input("Enter the annual rate of interest (in %): "))
PYTHON LAB ASSIGNMENT 2

time = float(input("Enter the time period (in years): "))


compounding_frequency = int(input("Enter the number of times interest
is compounded per year (e.g., 1 for annually, 4 for quarterly, 12 for
monthly): "))
amount = principal * (1 + rate / compounding_frequency) **
(compounding_frequency * time)
compound_interest = amount - principal
print(f"The Compound Interest is: {compound_interest:.2f}")

Output:
Enter the principal amount: 7900
Enter the annual rate of interest (in %): 8
Enter the time period (in years): 78
Enter the number of times interest is compounded per year (e.g., 1
for annually, 4 for quarterly, 12 for monthly): 6
The Compound Interest is: 3880017.24

Q4. To determine the net salary of an employee when it is known that


the employee is eligible to dearness allowance (DA)of 97% of the
basic pay, House Rent Allowance(HRA) of 57% of the basic pay and
medical allowance of Rs.150.It is further known that 12% of the
basic pay is deducted from the gross salary for the Employee’s
Provident Fund (EPF) and Rs.200 is deducted from the gross pay as
the professional tax.
Ans.
Input:
basic_pay = float(input("Enter the basic pay of the employee: "))
DA = 0.97 * basic_pay # 97% of basic pay
HRA = 0.57 * basic_pay # 57% of basic pay
medical_allowance = 150 # Fixed medical allowance
EPF = 0.12 * basic_pay # 12% of basic pay
professional_tax = 200 # Fixed professional tax deduction
gross_salary = basic_pay + DA + HRA + medical_allowance
net_salary = gross_salary - (EPF + professional_tax)
print(f"Gross Salary: {gross_salary:.2f}")
print(f"Net Salary: {net_salary:.2f}")

Output:
Enter the basic pay of the employee: 8900
Gross Salary: 22756.00
Net Salary: 21488.00

Q5.A program is to be developed in Python to find out the profit or


loss on a sale.
PYTHON LAB ASSIGNMENT 3

Ans.
Input:cost_price = float(input("Enter the cost price of the item: "))
selling_price = float(input("Enter the selling price of the
item: "))
if selling_price > cost_price:
profit = selling_price - cost_price
print(f"Profit of {profit:.2f} currency units")
elif selling_price < cost_price:
loss=cost_price-selling_price
print(f"Loss of {loss:.2f} currency units")
else:
print("No profit,No loss")

Output:
Enter the cost price of the item: 988
Enter the selling price of the item: 6778
Profit of 5790.00 currency units

Q6.To determine whether a quadrilateral is a square, rhombus,


parallelogram, rectangle or irregular on the basis of only
thelengths of all the sides and one internal angle.
Ans. Input:def classify_quadrilateral(a, b, c, d, angle):
"""
Function to classify a quadrilateral based on side lengths and an
internal angle.

:a: Length of the first side


:b: Length of the second side
:c: Length of the third side
:d: Length of the fourth side
:angle: One internal angle (in degrees)
:return: Type of quadrilateral
"""
if a == b == c == d:
if angle == 90:
return "Square"
else:
return "Rhombus"
elif (a == c and b == d):
if angle == 90:
return "Rectangle"
else:
return "Parallelogram"
else:
PYTHON LAB ASSIGNMENT 4

return "Irregular Quadrilateral"

# Taking input from the user


a = float(input("Enter the length of side a: "))
b = float(input("Enter the length of side b: "))
c = float(input("Enter the length of side c: "))
d = float(input("Enter the length of side d: "))
angle = float(input("Enter one internal angle (in degrees): "))
result = classify_quadrilateral(a, b, c, d, angle)
print(f"The quadrilateral is a {result}."

Output:
Enter the length of side a: 8
Enter the length of side b: 9
Enter the length of side c: 8
Enter the length of side d: 9
Enter one internal angle (in degrees): 45
The quadrilateral is a Parallelogram.

Q7.To categorize a triangle on the basis of its three given angles.


The triangle may be in an ‘invalid triangle’, ’Equiangular’,
‘ right-angle’, ‘acute angled’ or ‘obtuse angled’.
Ans.
Input:angle1 = float(input("Enter the first angle of the triangle (in
degrees): "))
angle2 = float(input("Enter the second angle of the triangle (in
degrees): "))
angle3 = float(input("Enter the third angle of the triangle (in
degrees): "))
if angle1 + angle2 + angle3 != 180 or angle1 <= 0 or angle2 <= 0 or
angle3 <= 0:
print("Invalid Triangle")
elif angle1 == 60 and angle2 == 60 and angle3 == 60:
print("Equiangular Triangle")
elif angle1 == 90 or angle2 == 90 or angle3 == 90:
print("Right-angled Triangle")
elif angle1 < 90 and angle2 < 90 and angle3 < 90:
print("Acute-angled Triangle")
else:
print("Obtuse-angled Triangle")
Output:
Enter the first angle of the triangle (in degrees): 45
Enter the second angle of the triangle (in degrees): 90
Enter the third angle of the triangle (in degrees): 45
PYTHON LAB ASSIGNMENT 5

The triangle is: Right-angled Triangle

Q8.Ask user to enter age, sex ( M or F ), marital status ( Y or N )


and then using following rules print their place of service. if
employee is female, then she will work only in urban areas. if
employee is a male and age is in between 20 to 40 then he may work in
anywhere if employee is male and age is in between 40 t0 60 then he
will work in urban areas only. And any other input of age
should print "ERROR".
Ans.
Input: age = int(input("Enter your age: "))
sex = input("Enter your sex (M/F): ")
marital_status = input("Enter your marital status (Y/N): ")
if sex.upper() == 'F':
print("You will work only in urban areas.")
elif sex.upper() == 'M'and 20 <= age <= 40:
print("You may work anywhere.")
elif sex.upper()== 'M' and 40 < age <= 60:
print("You will work only in urban areas.")
else:
print("ERROR")

Output:
Enter your age: 21
Enter your sex (M/F): M
Enter your marital status (Y/N): N
You may work anywhere.

Q9.A student will not be allowed to sit in exam if his/her attendance


is less than 75%.
Take following input from user:
Number of classes held
Number of classes attended.
Print percentage of class attended. Is student is allowed to
sit in exam or not.
Ans.
Input: classes_held = int(input("Enter the total number of
classes held: "))
classes_attended = int(input("Enter the number of classes
attended: "))
attendance_percentage = (classes_attended / classes_held) * 100
print(f"Attendance Percentage: {attendance_percentage:.2f}%")
if attendance_percentage>=75:
PYTHON LAB ASSIGNMENT 6

print("The student is allowed to sit in the exam.")


else:
print("The student is not allowed to sit in thee exam.")

Output:
Enter the total number of classes held: 90
Enter the number of classes attended: 59
Attendance Percentage: 65.56%
The student is not allowed to sit in thee exam.

Q10.In a workshop, the workers are paid on hourly basis at the end of
each week based on the total hours worked in the week. The payment
rules are as stated below:
For the first 37 hours, the rate of pay is fixed at Rs.23 per
hour;
( For the next 28 hours, the rate is Rs. 31 per hour and
( For the rest, if any, the rate is fixed at Rs, 41 per hour.
Ans.
Input: hours_worked = float(input("Enter the total hours worked
in the week: "))
if hours_worked <= 37:
total_payment = hours_worked *23
elif hours_worked <= 37 + 28:
total_payment = (37 *23) + ((hours_worked - 37) *31)
else:
total_payment = (37 *23) + (28 *31) + ((hours_worked - 65)
*41)
print(f"Total weekly payment: Rs. {total_payment:.2f}")

Output:
Enter the total hours worked in the week: 80
Total weekly payment: Rs. 2334.00

Q11.To find out the series of five consecutive numbers within 1000,
for which the sum of the squares of the first three is equal to
the sum of the squares of the last two. For example, (-2)2 +(-
1)2 +02 =12 +22
Ans.
Input: def find_consecutive_numbers():
"""
Function to find five consecutive numbers within 1000
where the sum of the squares of the first three
PYTHON LAB ASSIGNMENT 7

equals the sum of the squares of the last two.


"""
for n in range(-1000, 996): # Starting from -1000 to 995 to
ensure 5 numbers
# Five consecutive numbers
n1, n2, n3, n4, n5 = n, n + 1, n + 2, n + 3, n + 4

# Check if the sum of squares condition is met


if (n1**2 + n2**2 + n3**2) == (n4**2 + n5**2):
print(f"Series: {n1}, {n2}, {n3}, {n4}, {n5}")

# Call the function


find_consecutive_numbers()

Output:
Series: -2, -1, 0, 1, 2
Series: 10, 11, 12, 13, 14

Q12.It is required to develop a script in Python to find out the


factorial value of a positive number.
Ans.Input: def factorial(n):
"""
Function to calculate the factorial of a given positive number.

:n: A positive integer


:return: Factorial of n
"""
if n == 0 or n == 1:
return 1
else:
result = 1
for i in range(2, n + 1):
result *= i
return result

# Taking input from the user


try:
num = int(input("Enter a positive number to find its factorial:
"))

if num < 0:
print("ERROR: Please enter a positive number.”)
else:
PYTHON LAB ASSIGNMENT 8

print(f"The factorial of {num} is {factorial(num)}.")

except ValueError:
print("ERROR: Please enter a valid integer.")

Output:
Enter a positive number to find its factorial: 6
The factorial of 6 is 720.

Q13. It is required to develop a program in Python to show the


divisors of a given number.
Ans. Input:def find_divisors(n):
"""
Function to find and print all divisors of a given number.

:n: A positive integer


:return: A list of divisors of n
"""
divisors = []
for i in range(1, n + 1):
if n % i == 0:
divisors.append(i)
return divisors

# Taking input from the user


try:
num = int(input("Enter a positive number to find its divisors: "))

if num <= 0:
print("ERROR: Please enter a positive integer.")
else:
divisors = find_divisors(num)
print(f"The divisors of {num} are: {divisors}")

except ValueError:
print("ERROR: Please enter a valid integer.")

Output:
Enter a positive number to find its divisors: 68
The divisors of 68 are: [1, 2, 4, 17, 34, 68]

Q14.A number is said to be a Perfect Number if the sum of its


divisors except itself equals the number. Our aim is to develop a
PYTHON LAB ASSIGNMENT 9

python script for testing a given number as to whether it is a


perfect number or not.
Ans. Input: def is_perfect_number(n):
"""
Function to check if a given number is a perfect number.

:n: A positive integer


:return: True if the number is perfect, False otherwise
"""
if n <= 0:
return False

sum_of_divisors = 0

# Find divisors excluding the number itself


for i in range(1, n):
if n % i == 0:
sum_of_divisors += i

# Check if sum of divisors equals the number


return sum_of_divisors == n

# Taking input from the user


try:
num = int(input("Enter a positive number to check if it's a
perfect number: "))

if num <= 0:
print("ERROR: Please enter a positive integer.")
else:
if is_perfect_number(num):
print(f"{num} is a Perfect Number.")
else:
print(f"{num} is NOT a Perfect Number.")

except ValueError:
print("ERROR: Please enter a valid integer.")

Output:
Enter a positive number to check if it's a perfect number: 28
28 is a Perfect Number.

Q15. Let us develop a Python script to find out all the perfect
numbers within 10000.
PYTHON LAB ASSIGNMENT 10

Ans. Input:def is_perfect_number(n):


"""
Function to check if a number is perfect.

:n: A positive integer


:return: True if n is a perfect number, False otherwise
"""
sum_of_divisors = 1 # 1 is always a divisor

# Loop from 2 to sqrt(n) to find divisors


for i in range(2, int(n**0.5) + 1):
if n % i == 0:
sum_of_divisors += i
if i != n // i: # Avoid adding square roots twice
sum_of_divisors += n // i

return sum_of_divisors == n and n != 1 # Exclude 1 (not a


perfect number)

def find_perfect_numbers(limit):
"""
Function to find all perfect numbers up to a given limit.

:param limit: The upper limit to check for perfect numbers


:return: A list of perfect numbers within the given limit
"""
perfect_numbers = []
for num in range(2, limit + 1):
if is_perfect_number(num):
perfect_numbers.append(num)
return perfect_numbers

# Find and print perfect numbers within 10,000


perfect_numbers = find_perfect_numbers(10000)
print(f"Perfect numbers within 10,000: {perfect_numbers}")

Output:
Perfect numbers within 10,000: [6, 28, 496, 8128]

Q16.Let us now develop a Python script for finding out all the prime
numbers within a given range.
Ans. Input: def is_prime(n):
"""
Function to check if a number is prime.
PYTHON LAB ASSIGNMENT 11

:param n: A positive integer


:return: True if n is prime, False otherwise
"""
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1): # Check divisibility up to
sqrt(n)
if n % i == 0:
return False
return True

def find_prime_numbers(start, end):


"""
Function to find all prime numbers within a given range.

:start: Starting number of the range


:end: Ending number of the range
:return: A list of prime numbers within the range
"""
primes = []
for num in range(start, end + 1):
if is_prime(num):
primes.append(num)
return primes

# Taking input from the user


try:
start_range = int(input("Enter the start of the range: "))
end_range = int(input("Enter the end of the range: "))

if start_range < 0 or end_range < 0 or start_range > end_range:


print("ERROR: Please enter valid positive numbers with start
<= end.")
else:
prime_numbers = find_prime_numbers(start_range, end_range)
print(f"Prime numbers between {start_range} and {end_range}:
{prime_numbers}")

except ValueError:
print("ERROR: Please enter valid integers.")

Output:
Enter the start of the range: 45
PYTHON LAB ASSIGNMENT 12

Enter the end of the range: 254


Prime numbers between 45 and 254: [47, 53, 59, 61, 67, 71, 73, 79, 83,
89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157,
163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233,
239, 241, 251]

Q17. Narcissistic Numbers. if an n-digit number is equal to the sum


of the n th powers of its digits, then it is called an n-narcissistic
number. It is also sometimes known as an Armstrong number. For
example; 153, 1634, 558834 are such numbers. It is now required to
develop a Python script for checking whether a given number is a
Narcissistic number or not.
Ans.Input: def is_narcissistic(number):
"""
Function to check if a given number is a Narcissistic (Armstrong)
number.

:number: A positive integer


:return: True if the number is Narcissistic, False otherwise
"""
num_str = str(number) # Convert the number to a string to
extract digits
num_digits = len(num_str) # Count the number of digits

# Calculate the sum of the nth power of its digits


sum_of_powers = sum(int(digit) ** num_digits for digit in num_str)

return sum_of_powers == number

# Taking input from the user


try:
num = int(input("Enter a positive number to check if it's a
Narcissistic number: "))

if num < 0:
print("ERROR: Please enter a positive integer.")
else:
if is_narcissistic(num):
print(f"{num} is a Narcissistic (Armstrong) number.")
else:
print(f"{num} is NOT a Narcissistic (Armstrong) number.")

except ValueError:
print("ERROR: Please enter a valid integer.")
PYTHON LAB ASSIGNMENT 13

Output:
Enter a positive number to check if it's a Narcissistic number: 5767
5767 is NOT a Narcissistic (Armstrong) number.

Q18.A number is said to be a triad number if the double and triple of


the number contain all separate digits with no
repetition of any of them.
Ans.Input: def is_triad_number(n):
"""
Function to check if a number is a triad number.

:n: A positive integer


:return: True if the number is a triad number, False otherwise
"""
double_n = n * 2
triple_n = n * 3

# Convert all numbers to a single string


combined_digits = str(n) + str(double_n) + str(triple_n)

# Check if all digits are unique and exactly 9 in number


return len(combined_digits) == 9 and set(combined_digits) ==
set("123456789")

# Taking input from the user


try:
num = int(input("Enter a positive number to check if it's a Triad
number: "))

if num <= 0:
print("ERROR: Please enter a positive integer.")
else:
if is_triad_number(num):
print(f"{num} is a Triad number.")
else:
print(f"{num} is NOT a Triad number.")

except ValueError:
print("ERROR: Please enter a valid integer.")

Output:
Enter a positive number to check if it's a Triad number: 256
256 is NOT a Triad number.
PYTHON LAB ASSIGNMENT 14

Q19.Write a program to find out sum of digits of a given number.


Ans. Input: def sum_of_digits(n):
"""
Function to calculate the sum of digits of a given number.

:n: A non-negative integer


:return: Sum of the digits of the number
"""
return sum(int(digit) for digit in str(abs(n))) # Convert to
string and sum digits

# Taking input from the user


try:
num = int(input("Enter a number to find the sum of its digits: "))

sum_digits = sum_of_digits(num)
print(f"The sum of the digits of {num} is: {sum_digits}")

except ValueError:
print("ERROR: Please enter a valid integer.")
Output:
Enter a number to find the sum of its digits: 76778
The sum of the digits of 76778 is: 35

Q20.Write a program to reverse a given number.


Ans.Input: def reverse_number(n):
"""
Function to reverse the digits of a given number.

:n: An integer number (positive or negative)


:return: The reversed number
"""
sign = -1 if n < 0 else 1 # Preserve the sign of the number
reversed_num = int(str(abs(n))[::-1]) # Convert to string,
reverse, and convert back to integer
return sign * reversed_num # Restore original sign

# Taking input from the user


try:
num = int(input("Enter a number to reverse: "))

reversed_num = reverse_number(num)
print(f"The reverse of {num} is: {reversed_num}")
PYTHON LAB ASSIGNMENT 15

except ValueError:
print("ERROR: Please enter a valid integer.")
Output:
Enter a number to reverse: 8777
The reverse of 8777 is: 7778

Q21.Write a program to convert a decimal number into a binary number.


Ans. Input: def decimal_to_binary(n):
"""
Function to convert a decimal number to binary.

:n: An integer number (positive or negative)


:return: A string representing the binary equivalent of the
decimal number
"""
if n == 0:
return "0"

sign = "-" if n < 0 else "" # Handle negative numbers


n = abs(n)

binary_str = ""
while n > 0:
binary_str = str(n % 2) + binary_str # Get remainder and
build the binary string
n //= 2 # Divide by 2 for the next digit

return sign + binary_str

# Taking input from the user


try:
num = int(input("Enter a decimal number to convert to binary: "))

binary_result = decimal_to_binary(num)
print(f"The binary representation of {num} is: {binary_result}")

except ValueError:
print("ERROR: Please enter a valid integer.")
Output:
Enter a decimal number to convert to binary: 7886
The binary representation of 7886 is: 1111011001110
Q22.Write a program to calculate the sum of series:
i)X + X2 /2+ X3 /3+ ……………+Xn/n
PYTHON LAB ASSIGNMENT 16

ii)X + X2 /2! + X3 /3! + ……………+Xn/n!


Ans. Input1: def sum_of_series_1(x, n):
"""
Function to calculate the sum of the series:
X + X^2/2 + X^3/3 + ... + X^n/n

:x: The base value (X)


:n: The number of terms (n)
:return: Sum of the series
"""
series_sum = 0
for i in range(1, n + 1):
series_sum += (x ** i) / i # Compute each term
return series_sum

# Taking input from the user


try:
x = float(input("Enter the value of X: "))
n = int(input("Enter the number of terms (n): "))

if n <= 0:
print("ERROR: Number of terms should be positive.")
else:
result = sum_of_series_1(x, n)
print(f"Sum of the series X + X^2/2 + X^3/3 + ... + X^n/n is:
{result:.4f}")

except ValueError:
print("ERROR: Please enter valid numeric values.")
Output1:
Enter the value of X: 3
Enter the number of terms (n): 12
Sum of the series X + X^2/2 + X^3/3 + ... + X^n/n is: 69822.3263

Input2:import math

def sum_of_series_2(x, n):


"""
Function to calculate the sum of the series:
X + X^2/2! + X^3/3! + ... + X^n/n!

:x: The base value (X)


:n: The number of terms (n)
:return: Sum of the series
PYTHON LAB ASSIGNMENT 17

"""
series_sum = 0
for i in range(1, n + 1):
series_sum += (x ** i) / math.factorial(i) # Compute each
term using factorial
return series_sum

# Taking input from the user


try:
x = float(input("Enter the value of X: "))
n = int(input("Enter the number of terms (n): "))

if n <= 0:
print("ERROR: Number of terms should be positive.")
else:
result = sum_of_series_2(x, n)
print(f"Sum of the series X + X^2/2! + X^3/3! + ... + X^n/n!
is: {result:.4f}")

except ValueError:
print("ERROR: Please enter valid numeric values.")
Output2:
Enter the value of X: 2
Enter the number of terms (n): 25
Sum of the series X + X^2/2! + X^3/3! + ... + X^n/n! is: 6.3891

Q23.Write a program to print the following pattern:


(i)
*
**
***
****
*****
Ans.def print_pattern(rows):
"""
Function to print the pattern:
*
**
***
****
*****

:rows: Number of rows to print


"""
PYTHON LAB ASSIGNMENT 18

for i in range(1, rows + 1):


print('*' * i) # Print '*' repeated i times

# Taking input from the user


try:
n = int(input("Enter the number of rows: "))
if n <= 0:
print("ERROR: Please enter a positive integer.")
else:
print_pattern(n)
except ValueError:
print("ERROR: Please enter a valid integer.")
Output:
Enter the number of rows: 5
*
**
***
****
*****

(ii)
1
12
123
1234
12345
Ans. Input:def print_number_pattern(rows):
"""
Function to print the pattern:
1
12
123
1234
12345
...
:rows: Number of rows to print
"""
for i in range(1, rows + 1):
for j in range(1, i + 1):
print(j, end="") # Print numbers in a row
print() # Move to the next line

# Taking input from the user


try:
PYTHON LAB ASSIGNMENT 19

n = int(input("Enter the number of rows: "))


if n <= 0:
print("ERROR: Please enter a positive integer.")
else:
print_number_pattern(n)
except ValueError:
print("ERROR: Please enter a valid integer.")
Output:
Enter the number of rows: 5
1
12
123
1234
12345

(iii)
*
**
***
****
*****
Ans. Input: def print_right_aligned_pattern(rows):
"""
Function to print a right-aligned star pattern.

:rows: Number of rows to print


"""
for i in range(1, rows + 1):
print(' ' * (rows - i) + '*' * i) # Print spaces followed by
stars

# Taking input from the user


try:
n = int(input("Enter the number of rows: "))
if n <= 0:
print("ERROR: Please enter a positive integer.")
else:
print_right_aligned_pattern(n)
except ValueError:
print("ERROR: Please enter a valid integer.")
Output:
Enter the number of rows: 5
*
**
***
PYTHON LAB ASSIGNMENT 20

****
*****

(iv)
*
***
*****
*******
*********
Ans. Input: def print_pyramid_pattern(rows):
"""
Function to print a pyramid star pattern.

:rows: Number of rows to print


"""
for i in range(1, rows + 1):
spaces = ' ' * (rows - i) # Leading spaces to center the
stars
stars = '*' * (2 * i - 1) # Stars pattern for each row (1, 3,
5, ...)
print(spaces + stars)

# Taking input from the user


try:
n = int(input("Enter the number of rows: "))
if n <= 0:
print("ERROR: Please enter a positive integer.")
else:
print_pyramid_pattern(n)
except ValueError:
print("ERROR: Please enter a valid integer.")
Output:
Enter the number of rows: 5
*
***
*****
*******
*********

(V)
*********
*******
*****
***
PYTHON LAB ASSIGNMENT 21

*
Ans. Input: def print_inverted_pyramid_pattern(rows):
"""
Function to print an inverted pyramid star pattern.

:rows: Number of rows to print


"""
for i in range(rows, 0, -1):
spaces = ' ' * (rows - i) # Leading spaces for alignment
stars = '*' * (2 * i - 1) # Stars pattern for each row (9, 7,
5, 3, 1)
print(spaces + stars)

# Taking input from the user


try:
n = int(input("Enter the number of rows: "))
if n <= 0:
print("ERROR: Please enter a positive integer.")
else:
print_inverted_pyramid_pattern(n)
except ValueError:
print("ERROR: Please enter a valid integer.")
Output:Enter the number of rows: 5
*********
*******
*****
***
*

(vi)
1
121
12321
1234321
123454321
Ans.Input: def print_number_pyramid(rows):
"""
Function to print a number pyramid pattern.

:rows: Number of rows to print


"""
for i in range(1, rows + 1):
# Print leading spaces
spaces = ' ' * (rows - i)
PYTHON LAB ASSIGNMENT 22

# Print increasing numbers


increasing_numbers = ''.join(str(x) for x in range(1, i + 1))

# Print decreasing numbers


decreasing_numbers = ''.join(str(x) for x in range(i - 1, 0,
-1))

# Combine spaces, increasing numbers, and decreasing numbers


print(spaces + increasing_numbers + decreasing_numbers)

# Taking input from the user


try:
n = int(input("Enter the number of rows: "))
if n <= 0:
print("ERROR: Please enter a positive integer.")
else:
print_number_pyramid(n)
except ValueError:
print("ERROR: Please enter a valid integer.")
Output:
Enter the number of rows: 5
1
121
12321
1234321
123454321

(vii)
*
***
*****
*******
*********
*******
*****
***
*
Ans. Input: def print_diamond_pattern(rows):
"""
Function to print a diamond-shaped star pattern.

:rows: Number of rows for the top half of the diamond


"""
PYTHON LAB ASSIGNMENT 23

# Print the top half of the diamond


for i in range(1, rows + 1):
spaces = ' ' * (rows - i) # Leading spaces
stars = '*' * (2 * i - 1) # Stars pattern (1, 3, 5, 7, ...)
print(spaces + stars)

# Print the bottom half of the diamond


for i in range(rows - 1, 0, -1):
spaces = ' ' * (rows - i) # Leading spaces
stars = '*' * (2 * i - 1) # Stars pattern (odd number of
stars)
print(spaces + stars)

# Taking input from the user


try:
n = int(input("Enter the number of rows for the top half of the
diamond: "))
if n <= 0:
print("ERROR: Please enter a positive integer.")
else:
print_diamond_pattern(n)
except ValueError:
print("ERROR: Please enter a valid integer.")
Output:
Enter the number of rows for the top half of the diamond: 5
*
***
*****
*******
*********
*******
*****
***
*

(viii)
*
**
***
****
******
*****
***
**
PYTHON LAB ASSIGNMENT 24

*
Ans. Input: def print_pattern(rows):
"""
Function to print the pattern:

*
**
***
****
*****
****
***
**
*

:rows: Number of rows to print for the top half of the pattern
"""
# Print the top half of the pattern (increasing stars)
for i in range(1, rows + 1):
print('*' * i)

# Print the bottom half of the pattern (decreasing stars)


for i in range(rows - 1, 0, -1):
print('*' * i)

# Taking input from the user


try:
n = int(input("Enter the number of rows for the top half of the
pattern: "))
if n <= 0:
print("ERROR: Please enter a positive integer.")
else:
print_pattern(n)
except ValueError:
print("ERROR: Please enter a valid integer.")
Output:
Enter the number of rows for the top half of the pattern: 5
*
**
***
****
*****
****
***
PYTHON LAB ASSIGNMENT 25

**
*

Q24.Write a program to print the following patterns:


(i)
*
* *
* *
* *
* *
* *
* *
* *
*
Ans. Input:def print_diamond_pattern(rows):
"""
Function to print a diamond-like pattern with stars.

:rows: Number of rows for the top half of the diamond


"""
# Print the top half of the pattern
for i in range(1, rows + 1):
spaces = ' ' * (rows - i) # Leading spaces
stars = ' ' * (2 * i - 1) # Spaces between stars
if i == 1:
print(spaces + '*') # The first row has a single star
else:
print(spaces + '*' + ' ' * (2 * i - 3) + '*') # Stars on
both sides

# Print the bottom half of the pattern


for i in range(rows - 1, 0, -1):
spaces = ' ' * (rows - i) # Leading spaces
stars = ' ' * (2 * i - 1) # Spaces between stars
if i == 1:
print(spaces + '*') # The last row has a single star
else:
print(spaces + '*' + ' ' * (2 * i - 3) + '*') # Stars on
both sides

# Taking input from the user


try:
n = int(input("Enter the number of rows for the top half of the
pattern: "))
PYTHON LAB ASSIGNMENT 26

if n <= 0:
print("ERROR: Please enter a positive integer.")
else:
print_diamond_pattern(n)
except ValueError:
print("ERROR: Please enter a valid integer.")
Output:
Enter the number of rows for the top half of the pattern: 5
*
* *
* *
* *
* *
* *
* *
* *
*

(ii)
A
AB
ABC
ABCD
ABCDE
Ans. Input: def print_alphabet_pattern(rows):
"""
Function to print the alphabet pattern.

:param rows: Number of rows to print


"""
for i in range(1, rows + 1):
print(''.join(chr(65 + j) for j in range(i))) # Print
letters from 'A' to the i-th letter

# Taking input from the user


try:
n = int(input("Enter the number of rows: "))
if n <= 0:
print("ERROR: Please enter a positive integer.")
else:
print_alphabet_pattern(n)
except ValueError:
print("ERROR: Please enter a valid integer.")
Output:
PYTHON LAB ASSIGNMENT 27

Enter the number of rows: 5


A
AB
ABC
ABCD
ABCDE

(iii)
A
AB
ABC
ABCD
ABCDE
Ans. Input: def print_right_aligned_alphabet_pattern(rows):
"""
Function to print a right-aligned alphabet pattern.

:rows: Number of rows to print


"""
for i in range(1, rows + 1):
spaces = ' ' * (rows - i) # Leading spaces to align the
pattern
alphabets = ''.join(chr(65 + j) for j in range(i)) #
Generating the letters from 'A' to the i-th letter
print(spaces + alphabets) # Combine spaces and letters to
form the desired pattern

# Taking input from the user


try:
n = int(input("Enter the number of rows: "))
if n <= 0:
print("ERROR: Please enter a positive integer.")
else:
print_right_aligned_alphabet_pattern(n)
except ValueError:
print("ERROR: Please enter a valid integer.")
Output:
Enter the number of rows: 5
A
AB
ABC
ABCD
ABCDE
PYTHON LAB ASSIGNMENT 28

Q25.Write a function to determine the minimum number of 100 rupee


notes, 200 rupee notes, 500 rupee notes and 2000 rupee notes required
to dispense a given sum of money.
Ans. Input: def minimum_notes(amount):
"""
Function to determine the minimum number of 100, 200, 500, and
2000 rupee notes required to dispense the given sum.

:amount: The total amount of money to be dispensed


"""
# Initialize the number of notes
notes_2000 = amount // 2000
amount = amount % 2000

notes_500 = amount // 500


amount = amount % 500

notes_200 = amount // 200


amount = amount % 200

notes_100 = amount // 100


amount = amount % 100

# If the remaining amount is not zero, it means the amount cannot


be dispensed using the available notes
if amount != 0:
print("ERROR: The amount cannot be dispensed exactly with 100,
200, 500, and 2000 rupee notes.")
return

# Output the number of notes for each denomination


print("Minimum number of notes:")
print(f"2000 Rupee Notes: {notes_2000}")
print(f"500 Rupee Notes: {notes_500}")
print(f"200 Rupee Notes: {notes_200}")
print(f"100 Rupee Notes: {notes_100}")

# Taking input from the user


try:
amount = int(input("Enter the amount of money: "))
if amount < 0:
print("ERROR: The amount cannot be negative.")
else:
PYTHON LAB ASSIGNMENT 29

minimum_notes(amount)
except ValueError:
print("ERROR: Please enter a valid integer.")
Output:
Enter the amount of money: 25600
Minimum number of notes:
2000 Rupee Notes: 12
500 Rupee Notes: 3
200 Rupee Notes: 0
100 Rupee Notes: 1

Q26.An abundant number is a number that is smaller than the sum of


its aliquot parts (proper divisors). Twelve is the smallest abundant
number – the sum of its aliquot parts is 1 + 2 + 3 + 4 + 6 = 16 –
followed by 18, 20, 24, and 30. Write a function to check whether a
given number is abundant number or not.

Ans. Input: def is_abundant_number(number):


"""
Function to check if a given number is an abundant number.

:number: The number to check for abundance


:return: True if the number is abundant, otherwise False
"""
if number <= 0:
return False

# Find proper divisors of the number (excluding the number itself)


divisors_sum = 0
for i in range(1, number):
if number % i == 0:
divisors_sum += i

# Check if the sum of divisors is greater than the number


if divisors_sum > number:
return True
else:
return False

# Taking input from the user


try:
num = int(input("Enter a number: "))
if num <= 0:
print("ERROR: Please enter a positive integer.")
PYTHON LAB ASSIGNMENT 30

else:
if is_abundant_number(num):
print(f"{num} is an abundant number.")
else:
print(f"{num} is not an abundant number.")
except ValueError:
print("ERROR: Please enter a valid integer.")
Output:
Enter a number: 30
30 is an abundant number.

Q27.An automorphic number, also known as an automorph, is a number n


whose square ends in n. For instance 5 is automorphic, because 52 =
25, which ends in 5. Write a function to check whether a given number
is automorphic number or not.

Ans. Input: def is_automorphic_number(number):


"""
Function to check if a given number is an automorphic number.

:number: The number to check for being automorphic


:return: True if the number is automorphic, otherwise False
"""
# Calculate the square of the number
square = number ** 2

# Convert both the number and its square to strings


number_str = str(number)
square_str = str(square)

# Check if the square ends with the number itself


if square_str.endswith(number_str):
return True
else:
return False

# Taking input from the user


try:
num = int(input("Enter a number: "))
if num < 0:
print("ERROR: Please enter a non-negative integer.")
else:
if is_automorphic_number(num):
print(f"{num} is an automorphic number.")
PYTHON LAB ASSIGNMENT 31

else:
print(f"{num} is not an automorphic number.")
except ValueError:
print("ERROR: Please enter a valid integer.")
Output:
Enter a number: 25
25 is an automorphic number.

Q28.A Harshad number is a number that is divisible by the sum of its


own digits. For example, 1729 is a Harshad number because 1 + 7 + 2 +
9 = 19 and 1729 = 19 × 91. Harshad numbers are also known as Niven
numbers. Write a function to check whether a given number is
Harshad number or not.
Ans. Input: def is_harshad_number(number):
"""
Function to check if a given number is a Harshad (Niven) number.

:number: The number to check for being a Harshad number


:return: True if the number is a Harshad number, otherwise False
"""
# Convert the number to a string to extract digits
digits = [int(digit) for digit in str(number)]

# Calculate the sum of the digits


sum_of_digits = sum(digits)

# Check if the number is divisible by the sum of its digits


if sum_of_digits == 0:
return False # Prevent division by zero
elif number % sum_of_digits == 0:
return True
else:
return False

# Taking input from the user


try:
num = int(input("Enter a number: "))
if num <= 0:
print("ERROR: Please enter a positive integer.")
else:
if is_harshad_number(num):
print(f"{num} is a Harshad number.")
else:
print(f"{num} is not a Harshad number.")
PYTHON LAB ASSIGNMENT 32

except ValueError:
print("ERROR: Please enter a valid integer.")
Output:
Enter a number: 81
81 is a Harshad number.

Q29.Write a Python function to find the maximum of three numbers.


Ans. Input: def find_max_of_three(num1, num2, num3):
"""
Function to find the maximum of three numbers.

:num1: First number


:num2: Second number
:num3: Third number
:return: The maximum of the three numbers
"""
# Using the built-in max() function to find the maximum
return max(num1, num2, num3)

# Taking input from the user


try:
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
num3 = float(input("Enter the third number: "))

print(f"The maximum number is: {find_max_of_three(num1, num2,


num3)}")
except ValueError:
print("ERROR: Please enter valid numbers.")
Output:
Enter the first number: 66
Enter the second number: 87
Enter the third number: 94
The maximum number is: 94.0

Q30.Write a Python function to sum all the numbers in a list.


Ans. Input: def sum_of_list(numbers):
"""
Function to sum all the numbers in a list.

:numbers: List of numbers to sum


:return: Sum of all the numbers in the list
"""
return sum(numbers)
PYTHON LAB ASSIGNMENT 33

# Taking input from the user


try:
# Accepting a list of numbers from the user
numbers = list(map(int, input("Enter numbers separated by spaces:
").split()))

print(f"The sum of the numbers in the list is:


{sum_of_list(numbers)}")
except ValueError:
print("ERROR: Please enter valid numbers.")
Output:
Enter numbers separated by spaces: 34 56 78 89 90 654
The sum of the numbers in the list is: 1001

Q31.Write a Python function to multiply all the numbers in a list.


Ans. Input: def multiply_of_list(numbers):
"""
Function to multiply all the numbers in a list.

:numbers: List of numbers to multiply


:return: Product of all the numbers in the list
"""
product = 1
for number in numbers:
product *= number
return product

# Taking input from the user


try:
# Accepting a list of numbers from the user
numbers = list(map(int, input("Enter numbers separated by spaces:
").split()))

print(f"The product of the numbers in the list is:


{multiply_of_list(numbers)}")
except ValueError:
print("ERROR: Please enter valid numbers.")
Output:
Enter numbers separated by spaces: 46 76 4 56 76
The product of the numbers in the list is: 59515904

Q32.Write a Python function to check whether a number falls


within a given range.
PYTHON LAB ASSIGNMENT 34

Ans. Input: def is_within_range(number, start, end):


"""
Function to check whether a number falls within a given range
(inclusive).

:number: The number to check


:start: The starting value of the range
:end: The ending value of the range
:return: True if the number is within the range, otherwise False
"""
return start <= number <= end

# Taking input from the user


try:
number = float(input("Enter the number to check: "))
start = float(input("Enter the start of the range: "))
end = float(input("Enter the end of the range: "))

if is_within_range(number, start, end):


print(f"{number} falls within the range [{start}, {end}].")
else:
print(f"{number} does not fall within the range [{start},
{end}].")
except ValueError:
print("ERROR: Please enter valid numbers.")
Output:
Enter the number to check: 45
Enter the start of the range: 34
Enter the end of the range: 50
45.0 falls within the range [34.0, 50.0].

Q33.Write a Python program to print the even numbers from


a given list.
Ans. Input: def print_even_numbers(numbers):
"""
Function to print the even numbers from a given list.

:numbers: List of numbers to check


:return: List of even numbers
"""
even_numbers = [num for num in numbers if num % 2 == 0]
return even_numbers

# Taking input from the user


PYTHON LAB ASSIGNMENT 35

try:
# Accepting a list of numbers from the user
numbers = list(map(int, input("Enter numbers separated by spaces:
").split()))

even_numbers = print_even_numbers(numbers)

if even_numbers:
print("Even numbers from the given list:", even_numbers)
else:
print("No even numbers found in the list.")
except ValueError:
print("ERROR: Please enter valid numbers.")

Output:
Enter numbers separated by spaces: 4 576 74 87 76 443 76 89 90
Even numbers from the given list: [4, 576, 74, 76, 76, 90]

Q34.Write a Python function to create and print a list where the


values are the squares of numbers between 5 and 25.
Ans. Input: def squares_list(start=5, end=25):
"""
Function to generate and print a list of squares of numbers
between 5 and 25.

:start: Start of the range (default is 5)


:end: End of the range (default is 25)
:return: List of squared values
"""
squared_numbers = [num ** 2 for num in range(start, end + 1)]
return squared_numbers

# Generate and print the list of squares


squares = squares_list()
print("Squares of numbers from 5 to 25:", squares)

Output:
Squares of numbers from 5 to 25: [25, 36, 49, 64, 81, 100, 121, 144,
169, 196, 225, 256, 289, 324, 361, 400, 441, 484, 529, 576, 625]

Q35.Write a Python function to calculate the factorial of a number.


Ans. Input: def factorial(n):
"""
Function to calculate the factorial of a number.
PYTHON LAB ASSIGNMENT 36

:n: The number to calculate the factorial for (must be a non-


negative integer)
:return: Factorial of the number
"""
if n < 0:
return "Factorial is not defined for negative numbers."
elif n == 0 or n == 1:
return 1
else:
result = 1
for i in range(2, n + 1):
result *= i
return result

# Taking input from the user


try:
num = int(input("Enter a non-negative integer: "))
print(f"Factorial of {num} is: {factorial(num)}")
except ValueError:
print("ERROR: Please enter a valid non-negative integer.")
Output:
Enter a non-negative integer: 12
Factorial of 12 is: 479001600

Q36.Write a Python function to find the out a^b.


Ans. def power(a, b):
"""
Function to calculate a^b (a raised to the power of b).

:a: Base number


:b: Exponent
:return: The result of a raised to the power of b
"""
return a ** b

# Taking input from the user


try:
a = float(input("Enter the base (a): "))
b = int(input("Enter the exponent (b): "))

print(f"{a}^{b} = {power(a, b)}")


except ValueError:
print("ERROR: Please enter valid numbers.")
PYTHON LAB ASSIGNMENT 37

Output:
Enter the base (a): 6
Enter the exponent (b): 5
6.0^5 = 7776.0

Q37.Write a Python function to show the use of global and


local variable.
Ans. Input: # Global variable
x = 10

def demonstrate_scope():
# Local variable
x = 5 # This is a local variable inside the function
print("Inside the function, local x =", x)

def modify_global():
global x # Access the global variable inside the function
x = 20 # Modify the global variable
print("Inside modify_global function, global x =", x)

# Call the functions


print("Before calling functions, global x =", x)
demonstrate_scope()
print("After calling demonstrate_scope, global x remains =", x)
modify_global()
print("After calling modify_global, global x =", x)
Output:
Before calling functions, global x = 10
Inside the function, local x = 5
After calling demonstrate_scope, global x remains = 10
Inside modify_global function, global x = 20
After calling modify_global, global x = 20

Q38.Write a Python function to show the use of global statement.


Ans. Input: # Global variable
counter = 0

def increment_counter():
"""
Function to increment the global variable 'counter' using the
global statement.
"""
global counter # Using the global keyword to modify the global
variable
PYTHON LAB ASSIGNMENT 38

counter += 1
print("Counter inside function after increment:", counter)

# Function call
print("Initial counter value:", counter)
increment_counter()
increment_counter()
print("Final counter value:", counter)

Output:
nitial counter value: 0
Counter inside function after increment: 1
Counter inside function after increment: 2
Final counter value: 2

Q39.Write a Python function to show the use of keyword argument.


Ans. Input: def introduce_person(name, age, city="Unknown"):
"""
Function to introduce a person using keyword arguments.

:name: Name of the person


:age: Age of the person
:city: City where the person lives (default is 'Unknown')
"""
print(f"Hello, my name is {name}, I am {age} years old, and I
live in {city}.")

# Calling the function using keyword arguments


introduce_person(name="Sudip", age=19, city="Kolkata")
introduce_person(age=20, name="Suvendu",city="Kolkata")
introduce_person(city="Kolkata", name="Sovan", age=22)
Output:
Hello, my name is Sudip, I am 19 years old, and I live in Kolkata.
Hello, my name is Suvendu, I am 20 years old, and I live in Kolkata.
Hello, my name is Sovan, I am 22 years old, and I live in Kolkata.

Q40.Write a Python function to show the use of default argument.


Ans.Input: def greet(name, message="Hello"):
"""
Function to greet a person with a default message if no custom
message is provided.

:name: Name of the person


:message: Greeting message (default is 'Hello')
PYTHON LAB ASSIGNMENT 39

"""
print(f"{message}, {name}!")

# Calling the function with and without providing the default


argument
greet("Sudip") # Uses default message "Hello"
greet("Sovan", "Good morning") # Provides a custom greeting message
greet("Suvendu", "Welcome")

Output:
Hello, Sudip!
Good morning, Sovan!
Welcome, Suvendu!

Q41.Write a function to show the use of variable length arguments.


Ans.Input:

def variable_length_demo(*args, **kwargs):


"""
Function to demonstrate the use of variable-length arguments.

:args: Non-keyword (positional) variable arguments


:kwargs: Keyword variable arguments
"""
print("Positional arguments (*args):")
for arg in args:
print(arg)

print("\nKeyword arguments (**kwargs):")


for key, value in kwargs.items():
print(f"{key} = {value}")

# Calling the function with different numbers of arguments


variable_length_demo(1, 2, 3, 4, 5, name="Sudip", age=19,
city="Kolkata")

print("\nCalling with different arguments:")


variable_length_demo("Python", "Java", "C++", framework="Django",
version=3.9)
Output:
Positional arguments (*args):
1
2
3
PYTHON LAB ASSIGNMENT 40

4
5

Keyword arguments (**kwargs):


name = Sudip
age = 19
city = Kolkata

Calling with different arguments:


Positional arguments (*args):
Python
Java
C++

Keyword arguments (**kwargs):


framework = Django
version = 3.9

Q42.Write a recursive function to calculate factorial of a


given number.
Ans.Input: def factorial_recursive(n):
"""
Recursive function to calculate the factorial of a number.

:n: The number to calculate the factorial for


:return: Factorial of the number
"""
# Base case: factorial of 0 or 1 is 1
if n == 0 or n == 1:
return 1
else:
# Recursive case: n * factorial of (n-1)
return n * factorial_recursive(n - 1)

# Taking input from the user


try:
num = int(input("Enter a non-negative integer: "))
if num < 0:
print("ERROR: Factorial is not defined for negative numbers.")
else:
print(f"Factorial of {num} is: {factorial_recursive(num)}")
except ValueError:
print("ERROR: Please enter a valid non-negative integer.")
Output:
PYTHON LAB ASSIGNMENT 41

Enter a non-negative integer: 9


Factorial of 9 is: 362880

Q43.Write a recursive function to calculate X^Y.


Ans.Input:def power_recursive(x, y):
"""
Recursive function to calculate x raised to the power y (x^y).

:x: The base number


:y: The exponent
:return: x raised to the power y
"""
# Base case: if exponent is 0, x^0 is 1
if y == 0:
return 1
# Recursive case: x^y = x * x^(y-1)
else:
return x * power_recursive(x, y - 1)

# Taking input from the user


try:
x = float(input("Enter the base number (X): "))
y = int(input("Enter the exponent number (Y): "))

# Checking for negative exponent handling


if y < 0:
print(f"{x}^{y} = {1 / power_recursive(x, -y)}")
else:
print(f"{x}^{y} = {power_recursive(x, y)}")
except ValueError:
print("ERROR: Please enter valid numbers.")
Output:
Enter the base number (X): 8
Enter the exponent number (Y): 4
8.0^4 = 4096.0

Q44.Write a recursive function to display Fibonacci series


up to n terms.
Ans.Input: def fibonacci_recursive(n, a=0, b=1):
"""
Recursive function to display Fibonacci series up to n terms.

:n: Number of terms to display in the Fibonacci series


:a: First number in the Fibonacci series (default is 0)
PYTHON LAB ASSIGNMENT 42

:b: Second number in the Fibonacci series (default is 1)


"""
if n <= 0:
return
else:
print(a, end=" ")
fibonacci_recursive(n - 1, b, a + b)

# Taking input from the user


try:
n = int(input("Enter the number of terms for the Fibonacci series:
"))
if n <= 0:
print("ERROR: Please enter a positive integer greater than
0.")
else:
print(f"Fibonacci series up to {n} terms:")
fibonacci_recursive(n)
except ValueError:
print("ERROR: Please enter a valid integer.")
Output:
Enter the number of terms for the Fibonacci series: 14
Fibonacci series up to 14 terms:
0 1 1 2 3 5 8 13 21 34 55 89 144 233

Q45.Write a user defined function by which you can calculate length


of a given string.
Ans.Input: def string_length(s):
"""
Function to calculate the length of a given string.

:s: The string whose length is to be calculated


:return: Length of the string
"""
length = 0
for char in s:
length += 1
return length

# Taking input from the user


user_input = input("Enter a string to calculate its length: ")
print(f"The length of the string is: {string_length(user_input)}")
Output:
Enter a string to calculate its length: Beautiful
PYTHON LAB ASSIGNMENT 43

The length of the string is: 9

Q46.Write a function to remove vowels from a given string. After that


display the new string.
Ans. Input: def remove_vowels(s):
"""
Function to remove vowels from a given string.

:s: The string from which vowels are to be removed


:return: New string with vowels removed
"""
vowels = "aeiouAEIOU" # List of vowels (both lowercase and
uppercase)
result = ''.join([char for char in s if char not in vowels])
return result

# Taking input from the user


user_input = input("Enter a string to remove vowels: ")
new_string = remove_vowels(user_input)

# Displaying the new string


print(f"The string after removing vowels: {new_string}")
Output:
Enter a string to remove vowels: Pschycology
The string after removing vowels: Pschyclgy

Q47.Write a function to remove digits from a given string. After that


display the new string.
Ans. Input: def remove_digits(s):
"""
Function to remove digits from a given string.

:s: The string from which digits are to be removed


:return: New string with digits removed
"""
result = ''.join([char for char in s if not char.isdigit()])
return result

# Taking input from the user


user_input = input("Enter a string to remove digits: ")
new_string = remove_digits(user_input)

# Displaying the new string


print(f"The string after removing digits: {new_string}")
PYTHON LAB ASSIGNMENT 44

Output:
Enter a string to remove digits: Good2355 Morning567887
The string after removing digits: Good Morning

Q48.Write a program to count number of vowels in a given string.


Ans.Input: def count_vowels(s):
"""
Function to count the number of vowels in a given string.

:s: The string in which vowels need to be counted


:return: Number of vowels in the string
"""
vowels = "aeiouAEIOU" # List of vowels (both lowercase and
uppercase)
count = 0

for char in s:
if char in vowels:
count += 1

return count

# Taking input from the user


user_input = input("Enter a string to count vowels: ")
vowel_count = count_vowels(user_input)

# Displaying the result


print(f"The number of vowels in the string is: {vowel_count}")
Output:
Enter a string to count vowels: Education
The number of vowels in the string is: 5

Q49.A program is required to be developed for abbreviating a string


as illustrated below:
Damodar Valley Corporation will be abbreviated to DVC.
Ans.Input: def abbreviate_string(s):
"""
Function to abbreviate a string by taking the first letter of
each word.

:s: The input string to abbreviate


:return: Abbreviated string
"""
words = s.split() # Split the string into words
PYTHON LAB ASSIGNMENT 45

abbreviation = ''.join([word[0].upper() for word in words]) #


Take the first letter of each word
return abbreviation

# Taking input from the user


user_input = input("Enter a string to abbreviate: ")
abbreviated = abbreviate_string(user_input)

# Displaying the result


print(f"The abbreviated form is: {abbreviated}")

Output:
Enter a string to abbreviate: Damodar Valley Corporation
The abbreviated form is: DVC

Q50.A program is required to be developed for abbreviating a string


as illustrated below:
Tapas Kumar Das will become T. K. Das
Ranit Saha will become R. Saha
Ans.Input: def abbreviate_name(name):
"""
Function to abbreviate a name such that only the first letter of
first and middle names
are taken, followed by the full last name.

:name: The full name to abbreviate


:return: Abbreviated name
"""
# Split the name into words
name_parts = name.split()

# Abbreviate first and middle names


abbreviated = [part[0].upper() + '.' for part in name_parts[:-1]]
# First and middle names
abbreviated.append(name_parts[-1]) # Last name (full)

# Join the parts and return the abbreviated name


return ' '.join(abbreviated)

# Taking input from the user


user_input = input("Enter a full name to abbreviate: ")
abbreviated_name = abbreviate_name(user_input)

# Displaying the result


PYTHON LAB ASSIGNMENT 46

print(f"The abbreviated name is: {abbreviated_name}")


Output:
Enter a full name to abbreviate: Tapas Kumar Das
The abbreviated name is: T. K. Das

Q51.A program is required to be developed to test whether a given


word is a palindrome or not.
Ans.Input: def is_palindrome(word):
"""
Function to check whether a given word is a palindrome.

:word: The word to be checked


:return: True if the word is a palindrome, False otherwise
"""
# Converting the word to lowercase to make the check case-
insensitive
word = word.lower()

# Checking if the word is equal to its reverse


if word == word[::-1]:
return True
else:
return False

# Taking input from the user


user_input = input("Enter a word to check if it's a palindrome: ")

# Checking if the word is a palindrome


if is_palindrome(user_input):
print(f"{user_input} is a palindrome.")
else:
print(f"{user_input} is not a palindrome.")
Output:
Enter a word to check if it's a palindrome: Good
Good is not a palindrome.

Q52.Develop a program that prompts the user to input a string, then


create and display a new string which will contain each letter of
the string tripled and separated by space. For instance, if the
input is CAT, the output would be
CCC AAA TTT .
Ans.Input: def triple_and_separate(s):
"""
PYTHON LAB ASSIGNMENT 47

Function to triple each letter of the string and separate them by


spaces.

:s: The input string


:return: New string with each letter tripled and separated by
spaces
"""
result = ' '.join([char * 3 for char in s]) # Triple each
character and join with spaces
return result

# Taking input from the user


user_input = input("Enter a string: ")

# Creating and displaying the new string


new_string = triple_and_separate(user_input)
print(f"The new string is: {new_string}")

Output:
Enter a string: WORST
The new string is: WWW OOO RRR SSS TTT

Q53.Write a program to show the use of filter().


Ans.Input: def is_even(num):
"""
Function to check if a number is even.

:num: The number to be checked


:return: True if the number is even, False otherwise
"""
return num % 2 == 0

# List of numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Using filter() to get all even numbers


even_numbers = filter(is_even, numbers)

# Converting the filter object to a list and displaying the result


even_numbers_list = list(even_numbers)
print("Even numbers:", even_numbers_list)
Output:
Even numbers: [2, 4, 6, 8, 10]
Q54.Write a program to show the use of map().
PYTHON LAB ASSIGNMENT 48

Ans.Input: def square(num):


"""
Function to return the square of a number.

:num: The number to be squared


:return: The square of the number
"""
return num ** 2

# List of numbers
numbers = [1, 2, 3, 4, 5]

# Using map() to apply the square function to each element in the


list
squared_numbers = map(square, numbers)

# Converting the map object to a list and displaying the result


squared_numbers_list = list(squared_numbers)
print("Squared numbers:", squared_numbers_list)

Output:
Squared numbers: [1, 4, 9, 16, 25]

Q55.Write a program to create user defind dictionary,then add new


data,modify data and remove data then display.
Ans.Input: def create_and_modify_dict():
# Step 1: Create a user-defined dictionary
user_dict = {
'name': 'Sudip',
'age': 19,
'city': 'Kolkata'
}

# Displaying the original dictionary


print("Original dictionary:", user_dict)

# Step 2: Add new data to the dictionary


user_dict['occupation'] = 'Student'
print("Dictionary after adding new data:", user_dict)

# Step 3: Modify existing data in the dictionary


user_dict['age'] = 30 # Updating age
print("Dictionary after modifying data:", user_dict)
PYTHON LAB ASSIGNMENT 49

# Step 4: Remove data from the dictionary


user_dict.pop('city') # Removing 'city' key
print("Dictionary after removing data:", user_dict)

# Step 5: Display the final dictionary


print("Final dictionary:", user_dict)

# Calling the function to demonstrate


create_and_modify_dict()

Output:
Original dictionary: {'name': 'Sudip', 'age': 19, 'city': 'Kolkata'}
Dictionary after adding new data: {'name': 'Sudip', 'age': 19, 'city':
'Kolkata', 'occupation': 'Student'}
Dictionary after modifying data: {'name': 'Sudip', 'age': 30, 'city':
'Kolkata', 'occupation': 'Student'}
Dictionary after removing data: {'name': 'Sudip', 'age': 30,
'occupation': 'Student'}
Final dictionary: {'name': 'Sudip', 'age': 30, 'occupation':
'Student'}

Q56.Write a program to read a text file.


Ans.Input: def read_text_file(filename):
try:
# Open the file in read mode
with open(filename, 'r') as file:
# Reading the entire content of the file
content = file.read()
print("Content of the file:")
print(content)

except FileNotFoundError:
print(f"Error: The file '{filename}' does not exist.")
except Exception as e:
print(f"An error occurred: {e}")

# Asking the user for the file name


filename = input("Enter the name of the file to read (with extension,
e.g., 'file.txt'): ")

# Calling the function to read and display the file content


read_text_file(filename)

Output:
PYTHON LAB ASSIGNMENT 50

Enter the name of the file to read (with extension, e.g., 'file.txt'):
1st Assignment
Error: The file '1st Assignment' does not exist.

Q57.Write a program to write in a text file.


Ans.Input: def write_to_text_file(filename, content):
try:
# Open the file in write mode ('w')
with open(filename, 'w') as file:
# Write the provided content to the file
file.write(content)
print(f"Content successfully written to {filename}")

except Exception as e:
print(f"An error occurred: {e}")

# Ask the user for the file name and the content to write
filename = input("Enter the name of the file to write to (with
extension, e.g., 'file.txt'): ")
content = input("Enter the content to write to the file: ")

# Calling the function to write content to the file


write_to_text_file(filename, content)

Output:
Enter the name of the file to write to (with extension, e.g.,
'file.txt'): Assignment1
Enter the content to write to the file: Hello,this is a programming
language, call Python.
Content successfully written to Assignment1

Q58.Write a program to append in a text file.


Ans.Input: def append_to_text_file(filename, content):
try:
# Open the file in append mode ('a')
with open(filename, 'a') as file:
# Append the provided content to the file
file.write(content + '\n') # Adding a newline after each
append
print(f"Content successfully appended to {filename}")

except Exception as e:
print(f"An error occurred: {e}")
PYTHON LAB ASSIGNMENT 51

# Ask the user for the file name and the content to append
filename = input("Enter the name of the file to append to (with
extension, e.g., 'file.txt'): ")
content = input("Enter the content to append to the file: ")

# Calling the function to append content to the file


append_to_text_file(filename, content)

Output:
Enter the name of the file to append to (with extension, e.g.,
'file.txt'): Assignment1
Enter the content to append to the file: This is a very good
progamming language.
Content successfully appended to Assignment1

Q59.Create a class Circle with an attribute radius. Add a method


calculate_area to compute and return the area of the
circle.Create an object of the Circle class, assign a radius, and
use the method to calculate the area.
Ans.Input:
import math
# Define the Circle class
class Circle:
def __init__(self, radius):
self.radius = radius # Initialize the radius attribute

def calculate_area(self):
"""Method to calculate and return the area of the circle."""
return math.pi * self.radius ** 2

# Create an object of the Circle class with a given radius


radius_value = float(input("Enter the radius of the circle: "))
circle_obj = Circle(radius_value)

# Calculate the area using the object's method


area = circle_obj.calculate_area()

# Display the result


print(f"The area of the circle with radius {radius_value} is:
{area:.2f}")
Output:
Enter the radius of the circle: 24
The area of the circle with radius 24.0 is: 1809.56
PYTHON LAB ASSIGNMENT 52

Q60.Create a class Account with attributes balance. Add methods


deposit to increase the balance and withdraw to decrease it (with a
check to prevent withdrawal beyond the available balance). Display
the balance after each operation.
Ans.Input:
class Account:
def __init__(self, initial_balance=0.0):
"""Initialize the account with an optional initial balance
(default is 0)."""
self.balance = initial_balance

def deposit(self, amount):


"""Method to add money to the account."""
if amount > 0:
self.balance += amount
print(f"Deposited: Rs.{amount:.2f}")
else:
print("Deposit amount must be positive.")
self.display_balance()

def withdraw(self, amount):


"""Method to withdraw money from the account with balance
check."""
if amount > self.balance:
print("Insufficient balance! Cannot withdraw.")
elif amount > 0:
self.balance -= amount
print(f"Withdrawn: Rs.{amount:.2f}")
else:
print("Withdrawal amount must be positive.")
self.display_balance()

def display_balance(self):
"""Method to display the current account balance."""
print(f"Current Balance: Rs.{self.balance:.2f}\n")

# Create an Account object with an initial balance


my_account = Account(5000.0)

# Perform deposit and withdrawal operations


my_account.deposit(500) # Depositing Rs. 1000
my_account.withdraw(300) # Withdrawing Rs. 3000
my_account.withdraw(1500) # Trying to withdraw beyond balance
my_account.deposit(-100) # Invalid deposit attempt
PYTHON LAB ASSIGNMENT 53

my_account.withdraw(200) # Withdrawing Rs. 2000


Output:
Deposited: Rs.500.00
Current Balance: Rs.5500.00

Withdrawn: Rs.300.00
Current Balance: Rs.5200.00

Withdrawn: Rs.1500.00
Current Balance: Rs.3700.00

Deposit amount must be positive.


Current Balance: Rs.3700.00

Withdrawn: Rs.200.00
Current Balance: Rs.3500.00

You might also like