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

Solved PWP Programs by Campusify

The document contains a collection of solved Python programs covering various topics such as area calculations, variable swapping, user-defined functions, and object-oriented programming. It includes examples for mathematical operations, string manipulations, inheritance, and exception handling. The programs are designed for educational purposes and are intended to help students understand Python programming concepts.
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)
1 views

Solved PWP Programs by Campusify

The document contains a collection of solved Python programs covering various topics such as area calculations, variable swapping, user-defined functions, and object-oriented programming. It includes examples for mathematical operations, string manipulations, inheritance, and exception handling. The programs are designed for educational purposes and are intended to help students understand Python programming concepts.
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/ 10

PWP

SOLVED PROGRAMS

Join Our Telegram Channel to get Total Free MSBTE


Study Material
JOIN - https://t.me/campusifyy
SITE - https://www.campusify.co.in/

Downloaded From Campusify!


Solved All Python Programs

1. Write a Program to find the area of a triangle.


base = float(input("Enter the base of the triangle: "))
height = float(input("Enter the height of the triangle: "))
area = 1/2* base * height
print("The area of the triangle is: ", area)
2. Write a Program to swap two variables.
a = input("Enter the value of a: ")
b = input("Enter the value of b: ")
print("Before swapping:")
print("a =", a)
print("b =", b)
temp = a
a=b
b = temp
print("After swapping:")
print("a =", a)
print("b =", b)
3. Write a Program to calculate area and perimeter of the square.
side = float(input("Enter the length of a side of the square: "))
area = side ** 2
perimeter = 4 * side
print("The area of the square is:", area)
print("The perimeter of the square is:", perimeter)
4. Write a Program that takes the marks of 5 subjects and display
print("Enter the marks of 5 subjects:")
marks1 = float(input("Subject 1: "))
marks2 = float(input("Subject 2: "))
marks3 = float(input("Subject 3: "))
marks4 = float(input("Subject 4: "))
marks5 = float(input("Subject 5: "))

Downloaded From Campusify!


print("Marks obtained in Subject 1: ", marks1)
print("Marks obtained in Subject 2: ", marks2)
print("Marks obtained in Subject 3: ", marks3)
print("Marks obtained in Subject 4: ", marks4)
print("Marks obtained in Subject 5: ", marks5)
5. Write a Program to create user defined function to Check if a Number is Odd or Even
def check_odd_even(num):
if num % 2 == 0:
print(f"{num} is even")
else:
print(f"{num} is odd")
num = int(input("Enter a number: "))
check_odd_even(num)
6. Write a Program to create user defined function to Check Leap Year
def check_leap_year(year):
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
print(f"{year} is a leap year")
else:
print(f"{year} is not a leap year")
else:
print(f"{year} is a leap year")
else:
print(f"{year} is not a leap year")
year = int(input("Enter a year: "))
check_leap_year(year)
7. Write a Program to Check if a Number is Positive, Negative or Zero
num = float(input("Enter a number: "))
if num > 0:
print(f"{num} is positive")
elif num < 0:
print(f"{num} is negative")
else:
print(f"{num} is zero")
8. Write a Program to Print the Fibonacci series
n = int(input("Enter the number of terms you want in the Fibonacci series: "))
a, b = 0, 1
for i in range(n): Downloaded From Campusify!
print(a)
a, b = b, a + b
9. Write a Program to Find the Factorial of a Number
n = int(input("Enter a number: "))
factorial = 1
for i in range(1, n + 1):
factorial *= i
print(f"The factorial of {n} is {factorial}")
10. Write a Program to check given number is prime or not.
n = int(input("Enter a number: "))
for i in range(2, n):
if n % i == 0:
print(f"{n} is not a prime number")
break
else:
print(f"{n} is a prime number")
11. Write a Python Program to find the repeated items from a tuple.
my_tuple = (1, 2, 3, 4, 2, 5, 6, 5, 7, 8, 1, 9, 9, 2)
# create an empty set to store the repeated items
repeated_items = set()
# create a set to store the unique items
unique_items = set()
# iterate through each item in the tuple
for item in my_tuple:
# if the item appears more than once in the tuple, add it to the repeated_items set
if item in unique_items:
repeated_items.add(item)
# otherwise, add it to the unique_items set
else:
unique_items.add(item)
# print the repeated items
print(f"The repeated items in the tuple are: {repeated_items}")
12. Write a Python Program ,print the number in words for example:1234=> One Two three Four
num = input("Enter a number: ")
# create a dictionary to map each digit to its corresponding word
digit_words = {
Downloaded From Campusify!
"0": "Zero",
"1": "One",
"2": "Two",
"3": "Three",
"4": "Four",
"5": "Five",
"6": "Six",
"7": "Seven",
"8": "Eight",
"9": "Nine"
}
# iterate through each digit in the number and print its corresponding word
for digit in num:
print(digit_words[digit], end=" ")
13. Write a program to create two matrices and perform addition, subtraction, multiplication
anddivision on matrix using numpy package.
import numpy as np
matrix1 = np.array([[1, 2], [3, 4]])
matrix2 = np.array([[5, 6], [7, 8]])
addition_result = matrix1 + matrix2
subtraction_result = matrix1 - matrix2
multiplication_result = np.dot(matrix1, matrix2)
division_result = np.divide(matrix1, matrix2)
print("Addition Result:")
print(addition_result)
print("Subtraction Result:")
print(subtraction_result)
print("Multiplication Result:")
print(multiplication_result)
print("Division Result:")
print(division_result)
14. Write a program to concatenate two string using user defined module.
Module file :
str_concat.py :
def concat(str1, str2):
return str1 + str2

Main file :
concat_str :
import str_concat
Downloaded From Campusify!
string1 = input("Enter first string: ")
string2 = input("Enter second string: ")
result = string_concat.concat(string1, string2)
print("Concatenated String: ", result)
15. Write a program to perform arithmetic operations using user defined module.
Module file :
arithmetic.py :
def add(num1, num2):
return num1 + num2

def subtract(num1, num2):


return num1 - num2

def multiply(num1, num2):


return num1 * num2

def divide(num1, num2):


return num1 / num2

Main file :
Operate.py:
import arithmetic
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
sum_result = arithmetic.add(num1, num2)
difference_result = arithmetic.subtract(num1, num2)
product_result = arithmetic.multiply(num1, num2)
quotient_result = arithmetic.divide(num1, num2)
print("Sum: ", sum_result)
print("Difference: ", difference_result)
print("Product: ", product_result)
print("Quotient: ", quotient_result)
16. Implement a class student with data members; Name, Roll number, Marks. Create suitable
method for reading, printing student’s details & calculate percentage.
class Student:
def init (self, name, roll_number, marks):
self.name = name
self.roll_number = roll_number
self.marks = marks
def read_details(self):
self.name = input("Enter student name: ")
self.roll_number = input("Enter roll number: ")
print("Enter marks for 5 subjects:")
self.marks = []
for i in range(5):
mark = float(input(f"Enter mark for subject {i+1}: "))
self.marks.append(mark)
Downloaded From Campusify!
def print_details(self):
print("Name: ", self.name)
print("Roll Number: ", self.roll_number)
print("Marks: ", self.marks)

def calculate_percentage(self):
total_marks = 500 # Assuming maximum marks is 500 for 5 subjects
marks_obtained = sum(self.marks)
percentage = (marks_obtained / total_marks) * 100
return percentage

# Create a new Student object and read details


student1 = Student("", "", [])
student1.read_details()

# Print the details of the student


print("Details of the student:")
student1.print_details()

# Calculate and print the percentage of the student


percentage = student1.calculate_percentage()
print("Percentage: ", percentage)
17. Implement a program of Simple inheritance.
class Animal:
def speak(self):
print("Animal Speaking")
#child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking")
d = Dog()
d.bark()
d.speak()

18. Implement a program of multilevel inheritance.


class Animal:
def speak(self):
Downloaded From Campusify!
print("Animal Speaking")
#The child class Dog inherits the base class Animal
class Dog(Animal):
def bark(self):
print("dog barking")
#The child class Dogchild inherits another child class Dog
class DogChild(Dog):
def eat(self):
print("Eating bread...")
d = DogChild()
d.bark()
d.speak()
d.eat()
19. Implement a program of multiple inheritance.
class Mother:
mothername = ""
def mother(self):
print(self.mothername)
class Father:
fathername = ""
def father(self):
print(self.fathername)
class Son(Mother, Father):
def parents(self):
print("Father :", self.fathername)
print("Mother :", self.mothername)
s1 = Son()
s1.fathername = "RAM"
s1.mothername = "SITA"
s1.parents()
20. Write a program to implement concept of overriding.
class Parent: # define parent class
def myMethod(self):
print('Calling parent method')
class Child(Parent): # define child class
def myMethod(self):
Downloaded From Campusify!
print('Calling child method')
c = Child() # instance of child
c.myMethod()
p=Parent()
p.myMethod()
21. Write a program to read and write students information using two classes using simple
inheritance.
class Student_Details:
def init (self):
self.name = input("Enter Your Name: ")
self.cname = input("Enter Your College Name: ")
self.roll = int(input("Enter Your Roll Number: "))
class Temp(Student_Details):
def display(self):
print("============ Student Details are ==========")
print("Name: ", self.name)
print("College Name:", self.cname)
print("Roll number:", self.roll)
obj1 = Temp()
obj1.display()
22. Write a python function that accept a string and calculate the number of upper case letters
andlower case letters.

string=input("Enter a string : ")

def count_upper_lower(string):

upper_count = 0

lower_count = 0

for letter in string:

if letter.isupper():

upper_count += 1

elif letter.islower():

lower_count += 1

print("Number of uppercase letters:", upper_count)

print("Number of lowercase letters:", lower_count)


count_upper_lower(string) Downloaded From Campusify!
23. Write a program to implement predefine exception.
try:
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))
result = num1/num2
print("The result of division is:", result)
except ValueError:
print("Please enter a valid integer")
except ZeroDivisionError:
print("Division by zero is not allowed")
except Exception as e:
print("An error occurred:", e)
24. Write a program to implement User defined exception.
class MyException(Exception):
def init (self, message):
super(). init (message)
try:
age = int(input("Enter your age: "))
if age < 18:
raise MyException("Sorry, you are not eligible for voting.")
else:
print("You are eligible for voting.")
except MyException as me:
print(me)
except Exception as e:
print("Error:", e)

Downloaded From Campusify!

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy