Python Lab Assingnment
Python Lab Assingnment
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
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
Output:
Enter the basic pay of the employee: 8900
Gross Salary: 22756.00
Net Salary: 21488.00
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
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.
Output:
Enter your age: 21
Enter your sex (M/F): M
Enter your marital status (Y/N): N
You may work anywhere.
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
Output:
Series: -2, -1, 0, 1, 2
Series: 10, 11, 12, 13, 14
if num < 0:
print("ERROR: Please enter a positive number.”)
else:
PYTHON LAB ASSIGNMENT 8
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.
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]
sum_of_divisors = 0
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
def find_perfect_numbers(limit):
"""
Function to find all perfect numbers up to a given limit.
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
except ValueError:
print("ERROR: Please enter valid integers.")
Output:
Enter the start of the range: 45
PYTHON LAB ASSIGNMENT 12
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.
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
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
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
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
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
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
"""
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
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
(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
(iii)
*
**
***
****
*****
Ans. Input: def print_right_aligned_pattern(rows):
"""
Function to print a right-aligned star pattern.
****
*****
(iv)
*
***
*****
*******
*********
Ans. Input: def print_pyramid_pattern(rows):
"""
Function to print a pyramid star pattern.
(V)
*********
*******
*****
***
PYTHON LAB ASSIGNMENT 21
*
Ans. Input: def print_inverted_pyramid_pattern(rows):
"""
Function to print an inverted pyramid star pattern.
(vi)
1
121
12321
1234321
123454321
Ans.Input: def print_number_pyramid(rows):
"""
Function to print a number pyramid pattern.
(vii)
*
***
*****
*******
*********
*******
*****
***
*
Ans. Input: def print_diamond_pattern(rows):
"""
Function to print a diamond-shaped star pattern.
(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)
**
*
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.
(iii)
A
AB
ABC
ABCD
ABCDE
Ans. Input: def print_right_aligned_alphabet_pattern(rows):
"""
Function to print a right-aligned alphabet pattern.
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
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.
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.
except ValueError:
print("ERROR: Please enter a valid integer.")
Output:
Enter a number: 81
81 is a Harshad number.
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]
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]
Output:
Enter the base (a): 6
Enter the exponent (b): 5
6.0^5 = 7776.0
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)
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
"""
print(f"{message}, {name}!")
Output:
Hello, Sudip!
Good morning, Sovan!
Welcome, Suvendu!
4
5
Output:
Enter a string to remove digits: Good2355 Morning567887
The string after removing digits: Good Morning
for char in s:
if char in vowels:
count += 1
return count
Output:
Enter a string to abbreviate: Damodar Valley Corporation
The abbreviated form is: DVC
Output:
Enter a string: WORST
The new string is: WWW OOO RRR SSS TTT
# List of numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# List of numbers
numbers = [1, 2, 3, 4, 5]
Output:
Squared numbers: [1, 4, 9, 16, 25]
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'}
except FileNotFoundError:
print(f"Error: The file '{filename}' does not exist.")
except Exception as e:
print(f"An error occurred: {e}")
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.
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: ")
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
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: ")
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
def calculate_area(self):
"""Method to calculate and return the area of the circle."""
return math.pi * self.radius ** 2
def display_balance(self):
"""Method to display the current account balance."""
print(f"Current Balance: Rs.{self.balance:.2f}\n")
Withdrawn: Rs.300.00
Current Balance: Rs.5200.00
Withdrawn: Rs.1500.00
Current Balance: Rs.3700.00
Withdrawn: Rs.200.00
Current Balance: Rs.3500.00