0% found this document useful (0 votes)
1K views14 pages

Python Imp Program Msbte Campus Academy

The document provides examples of Python programs to demonstrate various concepts like loops, functions, classes, inheritance, exception handling, file handling, modules and packages. The programs cover basics like Fibonacci series, swapping tuples, reading and writing files to OOPs concepts like creating classes, inheritance and more advanced topics like user defined packages and exception handling.

Uploaded by

tanupandav333
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)
1K views14 pages

Python Imp Program Msbte Campus Academy

The document provides examples of Python programs to demonstrate various concepts like loops, functions, classes, inheritance, exception handling, file handling, modules and packages. The programs cover basics like Fibonacci series, swapping tuples, reading and writing files to OOPs concepts like creating classes, inheritance and more advanced topics like user defined packages and exception handling.

Uploaded by

tanupandav333
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/ 14

msbtecampus.

com By :- Vishal Chavare

PYTHON IMP PRO


1. Write a python program to print Fibonacci series up to n terms

n=int(input("Enter value of n : "))


a=0
b=1
i=0
print("Fibonacci series is..")
while i<n:
print(a)
c=a+b
a=b
b=c
i=i+1

2. Write a program to input any two tuples and interchange the tuple variable

a=(1,2,3,4,5)
b=(11,12,13,14,24,35)
a,b=b,a
print(a)
print(b)

3. Write a python program to read contents of first.txt file and write same
content in second.txt file

print("how many lines you want to write : ")


n=int(input())
outfile=open("one.txt","wt")
for i in range(n):
print("Enter the line..")
line=input()
outfile.write("\n"+line)
outfile.close()

infile=open("one.txt","rt")
outfile=open("two.txt","wt")
i=0
for i in range(n+1):
line=infile.readline()
outfile.write("\n"+line)
infile.close()
outfile.close()

infile=open("two.txt","rt")
print(infile.read())
infile.close()

@pritamundhe MSBTE CAMPUS ACADEMY


msbtecampus.com By :- Vishal Chavare
4. Write a python program to calculate factorial of given number using
function.

def factorial(n):
if n==0:
return 1
else:
return n*factorial(n-1)

num=int(input("Enter number to find factorial"))

if num<0:
print("Factorial is not defined for nr=egative numbers!!")
else:
result=factorial(num)
print("Factorial of : ",num," is ",result)

5. Design a class Employee with data members: name, department and salary.
Create suitable methods for reading and printing employee information

class Employee:
def __init__(self):
self.name=""
self.department=""
self.salary=0.0

def readinfo(self):
self.name=input("Enter your name : ")
self.department=input("Enter your Department : ")
self.salary=float(input("Enter your Salary : "))

def dispinfo(self):
print("Name of employee is : "+self.name)
print("Department of employee is : "+self.department)
print("Salary of employee is : ",self.salary)

employee= Employee()

employee.readinfo()
employee.dispinfo()

@pritamundhe MSBTE CAMPUS ACADEMY


msbtecampus.com By :- Vishal Chavare
6. Design a python program to calculate area of triangle and circle and print
the result

import math

base=float(input("Enter the base of triangle : "))


height=float(input("Enter the height of triangle :"))

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

atriangle=0.5*base*height
print("Area of trianngle is : ",atriangle)

acircle=math.pi*radius**2
print("Area of Circle is : ",acircle)

7. Design a python program which will throw exception if the value entered
by user is less than zero

def validate(value):
if value<0:
raise ValueError("Value cannot be less than 0 ")

try:
num=int(input("Enter a value : "))
validate(num)
print("Value is valid")

except ValueError as e:
print("Error : "+str(e))

8. Write a Python program to concatenate two strings

def con(str1,str2):
concatenated=str1+str2
return concatenated

string="Hello "
string1="World!"

result=con(string,string1)
print("Concatenated string are : "+result)

@pritamundhe MSBTE CAMPUS ACADEMY


msbtecampus.com By :- Vishal Chavare
9. Write a program to create class EMPLOYEE with ID and NAME and
display its contents.

class Employee:
def __init__(self):
self.id=""
self.name=""

def readin(self):
self.id=int(input("Enter your id :"))
self.name=input("Enter your name :")

def printin(self):
print("Employee id is : ",self.id)
print("Employee name is : "+self.name)

employee= Employee()

employee.readin()
employee.printin()

10.Write a program for importing module for addition and subtraction of two
numbers.

Mathop.py

def add_num(a, b):


return a + b

def sub_num(a, b):


return a - b

ex.py

import mathop

num1 = float(input("Enter the first number: "))


num2 = float(input("Enter the second number: "))

resultadd = mathop.add_num(num1, num2)

resultsub = mathop.sub_num(num1, num2)

print("Addition:", resultadd)
print("Subtraction:", resultsub)

@pritamundhe MSBTE CAMPUS ACADEMY


msbtecampus.com By :- Vishal Chavare
11.Write a program to create dictionary of students that includes their ROLL
NO. and NAME.
i) Add three students in above dictionary
ii) Update name = ‘Shreyas’ of ROLL NO = 2
iii) Delete information of ROLL NO = 1

students = {}

students[1] = 'Pritam'
students[2] = 'Sameer'
students[3] = 'Saurabh'

print("Initial dictionary of students:")


print(students)

students[2] = 'Shreyas'

print("\nDictionary after updating name:")


print(students)

del students[1]

print("\nDictionary after deleting information:")


print(students)

12.Write a program illustrating use of user defined package in python.

Directory file
- my_program.py
- my_package/
- mathop.py
- __init__.py

# mathop.py

def addnum(a, b):


return a + b

def subnum(a, b):


return a - b

@pritamundhe MSBTE CAMPUS ACADEMY


msbtecampus.com By :- Vishal Chavare

# my_program.py

from my_package import mathop

num1 = float(input("Enter the first number: "))


num2 = float(input("Enter the second number: "))

result_add = mathop.addnum(num1, num2)

result_subtract = mathop.subnum(num1, num2)

print("Addition:", result_add)
print("Subtraction:", result_subtract)

13.Write a program to open a file in write mode and append some contents at
the end of file

print("How many lines you want to write")


n=int(input())
outfile=open("one.txt","at")
for i in range(n):
outfile.write(input("Enter the line"))
outfile.close()
print("File Written Successfully")
infile=open("one.txt","rt")
line=infile.read()
print(line)
infile.close()

14.Write a program to implement the concept of inheritance in python.

#Single Inheritance

class Parent:
def fun1(self):
print("This is fun1 of Parent class")

class Child(Parent):
def fun2(self):
print("This is fun2 of Child class")

ob=Child()
ob.fun1()
ob.fun2()

@pritamundhe MSBTE CAMPUS ACADEMY


msbtecampus.com By :- Vishal Chavare
#Multiple Inheritance
class Parent:
def fun1(self):
print("This is fun1 of Parent class")

class Child:
def fun2(self):
print("This is fun2 of Child class")

class child(Parent,Child):
def fun3(self):
print("Hello i am class 3")
ob=child()
ob.fun1()
ob.fun2()
ob.fun3()

#Multilevel Inheritance
class Parent:
def fun1(self):
print("This is fun1 of Parent class")

class Child(Parent):
def fun2(self):
print("This is fun2 of Child class")

class child(Child):
def fun3(self):
print("Hello i am class 3")

ob=child()
ob.fun1()
ob.fun2()
ob.fun3()

#Hirarchical Inheritance
class Parent:
def fun1(self):
print("This is fun1 of Parent class")

class Child(Parent):
def fun2(self):
print("This is fun2 of Child class")

class child(Parent):
def fun3(self):
print("Hello i am class 3")

ob=child()
ob1=Child()
ob.fun1()
ob1.fun2()
ob.fun3()

@pritamundhe MSBTE CAMPUS ACADEMY


msbtecampus.com By :- Vishal Chavare
15.Write python program to illustrate if else ladder.

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

if num > 0:
print("The number is positive.")
elif num < 0:
print("The number is negative.")
else:
print("The number is zero.")

16.Write Python code for finding greatest among four numbers.

list1 = [ ]
num = int(input("Enter number of elements in list: "))
for i in range(1, num + 1):
element = int(input("Enter elements: "))
list1.append(element)
print("Largest element is:", max(list1))

17.Write python code to add two numbers given as input from


command line arguments and print its sum.

import sys
x=int(sys.argv[1])
y=int(sys.argv[2])
sum=x+y
print("The addition is :",sum)

18.Write python program to perform following operations on Set;


i) Create set
ii) Access set Element
iii) Update set
iv) Delete set
S={10,20,30,40,50}
print (S)
S.add(60)
print(S)
S.update(['A','B'])
print(S)
S.discard(30)
print(S)
S.remove('A')
print(S)
S.pop()
print(S)

@pritamundhe MSBTE CAMPUS ACADEMY


msbtecampus.com By :- Vishal Chavare
19.Design a class student with data members; Name, roll number address.
Create suitable method for reading and printing students details.

class Student:
def __init__(self):
self.name = ""
self.roll_number = ""
self.address = ""

def read_details(self):
self.name = input("Enter student's name: ")
self.roll_number = input("Enter student's roll number: ")
self.address = input("Enter student's address: ")

def print_details(self):
print("Student's Name:", self.name)
print("Roll Number:", self.roll_number)
print("Address:", self.address)

student1 = Student()

student1.read_details()
print("Student Details:")
student1.print_details()

20.Create a parent class named Animals and a child class Herbivorous which
will extend the class Animal. In the child class Herbivorous over side the
method feed ( ). Create a object of the class Herbivorous and call the
method feed.

class Animal:
def feed(self):
print("Animal is being fed.")

class Herbivorous(Animal):
def feed(self):
print("Herbivorous animal is being fed with plants.")

herbivorous_animal = Herbivorous()

herbivorous_animal.feed()

@pritamundhe MSBTE CAMPUS ACADEMY


msbtecampus.com By :- Vishal Chavare
21.Write a python program to print the following pyramid

for i in range(1,5):
for j in range(1,i+1):
print(j,end=' ')
print()

22.Write a python program to swap value of two variables

def swap(a,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)

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


b=int(input("Enter second number : "))
swap(a,b)

23.Write a python program to generate six random integers between 20 to 50

import random

random_integers = []

for _ in range(6):
random_int = random.randint(20, 50)
random_integers.append(random_int)

print("Random Integers:", random_integers)

24.Write a python program to print factorial of a given number.

def factorial(n):
if n==0:
return 1
else:
return n*factorial(n-1)

num=int(input("Enter number to find factorial"))

if num<0:
print("Factorial is not defined for nr=egative numbers!!")
else:
result=factorial(num)
print("Factorial of : ",num," is ",result)

@pritamundhe MSBTE CAMPUS ACADEMY


msbtecampus.com By :- Vishal Chavare
25.Write a python program to add two numbers using function.

def add_numbers(a, b):


sum = a + b
return sum

a=int(input("Enter value of a : "))


b=int(input("Enter value of b : "))

result = add_numbers(a,b)
print(result)

26.Write a python program to check for Zero Division Error Exception.

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

result = dividend / divisor


print("Result:", result)

except ZeroDivisionError:
print("Error: Division by zero is not allowed.")

except ValueError:
print("Error: Invalid input. Please enter integer values.")

except Exception as e:
print("An error occurred:", e)

27.Design class rectangle with data members length and breadth. Create
suitable methods for reading and printing the area and perimeter of
rectangle

class Rectangle:
def __init__(self):
self.length = 0
self.breadth = 0

def read_dimensions(self):
self.length = float(input("Enter the length of the rectangle: "))
self.breadth = float(input("Enter the breadth of the rectangle: "))

def area(self):
rarea = self.length * self.breadth
return rarea

def perimeter(self):
rperimeter = 2 * (self.length + self.breadth)

@pritamundhe MSBTE CAMPUS ACADEMY


msbtecampus.com By :- Vishal Chavare
return rperimeter

def print_details(self):
print("Area:", self.area())
print("Perimeter:", self.perimeter())

rectangle1 = Rectangle()

rectangle1.read_dimensions()
rectangle1.print_details()

28.Write a python program to demonstrate the use of any six built in


mathematical functions
import math

# 1. Absolute value
num1 = -5
abs_value = abs(num1)
print("Absolute value of", num1, "is", abs_value)

# 2. Square root
num2 = 16
sqrt_value = math.sqrt(num2)
print("Square root of", num2, "is", sqrt_value)

# 3. Exponential
num3 = 2
exp_value = math.exp(num3)
print("Exponential of", num3, "is", exp_value)

# 4. Trigonometric functions
angle = math.pi / 4
sin_value = math.sin(angle)
cos_value = math.cos(angle)
tan_value = math.tan(angle)
print("Sine of", angle, "is", sin_value)
print("Cosine of", angle, "is", cos_value)
print("Tangent of", angle, "is", tan_value)

# 5. Rounding
num4 = 3.75
round_value = round(num4)
print("Rounded value of", num4, "is", round_value)

# 6. Ceiling and floor


num5 = 4.2
ceil_value = math.ceil(num5)
floor_value = math.floor(num5)
print("Ceiling value of", num5, "is", ceil_value)
print("Floor value of", num5, "is", floor_value)

@pritamundhe MSBTE CAMPUS ACADEMY


msbtecampus.com By :- Vishal Chavare

29.Write a python program to read contents of abc.txtfile and write same


content in xyz.txtfile.

print("how many lines you want to write : ")


n=int(input())
outfile=open("abc.txt","wt")
for i in range(n):
print("Enter the line..")
line=input()
outfile.write("\n"+line)
outfile.close()

infile=open("abc.txt","rt")
outfile=open("pqr.txt","wt")
i=0
for i in range(n+1):
line=infile.readline()
outfile.write("\n"+line)
infile.close()
outfile.close()

infile=open("pqr.txt","rt")
print(infile.read())
infile.close()

30.Write a python program to calculate area of rectangle and area of square


using method overloading

class ShapeCalculator:
def calculate_area(self, length, breadth=None):
if breadth is None:
area = length * length
else:
area = length * breadth
return area

calculator = ShapeCalculator()

rectangle_area = calculator.calculate_area(5, 10)


print("Area of rectangle:", rectangle_area)

square_area = calculator.calculate_area(7)
print("Area of square:", square_area)

@pritamundhe MSBTE CAMPUS ACADEMY


msbtecampus.com By :- Vishal Chavare
31.Write a program to find the following in the list
= [3, 5, -5, -3, 10, 20, 100]
i) Largest number in the list
ii) Smallest number in the list
iii) Sum of all the elements in the list
iv) Total number of elements in the list
v) Sort the given list
vi) Reverse the list

my_list = [3, 5, -5, -3, 10, 20, 100]

# i) Largest number in the list


largest_num = max(my_list)
print("Largest number:", largest_num)

# ii) Smallest number in the list


smallest_num = min(my_list)
print("Smallest number:", smallest_num)

# iii) Sum of all the elements in the list


sum_of_elements = sum(my_list)
print("Sum of elements:", sum_of_elements)

# iv) Total number of elements in the list


num_of_elements = len(my_list)
print("Total number of elements:", num_of_elements)

# v) Sort the given list


sorted_list = sorted(my_list)
print("Sorted list:", sorted_list)

# vi) Reverse the list


reversed_list = list(reversed(my_list))
print("Reversed list:", reversed_list)

Reference:
Click

@pritamundhe MSBTE CAMPUS ACADEMY

You might also like