PWP Practicals Answer Key
PWP Practicals Answer Key
Q2. Write a Python Program to check if the input year is leap year or not.
Ans :
def is_leap_year(year):
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
return True
else:
return False
if is_leap_year(year):
print(year, "is a leap year.")
else:
print(year, "is not a leap year.")
Q3. Change the following code from while loop to for loop
Ans :
Q4. Write a Python Program to show how to find common items from two lists.
Ans :
# list comprehension
list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]
1 AG
print("Common items:", common_items)
# set()
list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
intersection = set1.intersection(set2)
Q6. Write a Python Program to sort dictionary in ascending order (by value)
Ans :
def square(number):
return number ** 2
# Example usage:
num = 5
print("Square of", num, "is", square(num))
print("MSBTE")
2 AG
Q9. Write a Python Program to display the absolute value of an input number.
Ans :
absolute_value = abs(number)
Q10. Change the following code from while loop to for loop
Ans :
# "+" operator
list1 = [1, 2, 3]
list2 = [4, 5, 6]
# extend()
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)
Q12. Write a python program to copy specific elements from existing Tuple to new Tuple.
Ans :
# Existing tuple
existing_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
3 AG
# Indices of specific elements to copy
indices_to_copy = (1, 3, 5, 7)
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
difference_set = set1.difference(set2)
Q14. Write a Python Program to display the concatenated dictionary from two dictionaries.
Ans :
Q15. Write a Python function to display whether the number is positive negative or zero.
Ans :
def check_number(num):
if num > 0:
print("The number is positive.")
elif num < 0:
print("The number is negative.")
else:
print("The number is zero.")
# Example usage:
4 AG
check_number(5) # Output: The number is positive.
check_number(-2) # Output: The number is negative.
check_number(0) # Output: The number is zero.
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
symmetric_difference_set = set1.symmetric_difference(set2)
Q17. Write a Python Program to display prime numbers between 2 to 100 using nested
loops
Ans :
5 AG
# Initialize a variable to store the result
result = 1
Q20. Write a Python program to get the largest number from a list.
Ans :
Q21. Write a Python program to get the smallest number from a list.
Ans :
# Define a list
my_list = [1, 2, 3, 4, 5]
6 AG
# Print the reversed list
print("Original list:", my_list)
print("Reversed list:", reversed_list)
Q23. Write a Python program to find common items from two lists.
Ans :
#list comprehension
#set()
# Define a list
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
7 AG
Q25. Write a Python Program to print
*
**
***
****
Ans :
my_list = [2, 3, 4, 5]
result = 1
print("Result:", result)
rows = 4
Q28. Write a Python program to combine two dictionary subtracting values for common
keys.
Ans :
8 AG
result = dict(dict1) # Make a copy of dict1 to avoid modifying it
directly
return result
# Example usage:
dict1 = {'a': 5, 'b': 10, 'c': 15}
dict2 = {'a': 2, 'b': 8, 'd': 4}
Q29. Write a Python program to print all even numbers between 1 to 100 using while loop.
Ans :
num = 2
while num <= 100:
print(num, end=" ")
num += 2
print()
Q30. Write a Python program to find the sum of first 10 natural numbers using for loop.
Ans :
def fibonacci_series(n):
# Initialize first two terms of the series
9 AG
fib_series = [0, 1]
return fib_series
def factorial(n):
# Base case: factorial of 0 or 1 is 1
if n == 0 or n == 1:
return 1
def reverse_number(number):
reversed_number = 0
10 AG
# Append the digit to the reversed number
reversed_number = (reversed_number * 10) + digit
# Remove the last digit from the original number
number //= 10
return reversed_number
Q34. Write a Python program takes in a number and finds the sum of digits in a number.
Ans :
def sum_of_digits(number):
# Initialize the sum to 0
sum_digits = 0
return sum_digits
Q35. Write a Python program that takes a number and checks whether it is a palindrome or
not.
Ans :
def is_palindrome(number):
# Convert the number to a string
number_str = str(number)
11 AG
reversed_str = number_str[::-1]
import math
# Calculate volume
volume = math.pi * radius ** 2 * height
12 AG
print("Surface Area of the cylinder:", surface_area)
print("Volume of the cylinder:", volume)
print("Lateral Surface Area of the cylinder:", lateral_surface_area)
Q37. Write a program to check the largest number among the three numbers
Ans :
Q38. Write a Python program to create a user defined module that will ask your first name
and last name and will display the name after concatenation.
Ans :
#name_module.py
def get_full_name():
# Ask for first name and last name from the user
first_name = input("Enter your first name: ")
last_name = input("Enter your last name: ")
return full_name
#main_program.py:
import name_module
13 AG
Q39. Write a program that takes the name of student and marks of 5 subjects and displays
the grade in tabular form.
Ans :
def calculate_grade(marks):
total_marks = sum(marks)
percentage = total_marks / len(marks)
14 AG
Q40. Write a Python program to create a set, add member(s) in a set and remove one item
from set.
Ans :
Q41. Write a Python program to perform following operations on set: intersection of sets,
union of sets, set difference, symmetric difference, clear a set.
Ans :
# Intersection of sets
intersection = set1.intersection(set2)
print("Intersection of sets:", intersection)
# Union of sets
union = set1.union(set2)
print("Union of sets:", union)
# Set difference
difference = set1 - set2
print("Set difference (set1 - set2):", difference)
# Symmetric difference
symmetric_difference = set1.symmetric_difference(set2)
print("Symmetric difference of sets:", symmetric_difference)
15 AG
# Clear a set
set1.clear()
print("Set1 after clearing:", set1)
Q42. Write a Python program to find maximum and the minimum value in a set.
Ans :
# Define a set
my_set = {10, 20, 30, 40, 50}
# Define a set
my_set = {10, 20, 30, 40, 50}
Q44. Write a program to check if the input year is a leap year of not.
Ans : Refer Q2
def bits_to_bytes(bits):
return bits / 8
def bytes_to_MB(bytes):
return bytes / (1024 ** 2)
def bytes_to_GB(bytes):
16 AG
return bytes / (1024 ** 3)
def bytes_to_TB(bytes):
return bytes / (1024 ** 4)
Q46. Write a program that takes the marks of 5 subjects and displays the grade.
Ans : Refer Q39
Q47. Write a Python program to create a user defined module that will ask your company
name and address and will display them.
Ans :
#company_info.py:
def get_company_info():
# Ask for company name and address
company_name = input("Enter company name: ")
company_address = input("Enter company address: ")
#main_program.py:
import company_info
17 AG
# Call the function from the user-defined module
company_info.get_company_info()
Q48. Write a Python function that accepts a string and calculate the number of upper case
letters and lower case letters.
Ans :
def count_upper_lower(text):
# Initialize counters for uppercase and lowercase letters
upper_count = 0
lower_count = 0
Ans :
def print_pattern(rows):
# Upper part of the pattern
for i in range(1, rows + 1):
print(" " * (rows - i) + "*" * (2 * i - 1))
18 AG
for i in range(rows - 1, 0, -1):
print(" " * (rows - i) + "*" * (2 * i - 1))
Q50. Write a Python program to perform following operations on set: intersection of sets,
union of sets, set difference, symmetric difference, clear a set.
Ans : Refer Q41
Q51. Write a Python function that takes a number as a parameter and check the number is
prime or not.
Ans :
def is_prime(number):
# Check if number is less than 2
if number < 2:
return False
# Check for factors from 2 to sqrt(number)
for i in range(2, int(number**0.5) + 1):
if number % i == 0:
return False
return True
Q52. Write a Python function to calculate the factorial of a number (a non-negative integer).
The function accepts the number as an argument.
Ans : Refer Q32
Q53. Write a Python function that takes a number as a parameter and check the number is
prime or not.
Ans : Refer Q51
Q54. Write a Python program that will calculate area and circumference of circle using inbuilt
Math Module.
Ans :
19 AG
import math
def calculate_area(radius):
return math.pi * radius ** 2
def calculate_circumference(radius):
return 2 * math.pi * radius
Q56. Write a Python program to create two matrices and perform addition, subtraction, and
multiplication and division operation on matrix.
Ans :
def print_matrix(matrix):
for row in matrix:
print(row)
20 AG
def add_matrices(matrix1, matrix2):
result = []
for i in range(len(matrix1)):
row = [matrix1[i][j] + matrix2[i][j] for j in
range(len(matrix1[0]))]
result.append(row)
return result
21 AG
print("Matrix 1:")
print_matrix(matrix1)
print("Matrix 2:")
print_matrix(matrix2)
# Addition
addition_result = add_matrices(matrix1, matrix2)
print("Addition result:")
print_matrix(addition_result)
# Subtraction
subtraction_result = subtract_matrices(matrix1, matrix2)
print("Subtraction result:")
print_matrix(subtraction_result)
# Multiplication
multiplication_result = multiply_matrices(matrix1, matrix2)
print("Multiplication result:")
print_matrix(multiplication_result)
# Division
division_result = divide_matrices(matrix1, matrix2)
if division_result:
print("Division result:")
print_matrix(division_result)
Q57. Write a Python program to create a class to print the area of a square and a rectangle.
The class has two methods with the same name but different number of parameters. The
method for printing area of rectangle has two parameters which are length and breadth
respectively while the other method for printing area of square has one parameter which
is side of square.
Ans :
class AreaCalculator:
def calculate_area(self, side=None, length=None, breadth=None):
if side is not None:
# Calculate area of square
return side ** 2
elif length is not None and breadth is not None:
# Calculate area of rectangle
return length * breadth
else:
return "Invalid input"
22 AG
# Create an instance of the class
calculator = AreaCalculator()
Q58. Python program to read and print student’s information using two classes using simple
Inheritance.
Ans :
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def display_info(self):
print("Name:", self.name)
print("Age:", self.age)
class Student(Person):
def __init__(self, name, age, roll_number):
super().__init__(name, age)
self.roll_number = roll_number
def display_info(self):
super().display_info()
print("Roll Number:", self.roll_number)
23 AG
# Display student's information
print("\nStudent's Information:")
student.display_info()
import math
def find_square_root(number):
if number < 0:
return "Square root is not defined for negative numbers"
else:
return math.sqrt(number)
Q60. Write a program to check the largest number among the three numbers
Ans : Refer Q37
try:
dividend = int(input("Enter the dividend: "))
divisor = int(input("Enter the divisor: "))
except ZeroDivisionError:
print("Error: Division by zero")
except ValueError:
print("Error: Invalid input. Please enter integers.")
Ans :
24 AG
data = [
{"V": "S001"},
{"V": "S002"},
{"VI": "S001"},
{"VI": "S005"},
{"VII": "S005"},
{"V": "S009"},
{"VIII": "S007"}
]
Q63. Print the number in words for Example: 1234 => One Two Three Four
Ans :
def number_to_words(number):
# Define a dictionary to map digits to their word representations
digit_words = {
'0': 'Zero', '1': 'One', '2': 'Two', '3': 'Three', '4': 'Four',
'5': 'Five', '6': 'Six', '7': 'Seven', '8': 'Eight', '9':
'Nine'
}
25 AG
# Get the word representation of the digit from the dictionary
digit_word = digit_words.get(digit)
if digit_word:
# Append the word representation to the string
words += digit_word + " "
# Example usage:
number = 1234
words = number_to_words(number)
print(f"{number} => {words}")
Q64. Write a NumPy program to generate six random integers between 10 and 30.
Ans :
import numpy as np
Q65. Write a Python program to create user defined exception that will check whether the
password is correct or not?
Ans :
class PasswordError(Exception):
"""Custom exception class for invalid passwords."""
def validate_password(password):
"""Function to validate the password."""
# Check if the password meets the criteria
if password == "correct_password":
print("Password is correct.")
else:
# Raise PasswordError exception if password is incorrect
raise PasswordError("Password is incorrect.")
26 AG
# Example usage:
try:
# Prompt user to enter a password
password_input = input("Enter the password: ")
except PasswordError as e:
# Handle the custom exception
print("Error:", e.message)
Q66. Create a class Employee with data members: name, department and salary. Create
suitable methods for reading and printing employee information
Ans :
class Employee:
def __init__(self, name, department, salary):
self.name = name
self.department = department
self.salary = salary
def read_employee_info(self):
self.name = input("Enter employee name: ")
self.department = input("Enter employee department: ")
self.salary = float(input("Enter employee salary: "))
def print_employee_info(self):
print("Employee Name:", self.name)
print("Department:", self.department)
print("Salary:", self.salary)
# Example usage:
employee = Employee("", "", 0) # Creating an instance of Employee
class
27 AG
Q67. Python program to read and print students information using two classes using simple
Inheritance.
Ans : Refer Q58
class Parent1:
def method1(self):
print("Parent1 method")
class Parent2:
def method2(self):
print("Parent2 method")
Q69. Write a Python program to create a class to print the area of a square and a rectangle.
The class has two methods with the same name but different number of parameters. The
method for printing area of rectangle has two parameters which are length and breadth
respectively while the other method for printing area of square has one parameter which
is side of square.
Ans : Refer Q57
def check_even_odd(number):
if number % 2 == 0:
print(number, "is even")
else:
print(number, "is odd")
28 AG
# Input a number from the user
number = int(input("Enter a number: "))
29 AG