[go: up one dir, main page]

0% found this document useful (0 votes)
4 views9 pages

PWP SOLVED INTERNAL v2

The document provides a series of Python programming exercises covering various topics such as dictionaries, factorial calculation, tuple manipulation, user-defined exceptions, palindrome checking, digit summation, list operations, class design, inheritance, pattern printing, set operations, string manipulation, and random number generation. Each exercise includes a brief explanation followed by example code. Additionally, the document emphasizes the importance of crediting the author when sharing or using the content.

Uploaded by

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

PWP SOLVED INTERNAL v2

The document provides a series of Python programming exercises covering various topics such as dictionaries, factorial calculation, tuple manipulation, user-defined exceptions, palindrome checking, digit summation, list operations, class design, inheritance, pattern printing, set operations, string manipulation, and random number generation. Each exercise includes a brief explanation followed by example code. Additionally, the document emphasizes the importance of crediting the author when sharing or using the content.

Uploaded by

dondanaitik
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

PWP SOLVED

1) Explain creating Dictionary and accessing Dictionary Elements


with example.
student = { "name": "Alice", "age": 20, "course": "CO"}

print("Name:", student["name"]) # Output: Alice


print("Age:", student["age"]) # Output: 20
print("Age:", student["course"]) # Output: 20

2) Write a Python program to find the factorial of a number


provided by the user.

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


if num < 0:
print("Factorial does not exist for negative numbers.")
else:
factorial = 1
for i in range(1, num + 1):
factorial *= i
print(f"The factorial of {num} is {factorial}.")

3) Write a python program to input any two tuples and


interchange the tuple variables.
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))

t1 = (a,)
t2 = (b,)
t1, t2 = t2, t1
print("First tuple:", t1)
print("Second tuple:", t2)

OR

t1 = (1, 2, 3)
t2 = ('a', 'b', 'c')

t1, t2 = t2, t1
print("First tuple:", t1)
print("Second tuple:", t2)

4) Write a program to show user defined exception in Python.


class NegativeNumberError(Exception):
pass
def check_number(num):
if num < 0:
raise NegativeNumberError("Negative numbers are not allowed!")
print("The number is:", num)
try:
number = int(input("Enter a number: "))
check_number(number)
except NegativeNumberError as e:
print(e)

OR

class NegativeNumberError(Exception):
pass
try:
num = int(input("Enter a number: "))
if num < 0:
raise NegativeNumberError("Negative numbers are not allowed!")
print("The number is:", num)
except NegativeNumberError as e:
print(e)

5) Write a Python Program to check if a string is palindrome or


not.

string = input("Enter a string: ")

if string == string[::-1]:
print("The string is a palindrome.")
else:
print("The string is not a palindrome.")

6) Write a Python program to calculate sum of digit of given


number using function.
def sum_of_digits(num):
total = 0
while num > 0:
total += num % 10
num = num // 10
return total

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

print("The sum of digits is:", sum_of_digits(number))

7) Write a Python Program to accept values from user in a list and


find the largest number and smallest number in a list.

numbers = list(map(int, input("Enter numbers separated by spaces:


").split()))

largest = max(numbers)
smallest = min(numbers)

print("Largest number:", largest)


print("Smallest number:", smallest)

8) Design a class student with data members : name, roll no.,


department, mobile no. Create suitable methods for reading
and printing student information.
class Student:
def __init__(self, name, roll_no, department, mobile_no):
self.name = name
self.roll_no = roll_no
self.department = department
self.mobile_no = mobile_no

def read_student_info(self):
self.name = input("Enter student's name: ")
self.roll_no = input("Enter student's roll number: ")
self.department = input("Enter student's department: ")
self.mobile_no = input("Enter student's mobile number: ")

def print_student_info(self):
print("Student Information:")
print("Name:", self.name)
print("Roll No:", self.roll_no)
print("Department:", self.department)
print("Mobile No:", self.mobile_no)

# Create a Student object


student = Student("", "", "", "")

# Read student information from the user


student.read_student_info()

# Print the student information


student.print_student_info()

9) With suitable program explain inheritance in Python.

# Parent class
class Animal:
def __init__(self, name):
self.name = name

def speak(self):
print(f"{self.name} makes a sound.")

# Child class (inherits from Animal)


class Dog(Animal):
def speak(self):
print(f"{self.name} barks.")

# Child class (inherits from Animal)


class Cat(Animal):
def speak(self):
print(f"{self.name} meows.")

dog = Dog("Buddy")
cat = Cat("Whiskers")
dog.speak()
cat.speak()

10) Print the following pattern using loop:


1010101
10101
101
1

rows = 4

for i in range(rows):
print(" " * i, end="")
for j in range(rows - i):
if j % 2 == 0:
print("1", end=" ")
else:
print("0", end=" ")
print()
11) Write python program to perform following operations on
set.
i) Create set of five elements
ii) Access set elements
iii) Update set by adding one element
iv) Remove one element from set.
# i) Create set of five elements
my_set = {1, 2, 3, 4, 5}
# ii) Access set elements
print("Set elements:")
for element in my_set:
print(element)
# iii) Update set by adding one element
my_set.add(6)
print("Set after adding 6:", my_set)
# iv) Remove one element from set
my_set.remove(3)
print("Set after removing 3:", my_set)

12) What is the output of the following program?


dict1 = {‘Google’ : 1, ‘Facebook’ : 2, ‘Microsoft’ : 3}
dict2 = {‘GFG’ : 1, ‘Microsoft’ : 2, ‘Youtube’ : 3}
dict1⋅update(dict2);
for key, values in dictl⋅items( ):
print (key, values)
corrected code:
dict1 = {'Google': 1, 'Facebook': 2, 'Microsoft': 3}
dict2 = {'GFG': 1, 'Microsoft': 2, 'Youtube': 3}
dict1.update(dict2)
for key, value in dict1.items():
print(key, value)

Output:
Google 1
Facebook 2
Microsoft 2
GFG 1
Youtube 3

13) Write a program function that accepts a string and calculate


the number of uppercase letters and lower case letters.
def count_case_letters(string):
upper_case_count = sum(1 for char in string if char.isupper())
lower_case_count = sum(1 for char in string if char.islower())

return upper_case_count, lower_case_count


string = input("Enter a string: ")
upper, lower = count_case_letters(string)

print(f"Uppercase letters: {upper}")


print(f"Lowercase letters: {lower}")

14) Write the output for the following if the variable course =
“Python”
>>> course [ : 3 ]
>>> course [ 3 : ]
>>> course [ 2 : 2 ]
>>> course [ : ]
>>> course [ -1 ]
>>> course [ 1 ]

Output:
Pyt
hon

Python
n
y

15) Write a python program to generate five random integers


between 10 and 50 using numpy library.

import numpy as np

random_integers = np.random.randint(10, 51,5)


print(random_integers)

16) Write a Python program to create user defined exception


that will check whether the password is correct or not.

class InvalidPasswordException(Exception):
pass

def check_password(input_password):
correct_password = "mypassword123"
if input_password != correct_password:
raise InvalidPasswordException("Password is incorrect!")
else:
print("Password is correct!")

password = input("Enter your password: ")


try:
check_password(password)
except InvalidPasswordException as e:
print(e)

17) Write the output for the following if the variable fruit =
‘banana’.
>> fruit [:3]
>> fruit [3:]
>> fruit [3:3]
>> fruit [:]

Output:
ban
ana

banana

18) Write python program to display output like.


2
4 6 8
10 12 14 16 18

num = 2 # Starting number

for row in range(1, 4): # 3 rows


for col in range(row * 2 - 1):
print(num, end=" ")
num += 2
print()

19) Write output of following:


T = (‘spam’, ‘Spam’, ‘SPAM!’, ‘SaPm’)
print (T[2])
print (T[-2])
print (T[2:])
print (List (T))

Output:
SPAM!
SPAM!
('SPAM!', 'SaPm')
['spam', 'Spam', 'SPAM!', 'SaPm']

© 2025 Naitik Donda. All Rights Reserved.

This document is created by Naitik Donda. It may not be copied,


distributed, or shared without giving proper credit. Please provide five
credits before sharing or using any part of this document. Unauthorized
use is prohibited.

For any queries; gmail> dondanaitik@gmail.com

You might also like