Unit - 1
1. Write a python program to print "Hello, World!"
# This program prints Hello, world!
print('Hello, world!')
Output:
Hello,World!
2. Write a python program to perform Arithmetic Operation.
operators in Python
a=7
b=2
print ('Sum: ', a + b)
print ('Subtraction: ', a - b)
print ('Multiplication: ', a * b)
print ('Division: ', a / b)
print ('Floor Division: ', a // b)
print ('Modulo: ', a % b)
print ('Power: ', a ** b)
Output:
Sum: 9
Subtraction: 5
Multiplication: 14
Division: 3.5
Floor Division: 3
Modulo: 1
Power: 49
3.Write a python program to accept the values for arithmatic operations.
a=int(input("Enter a value of a:"))
b=int(input("Enter a value of b:"))
print("Addition=",a+b)
print("Subtraction=",a-b)
print("Multiplication=",a*b)
print("Division=",a/b)
print("Module=",a%b)
print("Power=",a**b)
Output:
Enter a value of a:10
Enter a value of b:5
Addition= 15
Subtraction= 5
Multiplication= 50
Division= 2.0
Module= 0
Power= 100000
4. Write a Python program to swap two variables.
P = int( input("Please enter value for P: "))
Q = int( input("Please enter value for Q: "))
temp_1 = P
P=Q
Q = temp_1
print ("The Value of P after swapping: ", P)
print ("The Value of Q after swapping: ", Q)
Output:
Please enter value for P: 10
Please enter value for Q: 5
The Value of P after swapping: 5
The Value of Q after swapping: 10
5.Write a program to check if a no is odd or even using conditional statement.
num = int(input ("Enter any number to test whether it is odd or even:"))
if (num % 2) == 0:
print ("The number is even")
else:
print ("The number is odd")
Output:
Enter any number to test whether it is odd or even: 75
The number is odd
Enter any number to test whether it is odd or even: 22
The number is even
6. Write a python program to print the Fibonacci sequence up to n terms.
n = int (input("Enter the number of digits that you want in the Fibonacci sequence:"))
n1, n2 = 0, 1
count = 0
if n <= 0:
print (“The input is invalid. Please enter a positive integer.”)
elif n == 1:
print (“Fibonacci sequence up to n terms will be: “)
print (n1)
else:
print (“Fibonacci sequence up to the given terms will be: “)
while count < n:
print (n1)
nth = n1 + n2
n1 = n2
n2 = nth
count = count + 1
Output:
Enter the number of digits that you want in the Fibonacci sequence:10
Fibonacci sequence up to the given terms will be:
0
1
1
2
3
5
8
13
21
34
7. Write a python program that sorts a list of numbers in ascending order.
my_numbers = [10, 8, 3, 22, 33, 7, 11, 100, 54]
my_numbers.sort()
print(my_numbers)
Output:
[3, 7, 8, 10, 11, 22, 33, 54, 100]
8.Write a python program to find largest number from list.
list1=[20,5,82,71,90,17,65,43]
largest=max(list1)
print(largest)
Output:
90
9. Write a python program to remove duplicate values from a list.
list1=[20,5,82,71,90,175,5,20]
unique_list=list(set(list1))
print(unique_list)
Output:
[5, 71, 175, 82, 20, 90]
10. Write a python program to find factorial no using loop.
n = int (input ("Enter a number: "))
factorial = 1
if n >= 1:
for i in range (1, n+1):
factorial=factorial *i
print("Factorial of the given number is: ", factorial)
Output:
Enter a number: 5
Factorial of the given number is: 120
Unit-2
1. Write a python function that accepts a string and calculates the numbers of lowercase and
uppercase letters.
x=input("Enter the string:- ")
def char(x):
u=0
l=0
for i in x:
if i>='a' and i<='z':
l+=1
if i >='A' and i<='Z':
u+=1
print("LowerCase letter in the String",l)
print("UpperCase letter in the String",u)
char(x)
Output:
Enter the string:- ShivChhatrapatiCollege
LowerCase letter in the String 19
UpperCase letter in the String 3
2. Write a python program that writes data into a file.
file1 = open('myfile.txt', 'w')
L = ["This is Delhi \n", "This is Paris \n", "This is London \n"]
s = "Hello\n"
file1.write(s)
file1.writelines(L)
file1.close()
file1 = open('myfile.txt', 'r')
print(file1.read())
file1.close()
Output:
Hello
This is Delhi
This is Paris
This is London
3. Write a python program that handles a divide by zero exception.
def divide_numbers():
try:
X=10
Y=0
result = x / y
print("Result:", result)
except ZeroDivisionError:
print("The division by zero operation is not allowed.")
Output:
The division by zero operation is not allowed.
4.Write a python program that uses try, except, else and finally blocks.
def divide(x, y):
try:
result = x // y
except ZeroDivisionError:
print("Sorry ! You are dividing by zero ")
else:
print("Yeah ! Your answer is :", result)
finally:
print('This is always executed')
# Look at parameters and note the working of Program
divide(3, 2)
divide(3, 0)
Output:
Yeah ! Your answer is : 1.5
This is always executed
Sorry ! You are dividing by zero
This is always executed
x=0
try:
print(5 / x)
except ZeroDivisionError:
print("I am the except clause!")
else:
print("I am the else clause!")
finally:
print("I am the finally clause!")
Output:
I am the except clause!
I am the finally clause!
5. Write a python program that count no of lines in the file.
with open("myfile.txt",'r') as file:
lines=len(file.readlines())
print("Total no of lines=",lines)
Output:
Total no of lines=4
6. Write a python program to check number is palindrom or not.
s=("Enter a string:")
def is_palindrom(s):
if(s=s[::-1]):
print("This is a Palindrom")
else
print("This is not a Palindrom")
is_palindrom(s)
Output:
Enter a string:level
This is a Palindrom
Chap - 3
1.Write a python program to demonstrate the concept of Inheritance.
class Parent:
def parentMethod(self):
print ("Calling parent method")
class Child(Parent):
def childMethod(self):
print ("Calling child method")
c = Child()
c.childMethod()
c.parentMethod()
Output:
Calling child method
Calling parent method
2. Write a python program to demonstrate concept of method overriding.
class A:
def Disp(self):
print("This is Parent class Method")
class B(A):
def Disp(self):
#super().Disp()
print("This is Child class Method")
obj=B()
obj.Disp()
Output:
This is Child class Method
3. Write a python class that represents a rectangle, including methodsfor calculating ite area
and perameter.
class rectangle():
def __init__(self,breadth,length):
self.breadth=breadth
self.length=length
def area(self):
return self.breadth*self.length
a=int(input("Enter length of rectangle: "))
b=int(input("Enter breadth of rectangle: "))
obj=rectangle(a,b)
print("Area of rectangle:",obj.area())
Output:
Enter length of rectangle: 2
Enter breadth of rectangle: 3
Area of rectangle: 6
4.Write a python program to dedmonstrate the concept of polymorphism.
class India():
def capital(self):
print("New Delhi is the capital of India.")
def language(self):
print("Hindi is the most widely spoken language of India.")
def type(self):
print("India is a developing country.")
class USA():
def capital(self):
print("Washington, D.C. is the capital of USA.")
def language(self):
print("English is the primary language of USA.")
def type(self):
print("USA is a developed country.")
obj_ind = India()
obj_usa = USA()
for country in (obj_ind, obj_usa):
country.capital()
country.language()
country.type()
Output:
New Delhi is the capital of India.
Hindi is the most widely spoken language of India.
India is a developing country.
Washington, D.C. is the capital of USA.
English is the primary language of USA.
USA is a developed country.
5. Write a python program to handle an exception in a method of class.
class CustomException(Exception):
pass
def divide(a, b):
try
result = a / b
except ZeroDivisionError:
print("Division by zero!")
except CustomException as e:
print("Custom exception:", e)
else:
print("Result:", result)
finally:
print("Finally block executed.")
divide(10, 2)
divide(10, 0)
divide(10, "a")
Output:
Result: 5.0
Finally block executed.
Division by zero!
Finally block executed.
Finally block executed.
ERROR!
Traceback (most recent call last):
File "<main.py>", line 16, in <module>
File "<main.py>", line 5, in divide
TypeError: unsupported operand type(s) for /: 'int' and 'str'
6. Write a python program to demonstrate the concept of abstraction.
from abc import ABC
class Car(ABC):
def show(self):
print("Every car has 4 wheels")
@abstractmethod
def speed(self):
pass
class Maruti(Car):
def Speed(self):
print("Speed is 100km/H")
class Hyndai(car):
def speed(self):
print("Speed is 120Km/H")
obj1=Maruti()
obj1.show()
obj1.speed()
obj2=Hyundai()
obj2.show()
obj2.speed()
Output:
Every car has 4 wheels
Speed is 100km/H
Every car has 4 wheels
Speed is 120Km/H
7.Write a python program to demonstrate the concept of Encapsulation.
class A:
_a=10
__b=20
def show(self):
print("a=",self._a)
print("b=",self.__b)
obj=A()
obj.show()
print("Outside of the class:",obj._a)
print("Outside of the class:",obj.__b)
Output:
Outside of the class:10
Outside of the class:20
8. Write a python program to demonstrate multiple inheritance.
class Calculation1:
def Addition(self,a,b):
return a+b;
class Calculation2:
def Multiplication(self,a,b):
return a*b;
class Derived(Calculation1,Calculation2):
def Divide(self,a,b):
return a/b;
d = Derived()
print(d.Addition(10,20))
print(d.Multiplication(10,20))
print(d.Divide(10,20))
Output:
30
200
0.5
Chap - 4
1. Write a Python program using Matplotlib to plot a bar chart.
import matplotlib.pyplot as plt
fruits = ['Apples', 'Bananas', 'Cherries', 'Dates']
sales = [400, 350, 300, 450]
plt.bar(fruits, sales)
plt.title('Fruit Sales')
plt.xlabel('Fruits')
plt.ylabel('Sales')
plt.show()
Output:
2. Write a Python program that uses a generator to generate the Fibonacci sequence.
def fibonacci():
x, y = 0, 1
while True:
yield x
x, y = y, x + y
n = int(input("Input the number of Fibonacci numbers you want to generate? "))
print("Number of first ",n,"Fibonacci numbers:")
fib = fibonacci()
for _ in range(n):
print(next(fib),end=" ")
Output:
Input the number of Fibonacci numbers you want to generate? 10
Number of first 10 Fibonacci numbers:
0 1 1 2 3 5 8 13 21 34
3. write a python program that uses regular expression to validate an email address.
import re
email = "[email protected]"
alid = re.match(r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$', email)
if alid:
print("Valid email address")
else:
print("Invlid email address")
Output:
Valid email address
4. Write a Python program that uses list comprehension to create a new list based on an
existing one.
numbers = [1, 2, 3, 4]
doubled_numbers = [num * 2 for num in numbers]
print(doubled_numbers)
Output:
[2, 4, 6, 8]