100% found this document useful (1 vote)
288 views29 pages

PWP Practicals Answer Key

The document contains answers to Python programming questions and exercises. It includes Python code snippets to demonstrate concepts like loops, conditional statements, functions, lists, sets, dictionaries and more. Various questions cover printing patterns, finding common items in lists, sorting dictionaries, calculating sums and products.

Uploaded by

Renuka Kene
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
100% found this document useful (1 vote)
288 views29 pages

PWP Practicals Answer Key

The document contains answers to Python programming questions and exercises. It includes Python code snippets to demonstrate concepts like loops, conditional statements, functions, lists, sets, dictionaries and more. Various questions cover printing patterns, finding common items in lists, sorting dictionaries, calculating sums and products.

Uploaded by

Renuka Kene
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/ 29

PWP Practicals Answer Key

Q1. Write a Python Program to display “MSBTE” using interactive mode.


Ans :

#JUST DO THIS IN THE SHELL


print("MSBTE")

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

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

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 :

for x in range(100, 4, -1):


print(x)

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]

common_items = [item for item in list1 if item in list2]

1 AG
print("Common items:", common_items)

# set()

list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]

common_items = list(set(list1) & set(list2))

print("Common items:", common_items)

Q5. Write a Python Program to display intersection of two sets.


Ans :

set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}

intersection = set1.intersection(set2)

print("Intersection of set1 and set2:", intersection)

Q6. Write a Python Program to sort dictionary in ascending order (by value)
Ans :

my_dict = {'a': 3, 'b': 1, 'c': 2, 'd': 5, 'e': 4}

sorted_dict = dict(sorted(my_dict.items(), key=lambda item: item[1]))

print("Dictionary sorted by values in ascending order:", sorted_dict)

Q7. Write a Python function to calculate square of a number.


Ans :

def square(number):
return number ** 2

# Example usage:
num = 5
print("Square of", num, "is", square(num))

Q8. Write a Python Program to display “MSBTE” using script mode.


Ans :

print("MSBTE")

2 AG
Q9. Write a Python Program to display the absolute value of an input number.
Ans :

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

absolute_value = abs(number)

print("Absolute value of", number, "is", absolute_value)

Q10. Change the following code from while loop to for loop

Ans :

for x in range(1, 20):


print(x)

Q11. Write a Python Program to show how to concatenate two lists


Ans :

# "+" operator

list1 = [1, 2, 3]
list2 = [4, 5, 6]

concatenated_list = list1 + list2

print("Concatenated list:", concatenated_list)

# extend()

list1 = [1, 2, 3]
list2 = [4, 5, 6]

list1.extend(list2)

print("Concatenated list:", list1)

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)

# Create a new tuple containing specific elements


new_tuple = tuple(existing_tuple[i] for i in indices_to_copy)

# Print the new tuple


print("New tuple containing specific elements:", new_tuple)

Q13. Write a Python Program to display set difference of two sets.


Ans :

set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}

difference_set = set1.difference(set2)

print("Set difference of set1 and set2:", difference_set)

Q14. Write a Python Program to display the concatenated dictionary from two dictionaries.
Ans :

dict1 = {'a': 1, 'b': 2}


dict2 = {'c': 3, 'd': 4}

concatenated_dict = dict1.copy() # Copy dict1 to preserve its original


contents
concatenated_dict.update(dict2)

print("Concatenated dictionary:", concatenated_dict)

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.

Q16. Write a Python Program to display symmetric difference of two sets.


Ans :

set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}

symmetric_difference_set = set1.symmetric_difference(set2)

print("Symmetric difference of set1 and set2:",


symmetric_difference_set)

Q17. Write a Python Program to display prime numbers between 2 to 100 using nested
loops
Ans :

for num in range(2, 101):


is_prime = True
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
is_prime = False
break
if is_prime:
print(num, end=" ")

Q18. Write a Python program to sum all the items in a list.


Ans :

# Define a list of numbers


numbers = [1, 2, 3, 4, 5]

# Sum all the items in the list


total_sum = sum(numbers)

# Print the sum


print("Sum of all items in the list:", total_sum)

Q19. Write a Python program to multiply all the items in a list.


Ans :

# Define a list of numbers


numbers = [1, 2, 3, 4, 5]

5 AG
# Initialize a variable to store the result
result = 1

# Multiply all the items in the list


for num in numbers:
result *= num

# Print the result


print("Multiplication of all items in the list:", result)

Q20. Write a Python program to get the largest number from a list.
Ans :

# Define a list of numbers


numbers = [10, 20, 5, 35, 45]

# Get the largest number from the list


largest_number = max(numbers)

# Print the largest number


print("Largest number in the list:", largest_number)

Q21. Write a Python program to get the smallest number from a list.
Ans :

# Define a list of numbers


numbers = [10, 20, 5, 35, 45]

# Get the smallest number from the list


smallest_number = min(numbers)

# Print the smallest number


print("Smallest number in the list:", smallest_number)

Q22. Write a Python program to reverse a list.


Ans :

# Define a list
my_list = [1, 2, 3, 4, 5]

# Reverse the list using list slicing


reversed_list = my_list[::-1]

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

# Define two lists


list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]

# Find common items using list comprehension


common_items = [item for item in list1 if item in list2]

# Print the common items


print("Common items:", common_items)

#set()

# Define two lists


list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]

# Find common items using set intersection


common_items = set(list1) & set(list2)

# Print the common items


print("Common items:", common_items)

Q24. Write a Python program to select the even items of a list.


Ans :

# Define a list
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Select even items using list comprehension


even_items = [item for item in my_list if item % 2 == 0]

# Print the even items


print("Even items:", even_items)

7 AG
Q25. Write a Python Program to print
*
**
***
****
Ans :

for i in range(1, 5):


for j in range(i):
print("*", end="")
print()

Q26. Write a program that multiplies all items in a list.

my_list = [2, 3, 4, 5]
result = 1

for item in my_list:


result *= item

print("Result:", result)

Q27. Write a Python program to print


1010101
10101
101
1
Ans :

rows = 4

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


for j in range(i):
if j % 2 == 0:
print("1", end="")
else:
print("0", end="")
print()

Q28. Write a Python program to combine two dictionary subtracting values for common
keys.
Ans :

def subtract_common_keys(dict1, dict2):

8 AG
result = dict(dict1) # Make a copy of dict1 to avoid modifying it
directly

for key, value in dict2.items():


if key in result:
result[key] -= value

return result

# Example usage:
dict1 = {'a': 5, 'b': 10, 'c': 15}
dict2 = {'a': 2, 'b': 8, 'd': 4}

combined_dict = subtract_common_keys(dict1, dict2)

print("Combined dictionary:", combined_dict)

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 :

# Initialize a variable to store the sum


sum_of_numbers = 0

# Iterate through the first 10 natural numbers using a for loop


for num in range(1, 11):
sum_of_numbers += num

# Print the sum


print("Sum of the first 10 natural numbers:", sum_of_numbers)

Q31. Write a Python program to print Fibonacci series.


Ans :

def fibonacci_series(n):
# Initialize first two terms of the series

9 AG
fib_series = [0, 1]

# Generate Fibonacci series up to the nth term


for i in range(2, n):
next_term = fib_series[-1] + fib_series[-2]
fib_series.append(next_term)

return fib_series

# Number of terms in the series


num_terms = int(input("Enter the number of terms for Fibonacci series:
"))

# Call the function and print the Fibonacci series


print("Fibonacci series up to", num_terms, "terms:")
print(fibonacci_series(num_terms))

Q32. Write a Python program to calculate factorial of a number


Ans :

def factorial(n):
# Base case: factorial of 0 or 1 is 1
if n == 0 or n == 1:
return 1

# Recursive case: factorial of n is n times factorial of (n-1)


return n * factorial(n - 1)

# Input number for which factorial needs to be calculated


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

# Call the function and print the factorial


print("Factorial of", num, "is:", factorial(num))

Q33. Write a Python Program to Reverse a Given Number


Ans :

def reverse_number(number):
reversed_number = 0

# Loop to reverse the number


while number > 0:
# Extract the last digit
digit = number % 10

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

# Input the number to be reversed


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

# Call the function and print the reversed number


print("Reversed number:", reverse_number(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

# Convert the number to a string to iterate over its digits


number_str = str(number)

# Iterate over each digit and add it to the sum


for digit in number_str:
sum_digits += int(digit)

return sum_digits

# Input the number


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

# Call the function and print the sum of digits


print("Sum of digits in the number:", sum_of_digits(number))

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)

# Reverse the string

11 AG
reversed_str = number_str[::-1]

# Check if the original number is equal to its reverse


if number_str == reversed_str:
return True
else:
return False

# Input the number


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

# Check if the number is a palindrome


if is_palindrome(number):
print(number, "is a palindrome")
else:
print(number, "is not a palindrome")

Q36. Write a program to calculate surface volume and area of a cylinder.


Ans :

import math

def cylinder_properties(radius, height):


# Calculate surface area
surface_area = 2 * math.pi * radius * (radius + height)

# Calculate volume
volume = math.pi * radius ** 2 * height

# Calculate lateral surface area


lateral_surface_area = 2 * math.pi * radius * height

return surface_area, volume, lateral_surface_area

# Input radius and height of the cylinder


radius = float(input("Enter the radius of the cylinder: "))
height = float(input("Enter the height of the cylinder: "))

# Calculate the properties of the cylinder


surface_area, volume, lateral_surface_area =
cylinder_properties(radius, height)

# Print the results

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 :

# Input three numbers from the user


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

# Find the largest number using max() function


largest = max(num1, num2, num3)

# Print the largest number


print("Largest number among", num1, ",", num2, ", and", num3, "is:",
largest)

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: ")

# Concatenate the first name and last name


full_name = first_name + " " + last_name

return full_name

#main_program.py:

import name_module

# Call the function from the user-defined module


full_name = name_module.get_full_name()

# Display the concatenated name


print("Your full name is:", full_name)

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)

if percentage >= 90:


return 'A+'
elif percentage >= 80:
return 'A'
elif percentage >= 70:
return 'B'
elif percentage >= 60:
return 'C'
elif percentage >= 50:
return 'D'
else:
return 'F'

def display_results(name, marks):


print("Student Name:", name)
print("Subject\t\tMarks")
print("----------------------")
for subject, mark in marks.items():
print(subject, "\t\t", mark)
print("----------------------")
print("Grade:", calculate_grade(marks.values()))

# Input student name


name = input("Enter student name: ")

# Input marks for 5 subjects


marks = {}
for i in range(5):
subject = input("Enter subject {}: ".format(i+1))
mark = float(input("Enter marks for {}: ".format(subject)))
marks[subject] = mark

# Display the results in tabular form


display_results(name, 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 :

# Create an empty set


my_set = set()

# Add members to the set


my_set.add(1)
my_set.add(2)
my_set.add(3)

print("Set after adding members:", my_set)

# Remove one item from the set


item_to_remove = 2
my_set.remove(item_to_remove)

print("Set after removing", item_to_remove, ":", my_set)

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 :

# Define two sets


set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}

# 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}

# Find the maximum and minimum values in the set


maximum_value = max(my_set)
minimum_value = min(my_set)

# Print the maximum and minimum values


print("Maximum value in the set:", maximum_value)
print("Minimum value in the set:", minimum_value)

Q43. Write a Python program to find the length of a set.


Ans :

# Define a set
my_set = {10, 20, 30, 40, 50}

# Find the length of the set


set_length = len(my_set)

# Print the length of the set


print("Length of the set:", set_length)

Q44. Write a program to check if the input year is a leap year of not.
Ans : Refer Q2

Q45. Write a program to convert bits to Megabytes, Gigabytes and Terabytes


Ans :

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)

# Input bits from the user


bits = int(input("Enter number of bits: "))

# Convert bits to bytes


bytes = bits_to_bytes(bits)

# Convert bytes to MB, GB, and TB


MB = bytes_to_MB(bytes)
GB = bytes_to_GB(bytes)
TB = bytes_to_TB(bytes)

# Print the results


print("Megabytes:", MB)
print("Gigabytes:", GB)
print("Terabytes:", TB)

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: ")

# Display company name and address


print("Company Name:", company_name)
print("Company Address:", 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

# Iterate through each character in the string


for char in text:
# Check if the character is uppercase
if char.isupper():
upper_count += 1
# Check if the character is lowercase
elif char.islower():
lower_count += 1

# Return the counts


return upper_count, lower_count

# Test the function


text = input("Enter a string: ")
upper_count, lower_count = count_upper_lower(text)
print("Number of uppercase letters:", upper_count)
print("Number of lowercase letters:", lower_count)

Q49. Write a Python Program to print the following

Ans :

def print_pattern(rows):
# Upper part of the pattern
for i in range(1, rows + 1):
print(" " * (rows - i) + "*" * (2 * i - 1))

# Lower part of the pattern

18 AG
for i in range(rows - 1, 0, -1):
print(" " * (rows - i) + "*" * (2 * i - 1))

# Number of rows in the pattern


rows = 3

# Print the pattern


print_pattern(rows)

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

# Test the function


num = int(input("Enter a number: "))
if is_prime(num):
print(num, "is a prime number.")
else:
print(num, "is not a prime number.")

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

# Input the radius of the circle


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

# Calculate area and circumference


area = calculate_area(radius)
circumference = calculate_circumference(radius)

# Print the results


print("Area of the circle:", area)
print("Circumference of the circle:", circumference)

Q55. Write a Python program to concatenate two strings.


Ans :

def concatenate_strings(str1, str2):


return str1 + str2

# Input two strings from the user


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

# Concatenate the strings


result = concatenate_strings(str1, str2)

# Print the concatenated string


print("Concatenated string:", result)

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

def subtract_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

def multiply_matrices(matrix1, matrix2):


result = []
for i in range(len(matrix1)):
row = []
for j in range(len(matrix2[0])):
element = sum(matrix1[i][k] * matrix2[k][j] for k in
range(len(matrix2)))
row.append(element)
result.append(row)
return result

def divide_matrices(matrix1, matrix2):


result = []
for i in range(len(matrix1)):
row = []
for j in range(len(matrix1[0])):
if matrix2[i][j] == 0:
print("Error: Division by zero")
return None
row.append(matrix1[i][j] / matrix2[i][j])
result.append(row)
return result

# Hardcoded values for matrices


matrix1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
matrix2 = [[9, 8, 7], [6, 5, 4], [3, 2, 1]]

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()

# Calculate and print area of a square


side_length = float(input("Enter side length of the square: "))
print("Area of square:", calculator.calculate_area(side=side_length))

# Calculate and print area of a rectangle


length = float(input("Enter length of the rectangle: "))
breadth = float(input("Enter breadth of the rectangle: "))
print("Area of rectangle:", calculator.calculate_area(length=length,
breadth=breadth))

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)

# Input student's information


name = input("Enter student's name: ")
age = int(input("Enter student's age: "))
roll_number = input("Enter student's roll number: ")

# Create a student object


student = Student(name, age, roll_number)

23 AG
# Display student's information
print("\nStudent's Information:")
student.display_info()

Q59. Write a program to find the square root of a number.


Ans :

import math

def find_square_root(number):
if number < 0:
return "Square root is not defined for negative numbers"
else:
return math.sqrt(number)

# Input the number


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

# Calculate and print the square root


result = find_square_root(number)
print("Square root of", number, "is:", result)

Q60. Write a program to check the largest number among the three numbers
Ans : Refer Q37

Q61. Write a Python program to Check for ZeroDivisionError Exception.


Ans :

try:
dividend = int(input("Enter the dividend: "))
divisor = int(input("Enter the divisor: "))

result = dividend / divisor


print("Result of division:", result)

except ZeroDivisionError:
print("Error: Division by zero")
except ValueError:
print("Error: Invalid input. Please enter integers.")

Q62. Write a Python program to print all unique values in a dictionary.

Ans :

24 AG
data = [
{"V": "S001"},
{"V": "S002"},
{"VI": "S001"},
{"VI": "S005"},
{"VII": "S005"},
{"V": "S009"},
{"VIII": "S007"}
]

# Initialize an empty set to store unique values


unique_values = set()

# Iterate over the list of dictionaries


for item in data:
# Iterate over the values in each dictionary and add them to the
set
for value in item.values():
unique_values.add(value)

# Print the unique values


print("Unique values in the dictionary:", unique_values)

Q63. Print the number in words for Example: 1234 =&gt; 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'
}

# Convert the number to a string


number_str = str(number)

# Initialize an empty string to store the words


words = ""

# Iterate over each digit in the number


for digit in number_str:

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 + " "

return words.strip() # Remove trailing whitespace

# 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

# Generate six random integers between 10 and 30


random_integers = np.random.randint(10, 31, size=6)

print("Six random integers between 10 and 30:")


print(random_integers)

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 __init__(self, message="Invalid password."):


self.message = message
super().__init__(self.message)

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: ")

# Validate the entered password


validate_password(password_input)

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

# Reading employee information


employee.read_employee_info()

# Printing employee information


print("\nEmployee Information:")
employee.print_employee_info()

27 AG
Q67. Python program to read and print students information using two classes using simple
Inheritance.
Ans : Refer Q58

Q68. Write a Python program to implement multiple inheritance.


Ans :

class Parent1:
def method1(self):
print("Parent1 method")

class Parent2:
def method2(self):
print("Parent2 method")

class Child(Parent1, Parent2):


def method3(self):
print("Child method")

# Create an object of the Child class


child_obj = Child()

# Call methods from parent classes


child_obj.method1() # Output: Parent1 method
child_obj.method2() # Output: Parent2 method

# Call method from the child class


child_obj.method3() # Output: Child 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

Q70. Write a program to check whether a number is even or odd


Ans :

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: "))

# Check if the number is even or odd


check_even_odd(number)

29 AG

You might also like