Python Practicals (1)
Python Practicals (1)
3. Write a program to check the largest number among the three numbers
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
num3 = float(input("Enter the third number: "))
if num1 >= num2 and num1 >= num3:
largest = num1
elif num2 >= num1 and num2 >= num3:
largest = num2
else:
largest = num3
print("The largest number among", num1, num2, "and", num3, "is", largest)
6. Write a program that takes the marks of 5 subjects and displays the grade.
subject1 = int(input("Enter marks for subject 1: "))
subject2 = int(input("Enter marks for subject 2: "))
subject3 = int(input("Enter marks for subject 3: "))
subject4 = int(input("Enter marks for subject 4: "))
subject5 = int(input("Enter marks for subject 5: "))
total = subject1 + subject2 + subject3 + subject4 + subject5
average = total // 5
if average >= 90:
grade = "A"
elif average >= 80:
grade = "B"
elif average >= 70:
grade = "C"
elif average >= 60:
grade = "D"
else:
grade = "F"
print("Grade:", grade)
Practical5
1. Print the following patterns using loop:
a. *
**
***
****
rows = 4
for i in range(1, rows + 1):
print("*" * i)
b. *
***
*****
***
*
rows = 3
for i in range(rows):
print(" " * (rows - i - 1) + "*" * (2 * i + 1))
for i in range(rows - 2, -1, -1):
print(" " * (rows - i - 1) + "*" * (2 * i + 1)
c. 1010101
10101
101
1
rows = 4
for i in range(rows):
print(" " * i, end="")
for j in range(2 * (rows - i) - 1):
print("1" if j % 2 == 0 else "0", end="")
print()
2. Write a Python program to print all even numbers between 1 to 100 using while
Loop.
num = 2
while num <= 100:
print(num, end=" ")
num += 2
3. Write a Python program to find the sum of first 10 natural numbers using for loop.
sum_of_numbers = 0
for i in range(1, 11):
sum_of_numbers += i
print("The sum of the first 10 natural numbers is:", sum_of_numbers)
4. Write a Python program to print Fibonacci series.
n = int(input("Enter the number of terms: "))
a, b = 0, 1
print("Fibonacci Series:")
for _ in range(n):
print(a, end=" ")
a, b = b, a + b
1.Create a tuple and find the minimum and maximum number from it.
numbers = (10, 20, 30, 40, 50)
min_number = min(numbers)
max_number = max(numbers)
print("The minimum number is:", min_number)
print("The maximum number is:", max_number)
3. Print the number in words for Example: 1234 => One Two Three Four
num = input("Enter a number: ")
words = ""
for digit in num:
if digit == '0':
words += 'Zero '
elif digit == '1':
words += 'One '
elif digit == '2':
words += 'Two '
elif digit == '3':
words += 'Three '
elif digit == '4':
words += 'Four '
elif digit == '5':
words += 'Five '
elif digit == '6':
words += 'Six '
elif digit == '7':
words += 'Seven '
elif digit == '8':
words += 'Eight '
elif digit == '9':
words += 'Nine '
print("Number in words:", words)
Practical8
1. Write a Python program to create a set, add member(s) in a set and remove one
item from set.
my_set = {1, 2, 3, 4, 5}
my_set.add(6)
my_set.update([7, 8, 9])
my_set.remove(4)
print("Final set:", my_set)
3. Write a Python program to combine two dictionary adding values for common
keys.
a. d1 = {'a': 100, 'b': 200, 'c':300}b. d2 = {'a': 300, 'b': 200, 'd':400}
d1={'a':100,'b':200,'c':300}
d2={'a':300,'b':200,'c':400}
result=d1.copy()
for key,value in d2.items():
if key in result:
result[key]=result[key]+value
else:
result[key]=value
print(result)
4. Write a Python program to print all unique values in a dictionary.
a. Sample Data: [{"V":"S001"}, {"V": "S002"}, {"VI": "S001"}, {"VI": "S005"},
{"VII":"S005"}, {"V":"S009"}, {"VIII":"S007"}]
data=[{"V":"S001"},{"V":"S002"},{"VI":"S001"},{"VI":"S005"},{"VII":"S005"},{"V":"S009"}
,{"VIII":"S007"}]
values=[]
for item in data:
for key in item:
values.append(item[key])
unique_values=list(set(values))
print(unique_values)
1.Write a Python function that accepts a string and calculate the number of upper
case letters and lower case letters.
def count_case(s):
upper=0
lower=0
for char in s:
if char.isupper():
upper=upper+1
elif char.islower():
lower=lower+1
print("Upper case letters:",upper)
print("Lower case letters:",lower)
string=input("Enter a string: ")
count_case(string)
2. Write a Python program to generate a random float where the value is between 5
and 50 using Python math module.
import random
random_float=random.uniform(5,50)
print(random_float)
Practical11
1.Write a Python function that takes a number as a parameter and check the number
is prime or not.
def is_prime(num):
if num <= 1:
print(num,"is not a prime number")
else:for i in range(2,num):
if num % i == 0:
print(num,"is not a prime number")
break
else:
print(num,"is a prime number")
number=int(input("Enter a number: "))
is_prime(number)
3. Write a Python function that accepts a string and calculate the number of upper
case letters and lower case letters.
def count_case(s):
upper=0
lower=0
for char in s:
if char.isupper():
upper=upper+1
elif char.islower():
lower=lower+1
print("Upper case letters:",upper)
print("Lower case letters:",lower)
string=input("Enter a string: ")
count_case(string)
Practical12
1.Write a Python program to create a user defined module that will ask your college
name and will display the name of the college.
Module:
def get_college_name():
college_name = input("Enter your college name: ")
print("Your college name is:", college_name)
Main program:
import college_module
college_module.get_college_name()
2. Write a Python program that will calculate area and circumference of circle using
inbuilt Math Module
import math
radius = float(input("Enter the radius of the circle: "))
area = math.pi * radius ** 2
circumference = 2 * math.pi * radius5
print("Area of the circle:", area)
print("Circumference of the circle:", circumference)
3. Write a Python program that will display Calendar of given month using Calendar
Module
import calendar
year = int(input("Enter year: "))
month = int(input("Enter month: "))
print(calendar.month(year, month))
Practical13
1. Write a Python program to create two matrices and perform addition, subtraction,
multiplication and division operation on matrix.
import numpy as np
matrix1=np.array([[1,2,3],[4,5,6],[7,8,9]])
matrix2=np.array([[9,8,7],[6,5,4],[3,2,1]])
addition=matrix1+matrix2
print("Addition of matrices:\n",addition)
subtraction=matrix1-matrix2
print("Subtraction of matrices:\n",subtraction)
multiplication=matrix1*matrix2
print("Element-wise multiplication of matrices:\n",multiplication)
division=matrix1/matrix2
print("Element-wise division of matrices:\n",division)
1.Write a Python program to create a class to print an integer and a character with
two methods having the same name but different sequence of the integer and the
character parameters. For example, if the parameters of the first method are of the
form (int n, char c), then that of the second method will be of the form (char c, int
n)
class PrintValues:
def print_data(self, *args):
if isinstance(args[0], int):
number, char = args
print(f"First method (number, char): Number = {number}, Character = {char}")
else:
char, number = args
print(f"Second method (char, number): Character = {char}, Number =
{number}")
def main():
printer = PrintValues()
printer.print_data(42, 'A')
printer.print_data('B', 100)
if __name__ == "__main__":
main()
2. 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.
class Shape:
def area(self, *args):
if len(args) == 1:
side = args[0]
area = side * side
print(f"Area of Square with side {side} = {area}")
elif len(args) == 2:
length, breadth = args
area = length * breadth
print(f"Area of Rectangle with length {length} and breadth {breadth} = {area}")
def main():
shape = Shape()
shape.area(5)
shape.area(4, 6)
if __name__ == "__main__":
main()
1. Create a class Employee with data members: name, department and salary.
Create suitable methods for reading and printing employee information
class Employee:
def __init__(self, name, department, salary):
self.name = name
self.department = department
self.salary = salary
def display_info(self):
print("Name:", self.name)
print("Department:", self.department)
print("Salary:", self.salary)
emp = Employee("sanskruti nile", "IT", 75000)
emp.display_info()
2. Python program to read and print students information using two classes using
simple inheritance.
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, student_id, course):
super().__init__(name, age)
self.student_id = student_id
self.course = course
def display_info(self):
super().display_info()
print("Student ID:", self.student_id)
print("Course:", self.course)
student = Student("sanskrutinile", 18, "1503", "Computer Science")
student.display_info()
3. Write a Python program to implement multiple inheritance
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal):
def bark(self):
print("Dog barks")
class Cat(Animal):
def meow(self):
print("Cat meows")
class Pet(Dog, Cat):
def play(self):
print("Pet is playing")
pet = Pet()
pet.speak()
pet.bark()
pet.meow()
pet.play()
practical16
2. Write a Python program to create user defined exception that will check whether
the password is correct or not?
class InvalidPasswordError(Exception):
pass
def check_password(password):
if password != "1234":
raise InvalidPasswordError("Incorrect Password")
else:
print("Password is correct")
try:
user_password = input("Enter password: ")
check_password(user_password)
except InvalidPasswordError as e:
print(e)