Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
19 views

Python Practicals (1)

The document contains a series of practical Python programming exercises covering various topics such as printing Python version, basic input/output operations, mathematical calculations, control flow, data structures, and functions. Each exercise includes code snippets for tasks like converting currencies, calculating areas, checking even/odd numbers, and manipulating lists and dictionaries. The document serves as a comprehensive guide for beginners to practice and enhance their Python programming skills.

Uploaded by

sanskrutinile06
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Python Practicals (1)

The document contains a series of practical Python programming exercises covering various topics such as printing Python version, basic input/output operations, mathematical calculations, control flow, data structures, and functions. Each exercise includes code snippets for tasks like converting currencies, calculating areas, checking even/odd numbers, and manipulating lists and dictionaries. The document serves as a comprehensive guide for beginners to practice and enhance their Python programming skills.

Uploaded by

sanskrutinile06
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Practical1

1.Print the version of Python


import platform
print("Python version:", platform.python_version())
Practical2

1. Write a Python program to display your name using Interactive Mode


name = input("Enter name: ")
print("Name is", name)

2.Write a Python program to display “MSBTE” using Script Mode


print("MSBTE")
practical3

1. Write a program to convert U.S. dollars to Indian rupees.


usd = float(input("Enter amount in U.S. Dollars: "))
inr = usd * 73
print("dollor is ",usd ,"indin rupee after converting ",inr)

2. Write a program to convert bits to Megabytes, Gigabytes and Terabytes


bits = float(input("Enter the number of bits: "))
bits_in_byte = 8
bytes_in_kilobyte = 1024
kilobytes_in_megabyte = 1024
megabytes_in_gigabyte = 1024
gigabytes_in_terabyte = 1024
bytes = bits / bits_in_byte
megabytes = bytes / (bytes_in_kilobyte * kilobytes_in_megabyte)
gigabytes = megabytes / megabytes_in_gigabyte
terabytes = gigabytes / gigabytes_in_terabyte
print("Bits:", bits, "bits")
print("Megabytes:", round(megabytes, 6), "MB")
print("Gigabytes:", round(gigabytes, 6), "GB")
print("Terabytes:", round(terabytes, 6), "TB")

3. Write a program to find the square root of a number


import math
number = float(input("Enter a number: "))
square_root = math.sqrt(number)
print("The square root of", number, "is", square_root)

4. Write a program to find the area of Rectangle


length = float(input("Enter the length of the rectangle: "))
width = float(input("Enter the width of the rectangle: "))
area = length * width
print("The area of the rectangle is:", area)

5. Write a program to calculate area and perimeter of the square


side = float(input("Enter the side length of the square: "))
area = side *side
perimeter = 4 * side
print("The area of the square is:", area)
print("The perimeter of the square is:", perimeter)

6. Write a program to calculate surface volume and area of a cylinder.


import math
radius = float(input("Enter the radius of the cylinder: "))
height = float(input("Enter the height of the cylinder: "))
surface_area = 2 * math.pi * radius * (radius + height)
volume = math.pi * radius**2 * height
print("Surface Area of the cylinder is:", surface_area)
print("Volume of the cylinder is:", volume)

7. Write a program to swap the value of two variables


a = float(input("Enter the value of a: "))
b = float(input("Enter the value of b: "))
a, b = b, a
print("After swapping:")
print("Value of a:", a)
print("Value of b:", b)
Practical4

1. Write a program to check whether a number is even or odd


number = int(input("Enter a number: "))
if number % 2 == 0:
print("The number", number, "is even.")
else:
print("The number", number, "is odd.")

2. Write a program to find out absolute value of an input number


number = float(input("Enter a number: "))
absolute_value = abs(number)
print("The absolute value of", number, "is", absolute_value)

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)

4. Write a program to check if the input year is a leap year of not

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


if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print(year, "is a leap year.")
else: print(year, "is not a leap year.")

5. Write a program to check if a Number is Positive, Negative or Zero


number = float(input("Enter a number: "))
if number > 0:
print("The number", number, "is positive.")
elif number < 0:
print("The number", number, "is negative.")
else:
print("The number is zero.")

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

5. Write a Python program to calculate factorial of a number


num = int(input("Enter a number: "))
result = 1
for i in range(1, num + 1):
result *= i
print("The factorial of is:",result)

6. Write a Python Program to Reverse a Given Number


n = int(input("Enter a number: "))
rev = 0
while n > 0:
digit = n % 10
rev = rev * 10 + digit
n //= 10
print("The reversed number is:",rev )
7. Write a Python program takes in a number and finds the sum of digits in a
Number.
num = int(input("Enter a number: "))
sum_numbers = 0
for i in range(1, num + 1):
sum_numbers += i
print("The sum of numbers is ", sum_numbers)

8. Write a Python program that takes a number and checks whether it is a


palindrome
or not.
num = int(input("Enter a number: "))
original_num = num
reversed_num = 0
while num > 0:
digit = num % 10
reversed_num = reversed_num * 10 + digit
num //= 10
if original_num == reversed_num:
print("The number is a palindrome")
else:
print("The number is not a palindrome")
Practical6

1. Write a Python program to sum all the items in a list.


numbers = [1, 2, 3, 4, 5]
total = 0
for num in numbers:
total =total+ num
print("The sum of all items in the list is:", total)

2. Write a Python program to multiplies all the items in a list.


numbers = [1, 2, 3, 4, 5]
product = 1
for num in numbers:
product = product * num
print("The product of all items in the list is:", product)

3. Write a Python program to get the largest number from a list.


numbers = [10, 20, 4, 45, 99]
largest = numbers[0]
for num in numbers:
if num > largest:
largest = num
print("The largest number in the list is:", largest)

4. Write a Python program to get the smallest number from a list.


numbers = [10, 20, 4, 45, 99]
smallest = numbers[0]
for num in numbers:
if num < smallest:
smallest = num
print("The smallest number in the list is:", smallest)
5. Write a Python program to reverse a list.
numbers = [10, 20, 30, 40, 50]
reversed_list = []
for num in numbers:
reversed_list = [num] + reversed_list
print("The reversed list is:", reversed_list)

6. Write a Python program to find common items from two lists.


list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]
common_items = []
for item in list1:
if item in list2:
common_items.append(item)
print("Common items:", common_items)

7. Write a Python program to select the even items of a list.


numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_items = []
for num in numbers:
if num % 2 == 0:
even_items.append(num)
print("Even items:", even_items)
Practical7

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)

2. Write a Python program to find the repeated items of a tuple.


numbers = (1, 2, 3, 4, 5, 1, 2, 6, 7, 8, 2)
seen = set()
repeated_items = []
for num in numbers:
if num in seen:
repeated_items.append(num)
else:
seen.add(num)
print("Repeated items:", repeated_items)

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)

2. Write a Python program to perform following operations on set: intersection of


sets, union of sets, set difference, symmetric difference, clear a set.
set1={1,2,3,4,5}
set2={4,5,6,7,8}
intersection=set1&set2
print("Intersection of sets:",intersection)
union=set1|set2
print("Union of sets:",union)
difference=set1-set2
print("Set difference (set1-set2):",difference)
symmetric_difference=set1^set2
print("Symmetric difference:",symmetric_difference)
set1.clear()
print("Set1 after clearing:",set1)
3. Write a Python program to find maximum and the minimum value in a set.
my_set = {10, 20, 30, 40, 50}
max_value = max(my_set)
min_value = min(my_set)
print("Maximum value:", max_value)
print("Minimum value:", min_value)

4. Write a Python program to find the length of a set.


my_set = {10, 20, 30, 40, 50}
length = len(my_set)
print("Length of the set:", length)
Practical9

1. Write a Python script to sort (ascending and descending) a dictionary by value.


from operator import itemgetter
my_dict={'a':50,'b':10,'c':30,'d':40,'e':20}
ascending=dict(sorted(my_dict.items(),key=itemgetter(1)))
print("Ascending order:",ascending)
descending=dict(sorted(my_dict.items(),key=itemgetter(1),reverse=True))
print("Descending order:",descending)

2. Write a Python script to concatenate following dictionaries to create a new one.


a. Sample Dictionary:
b. dic1 = {1:10, 2:20}
c. dic2 = {3:30, 4:40}
d. dic3 = {5:50,6:60}
dic1={1:10,2:20}
dic2={3:30,4:40}
dic3={5:50,6:60}
result=dic1.copy()
result.update(dic2)
result.update(dic3)
print(result)

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)

5. Write a Python program to find the highest 3 values in a dictionary.


my_dict={'a':100,'b':200,'c':300,'d':400,'e':500}
sorted_values=sorted(my_dict.values(),reverse=True)
highest_three=sorted_values[:3]
print(highest_three)
Practical10

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)

2. Write a Python function to calculate the factorial of a number (a non-negative


integer). The function accepts the number as an argument.
def factorial(num):
result=1
if num < 0:
print("Factorial does not exist for negative numbers")
else:
for i in range(1,num+1):
result=result*i
print("Factorial of",num,"is",result)
number=int(input("Enter a number: "))
factorial(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)

2. Write a Python program to concatenate two strings.


str1=input("Enter first string:")
str2=input("Enter second string:")
result=str1+str2
print("Concatenated string:",result)
3. Write a NumPy program to generate six random integers between 10 and 30.
import numpy as np
random_integers=np.random.randint(10,30,6)
print("Random integers:",random_integers)
Practical14

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()

3. Write a Python program to create a class 'Degree' having a method 'getDegree'


that prints "I got a degree". It has two subclasses namely 'Undergraduate' and
'Postgraduate' each having a method with the same name that prints "I am an
Undergraduate" and "I am a Postgraduate" respectively. Call the method by
creating an object of each of the three classes.
class Degree:
def getDegree(self):
print("I got a degree")
class Undergraduate(Degree):
def getDegree(self):
print("I am an Undergraduate")
class Postgraduate(Degree):
def getDegree(self):
print("I am a Postgraduate")
def main():
degree = Degree()
undergrad = Undergraduate()
postgrad = Postgraduate()
print("Calling through Degree class:")
degree.getDegree()
print("\nCalling through Undergraduate class:")
undergrad.getDegree()
print("\nCalling through Postgraduate class:")
postgrad.getDegree()
if __name__ == "__main__":
main()
Practical15

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

1.Write a Python program to Check for ZeroDivisionError Exception.


try:
num1 = int(input("Enter numerator: "))
num2 = int(input("Enter denominator: "))
result = num1 / num2
print("Result:", result)
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")

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)

You might also like