python practical
python practical
2. Write a Python program to check and print the types of at least 5 different inbuilt
objects.
a = 10
b = 3.14
c = "Hello"
d = [1, 2, 3]
e = {'x': 1, 'y': 2}
print("Tanushree Nair\nMCA IInd SEM\nProgramming in Python\
n---------------------------------")
print(type(a))
print(type(b))
print(type(c))
print(type(d))
print(type(e))
9. Write a Python program to get a Decimal number from user and convert
it into Binary, Octal and Hexadecimal.
print("Tanushree Nair\nMCA IInd SEM\nProgramming in Python\
n---------------------------------")
n=int(input("Choose on of the below for conversion :\n1. To binary\n2. To Octal\n3. To
hexadecimal\n"))
match n:
case 1:
x=int(input("Enter a number to convert it to binary number: "))
Tanushree Nair Page 4 of 40
MCA 206: Programming in Python MCA 2nd Semester
print(bin(x))
case 2:
y=int(input("Enter a number to convert it to octal number: "))
print(oct(y))
case 3:
z=int(input("Enter a number to convert it to hexadecimal number: "))
print(hex(z))
'''match per:
case per<=50:
print E
break
case per<=65 and per>50:
print E
break
case per<=75 and per>65:
print E
break
case per<=85 and per>75:
print E
break
case per<=100 and per>85:
print E
break'''
if (per<=50):
print("E")
elif (per>50 and per<=65):
print("D")
elif (per>65 and per<=75):
print("C")
elif (per>75 and per<=85):
print("B")
else:
12.Write a Python program to get a number and find the sum and product of
its digits.
print("Tanushree Nair\nMCA IInd SEM\nProgramming in Python\
n---------------------------------")
num = input("Enter a number: ")
digit_sum = 0
digit_product = 1
gcd = math.gcd(a, b)
14. Write a Python program to find factorial of a number using while loop.
print("Tanushree Nair\nMCA IInd SEM\nProgramming in Python\
n---------------------------------")
num = int(input("Enter a number: "))
if num < 0:
print("Factorial does not exist for negative numbers.")
elif num == 0:
print("The factorial of 0 is 1.")
else:
factorial = 1
i=1
while i <= num:
factorial *= i
i += 1
print(f"The factorial of {num} is {factorial}.")
if n <= 0:
print("Please enter a positive integer.")
elif n == 1:
print("Fibonacci sequence up to 1 term:")
print(a)
else:
print(f"Fibonacci sequence up to {n} terms:")
while count < n:
print(a, end=" ")
a, b = b, a + b
count += 1
position = main_str.find(sub_str)
if position != -1:
print(f"The first occurrence of '{sub_str}' is at index {position}.")
else:
print(f"'{sub_str}' not found in the main string.")
count = main_str.count(sub_str)
24.Write a Python function to take a list of integers as input and return the
average.
print("Tanushree Nair\nMCA IInd SEM\nProgramming in Python\
n---------------------------------")
def calculate_average(numbers):
if len(numbers) == 0:
return "The list is empty, cannot calculate the average."
return sum(numbers) / len(numbers)
input_numbers = list(map(int, input("Enter a list of integers separated by space: ").split()))
average = calculate_average(input_numbers)
print(f"The average of the list is: {average}")
25.Write a Python function to take two distinct integers as input and print all
prime numbers between them.
print("Tanushree Nair\nMCA IInd SEM\nProgramming in Python\
n---------------------------------")
def is_prime(n):
if n <= 1:
return False
26.Write a Python function to take two integers as input and return both
their sum and product.
print("Tanushree Nair\nMCA IInd SEM\nProgramming in Python\
n---------------------------------")
def sum_and_product(num1, num2):
sum_result = num1 + num2
product_result = num1 * num2
return sum_result, product_result
num1 = int(input("Enter the first integer: "))
num2 = int(input("Enter the second integer: "))
sum_result, product_result = sum_and_product(num1, num2)
print(f"The sum of {num1} and {num2} is: {sum_result}")
print(f"The product of {num1} and {num2} is: {product_result}")
def show_message():
message = "I am a local variable"
print("Inside the function:", message)
def show_global_message():
print("Accessing global variable inside function:", message)
show_message()
show_global_message()
print("Outside the function:", message)
def global_example():
global count # Refers to the global variable
count += 1
print("Inside global_example (modified global count):", count)
local_example()
print("After local_example (global count remains unchanged):", count)
global_example()
print("After global_example (global count is changed):", count)
38.Write a Python program to find the biggest and smallest numbers in a list
of integers.
print("Tanushree Nair\nMCA IInd SEM\nProgramming in Python\
n---------------------------------")
numbers = list(map(int, input("Enter integers separated by space: ").split()))
smallest = min(numbers)
biggest = max(numbers)
print("Smallest number in the list:", smallest)
Tanushree Nair Page 22 of 40
MCA 206: Programming in Python MCA 2nd Semester
print("Biggest number in the list:", biggest)
student['graduation_year'] = 2024
print("Student's Graduation Year:", student['graduation_year'])
student['age'] = 22
print("Modified Age:", student['age'])
del student['grades']
print("Student Dictionary after deleting 'grades':", student)
42. Write a Python program to find the number of occurrences of each letter
in a string
using dictionaries.
print("Tanushree Nair\nMCA IInd SEM\nProgramming in Python\
n---------------------------------")
string = input("Enter a string: ")
letter_count = {}
43.Write a Python program to print the CWD and change the CWD.
Tanushree Nair Page 25 of 40
MCA 206: Programming in Python MCA 2nd Semester
print("Tanushree Nair\nMCA IInd SEM\nProgramming in Python\
n---------------------------------")
import os
current_directory = os.getcwd()
print("Current Working Directory:", current_directory)
new_directory = input("Enter the path to change to: ")
try:
os.chdir(new_directory)
print("Directory successfully changed to:", os.getcwd())
except FileNotFoundError:
print(f"Error: The directory '{new_directory}' does not exist.")
except PermissionError:
print(f"Error: You do not have permission to access '{new_directory}'.")
44. Write a Python program that takes a list of words from the user and
writes them into a file. The program should stop when the user enters the word ‘quit’.
print("Tanushree Nair\nMCA IInd SEM\nProgramming in Python\
n---------------------------------")
with open('words.txt', 'w') as file:
print("Enter words to be written to the file. Type 'quit' to stop.")
while True:
word = input("Enter a word: ")
if word.lower() == 'quit':
break
file.write(word + '\n')
45. Write a Python program that reads a file in text mode and counts the
number of words that contain anyone of the letters [‘w’, ‘o’, ‘r’, ‘d’, ‘s’].
print("Tanushree Nair\nMCA IInd SEM\nProgramming in Python\
n---------------------------------")
file_name = input("Enter the file name to read: ")
try:
with open(file_name, 'r') as file:
content = file.read()
words = content.split()
target_letters = set('words')
count = 0
for word in words:
if any(letter in target_letters for letter in word.lower()):
count += 1
print("Number of words containing any of the letters ['w', 'o', 'r', 'd', 's']:", count)
except FileNotFoundError:
print(f"Error: The file '{file_name}' was not found.")
x = 10
y=5
except ValueError:
print("Error: Please enter valid integers.")
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
except FileNotFoundError:
print("Error: The file you entered does not exist.")
except Exception as e:
print("An unexpected error occurred:", e)
51. Write a Python program that creates a class “Person”, with attributes
[aadhar, name, DoB]
print("Tanushree Nair\nMCA IInd SEM\nProgramming in Python\
n---------------------------------")
class Person:
def __init__(self, aadhar, name, dob):
self.aadhar = aadhar
self.name = name
self.dob = dob
def display_info(self):
print("Aadhar:", self.aadhar)
Tanushree Nair Page 30 of 40
MCA 206: Programming in Python MCA 2nd Semester
print("Name:", self.name)
print("Date of Birth:", self.dob)
52. Write a Python program that creates classes “Point” and “Rectangle”
where the Rectangle class has a Point object as its attribute.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
class Rectangle:
def __init__(self, corner, width, height):
self.corner = corner # This should be a Point object
self.width = width
self.height = height
def area(self):
return self.width * self.height
def display(self):
print("Rectangle Corner Coordinates:", f"({self.corner.x}, {self.corner.y})")
print("Width:", self.width)
print("Height:", self.height)
print("Area:", self.area())
corner_point = Point(x, y)
rect = Rectangle(corner_point, width, height)
print("\nRectangle Details:")
rect.display()
53. Write a Python program that creates a class Students which inherits the
properties of the “Person” class; add attributes [roll_no, class].
class Person:
def __init__(self, aadhar, name, dob):
self.aadhar = aadhar
self.name = name
self.dob = dob
def display_person(self):
print("Aadhar:", self.aadhar)
print("Name:", self.name)
print("Date of Birth:", self.dob)
class Students(Person):
def __init__(self, aadhar, name, dob, roll_no, class_):
super().__init__(aadhar, name, dob)
self.roll_no = roll_no
self.class_ = class_
Tanushree Nair Page 32 of 40
MCA 206: Programming in Python MCA 2nd Semester
def display_student(self):
self.display_person()
print("Roll Number:", self.roll_no)
print("Class:", self.class_)
print("\nStudent Details:")
student1.display_student()
class Mother:
def skills(self):
print("Mother's skills: Cooking, Painting")
# Example usage
c = Child()
c.skills()
class Dog(Animal):
def sound(self):
print("Dog barks")
print("Tanushree Nair\nMCA IInd SEM\nProgramming in Python\
n---------------------------------")
a = Animal()
d = Dog()
58.Use the “turtle” module to draw concentric circles with different colours.
import turtle
print("Tanushree Nair\nMCA IInd SEM\nProgramming in Python\
n---------------------------------")
# Set up the screen
screen = turtle.Screen()
screen.bgcolor("white")
t = turtle.Turtle()
t.speed(0)
t.penup()
def draw_multiplication_table():
t.goto(-200, 250)
for i in range(1, 11):
for j in range(1, 11):
t.write(f"{i} x {j} = {i * j}", align="left", font=("Arial", 12, "normal"))
t.forward(120)
t.goto(-200, t.ycor() - 30)
draw_multiplication_table()
t.hideturtle()
turtle.done()
60. Use the “turtle” module to draw (not write) your name.
print("Tanushree Nair\nMCA IInd SEM\nProgramming in Python\
n---------------------------------")
import turtle
# Finish up
turtle.hideturtle() # Hide the turtle
turtle.done() # Finish the drawing