MCA 206: Programming in Python MCA 2nd Semester
1. Write a Python program to perform arithmetic operations on integers.
print("Tanushree Nair\nMCA IInd SEM\nProgramming in Python\n---------------------------------")
x=int(input("Enter value of x : "))
y=int(input("Enter value of y : "))
print("Sum : ",x + y)
print("Difference : ",x - y)
print("Multiplication : ",x * y)
print("Division : ",x / y)
print("Floor division : ",x // y)
print("Modulus : ",x % y)
print("Exponentiation : ",x ** y)
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))
Tanushree Nair Page 1 of 40
MCA 206: Programming in Python MCA 2nd Semester
3. Write a Python program to check if a number is EVEN or ODD.
print("Tanushree Nair\nMCA IInd SEM\nProgramming in Python\
n---------------------------------")
x=int(input("Enter a number to check whether it is even or odd : "))
if x%2==0: print("The number ",x," is an even number.")
else: print("The number ",x," is an odd number.")
4. Write a Python program to check if a number is Positive, Negative or
Zero.
print("Tanushree Nair\nMCA IInd SEM\nProgramming in Python\n---------------------------------")
num=int(input("Enter a number to check whether it is negative, positive or zero : "))
if num>0: print("The entered number is positive.")
elif num<0: print("The entered number is negative.")
else: print("Entered number is zero.")
Tanushree Nair Page 2 of 40
MCA 206: Programming in Python MCA 2nd Semester
5. Write a Python program to check if a number is PRIME or NOT.
print("Tanushree Nair\nMCA IInd SEM\nProgramming in Python\n---------------------------------")
x=int(input("Enter a number to check whether it is prime or composite : "))
if (x==0 and x==1):
print("Neither a prime number nor a composite number")
elif x>1:
for i in range(2, x):
if(x%i)==0: print(x," is not a prime number")
else: print(x," is a prime number")
break
else:
print("Not a prime number")
6. Write a Python program to check whether a string entered by the user is
a valid decimal number or not.
print("Tanushree Nair\nMCA IInd SEM\nProgramming in Python\n---------------------------------")
check=input("Enter string to check whether it is a decimal or not: ")
if float(check) :
print("Given string is a decimal")
else :
print("Given string is not a decimal number")
Tanushree Nair Page 3 of 40
MCA 206: Programming in Python MCA 2nd Semester
7. Write a Python program to check if a year entered by the user is a Leap
Year or NOT.
print("Tanushree Nair\nMCA IInd SEM\nProgramming in Python\
n---------------------------------")
num=int(input("Enter a year to check whether it is a leap year or not :"))
if (num%4==0) and (num%100==0) and (num%400==0):
print(num," is a leap year.")
else :
print(num," is not a leap year.")
8. Write a Python program to check whether a string entered by the user is
a palindrome or not.
print("Tanushree Nair\nMCA IInd SEM\nProgramming in Python\
n---------------------------------")
num=int(input("Enter a number to check if it is palindrom number : "))
#str(num)
if (str(num)==str(num)[::-1]) :
print(num," is a palindrome number.")
else :
print(num," is not a palindrome number.")
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))
10.Write a Python program to find sum of natural numbers, up to N.
print("Tanushree Nair\nMCA IInd SEM\nProgramming in Python\
n---------------------------------")
n=int(input("Enter a number :"))
sum=0
for i in range(0,n+1) :
#i+=1
sum+=i
print("Sum of natural numbers from 0 to",n,"= ",sum)
Tanushree Nair Page 5 of 40
MCA 206: Programming in Python MCA 2nd Semester
11.Write a Python program to get marks in five subjects from user and
calculate average marks, percentage and grade of a student.
print("Tanushree Nair\nMCA IInd SEM\nProgramming in Python\
n---------------------------------")
print("Enter marks out of 100")
sub1=int(input("Subject 1: "))
sub2=int(input("Subject 2: "))
sub3=int(input("Subject 3: "))
sub4=int(input("Subject 4: "))
sub5=int(input("Subject 5: "))
total=sub1+sub2+sub3+sub4+sub5
avg=total/5
print("Average marks : ",avg)
per=(total /500)*100
print("Percentage : ",per)
'''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:
Tanushree Nair Page 6 of 40
MCA 206: Programming in Python MCA 2nd Semester
print("A")
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
for digit in num:
if digit.isdigit():
digit = int(digit)
digit_sum += digit
digit_product *= digit
else:
print("Invalid input. Please enter digits only.")
break
else:
print("Sum of digits:", digit_sum)
print("Product of digits:", digit_product)
Tanushree Nair Page 7 of 40
MCA 206: Programming in Python MCA 2nd Semester
13.Write a Python program to get two integers and find their GCD and
LCM.
import math
print("Tanushree Nair\nMCA IInd SEM\nProgramming in Python\n---------------------------------")
a = int(input("Enter first integer: "))
b = int(input("Enter second integer: "))
gcd = math.gcd(a, b)
lcm = abs(a * b) // gcd if gcd != 0 else 0
print("GCD of", a, "and", b, "is:", gcd)
print("LCM of", a, "and", b, "is:", lcm)
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}.")
Tanushree Nair Page 8 of 40
MCA 206: Programming in Python MCA 2nd Semester
15. Write a Python program to print Fibonacci series up to N terms.
print("Tanushree Nair\nMCA IInd SEM\nProgramming in Python\
n---------------------------------")
n = int(input("Enter the number of terms: "))
# First two terms
a, b = 0, 1
count = 0
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
16.Write a Python program to print multiplication table.
print("Tanushree Nair\nMCA IInd SEM\nProgramming in Python\
n---------------------------------")
num = int(input("Enter a number to print its multiplication table: "))
print(f"\nMultiplication Table of {num}:")
i=1
while i <= 10:
print(f"{num} x {i} = {num * i}")
i += 1
Tanushree Nair Page 9 of 40
MCA 206: Programming in Python MCA 2nd Semester
17.Write a Python program to access each element of a string in forward and
backward orders using the ‘while’ loop.
print("Tanushree Nair\nMCA IInd SEM\nProgramming in Python\
n---------------------------------")
text = input("Enter a string: ")
print("\nCharacters in forward order:")
i=0
while i < len(text):
print(text[i])
i += 1
print("\nCharacters in backward order:")
i = len(text) - 1
while i >= 0:
print(text[i])
i -= 1
Tanushree Nair Page 10 of 40
MCA 206: Programming in Python MCA 2nd Semester
18.Write a Python program to access each element of a string in forward and
backward orders using the ‘for’ loop.
print("Tanushree Nair\nMCA IInd SEM\nProgramming in Python\
n---------------------------------")
text = input("Enter a string: ")
print("\nCharacters in forward order:")
for ch in text:
print(ch)
print("\nCharacters in backward order:")
for ch in reversed(text):
print(ch)
Tanushree Nair Page 11 of 40
MCA 206: Programming in Python MCA 2nd Semester
19.Write a Python program to find whether a substring exists in main string
or not.
print("Tanushree Nair\nMCA IInd SEM\nProgramming in Python\
n---------------------------------")
main_str = input("Enter the main string: ")
sub_str = input("Enter the substring to search: ")
if sub_str in main_str:
print(f"Yes, '{sub_str}' exists in the main string.")
else:
print(f"No, '{sub_str}' does not exist in the main string.")
20.Write a Python program to find the first occurrence of a substring in the
main string.
print("Tanushree Nair\nMCA IInd SEM\nProgramming in Python\
n---------------------------------")
main_str = input("Enter the main string: ")
sub_str = input("Enter the substring to find: ")
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.")
21.Write a Python program to count the number of times a substring
appears in the main string.
print("Tanushree Nair\nMCA IInd SEM\nProgramming in Python\
n---------------------------------")
main_str = input("Enter the main string: ")
sub_str = input("Enter the substring to count: ")
Tanushree Nair Page 12 of 40
MCA 206: Programming in Python MCA 2nd Semester
count = main_str.count(sub_str)
print(f"The substring '{sub_str}' appears {count} time(s) in the main string.")
22.Write a Python program to demonstrate the use of all “casing” methods
and display a string in different cases.
print("Tanushree Nair\nMCA IInd SEM\nProgramming in Python\
n---------------------------------")
text = input("Enter a string: ")
print("\nDifferent casing methods applied on the string:\n")
print("Original: ", text)
print("Lowercase: ", text.lower())
print("Uppercase: ", text.upper())
print("Title Case: ", text.title())
print("Capitalize: ", text.capitalize())
print("Swap Case: ", text.swapcase())
casefolded = text.casefold()
print("Casefold (for comparisons):", casefolded)
Tanushree Nair Page 13 of 40
MCA 206: Programming in Python MCA 2nd Semester
23.Write a Python program to demonstrate the use of all string testing
{isXXX()} methods.
print("Tanushree Nair\nMCA IInd SEM\nProgramming in Python\
n---------------------------------")
text = input("Enter a string to test: ")
print("\nTesting the string using isXXX() methods:\n")
print("Is alphanumeric (letters or digits)? :", text.isalnum())
print("Is alphabetic (only letters)? :", text.isalpha())
print("Is digit (only numbers)? :", text.isdigit())
print("Is decimal (only decimal numbers)? :", text.isdecimal())
print("Is numeric (numbers including unicode)? :", text.isnumeric())
print("Is lowercase? :", text.islower())
print("Is uppercase? :", text.isupper())
print("Is title case? :", text.istitle())
print("Is space (only whitespace)? :", text.isspace())
print("Is identifier (valid variable name)? :", text.isidentifier())
print("Is printable? :", text.isprintable())
Tanushree Nair Page 14 of 40
MCA 206: Programming in Python MCA 2nd Semester
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
Tanushree Nair Page 15 of 40
MCA 206: Programming in Python MCA 2nd Semester
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def print_primes_between(num1, num2):
if num1 > num2:
num1, num2 = num2, num1 # Ensure num1 is less than num2
print(f"Prime numbers between {num1} and {num2} are:")
for num in range(num1 + 1, num2):
if is_prime(num):
print(num, end=" ")
num1 = int(input("Enter the first integer: "))
num2 = int(input("Enter the second integer: "))
print_primes_between(num1, num2)
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}")
Tanushree Nair Page 16 of 40
MCA 206: Programming in Python MCA 2nd Semester
27.Write a Python program to demonstrate the positional arguments of a
function.
print("Tanushree Nair\nMCA IInd SEM\nProgramming in Python\
n---------------------------------")
def greet(name, age, city):
print(f"Hello, my name is {name}, I am {age} years old, and I live in {city}.")
greet("Alice", 25, "New York")
greet("Bob", 30, "London")
28.Write a Python program to demonstrate the keyword arguments of a
function.
print("Tanushree Nair\nMCA IInd SEM\nProgramming in Python\
n---------------------------------")
def greet(name, age, city):
print(f"Hello, my name is {name}, I am {age} years old, and I live in {city}.")
greet(name="Alice", age=25, city="New York")
greet(city="London", name="Bob", age=30) # Order does not matter here
29.Write a Python program to demonstrate the default arguments of a
function.
print("Tanushree Nair\nMCA IInd SEM\nProgramming in Python\
n---------------------------------")
def greet(name="Guest", age=18, city="Unknown"):
print(f"Hello, my name is {name}, I am {age} years old, and I live in {city}.")
greet()
greet(name="Alice")
greet(name="Bob", age=30)
Tanushree Nair Page 17 of 40
MCA 206: Programming in Python MCA 2nd Semester
greet(name="Charlie", age=25, city="Los Angeles")
30.Write a Python function to demonstrate variable length arguments.
print("Tanushree Nair\nMCA IInd SEM\nProgramming in Python\
n---------------------------------")
def display_numbers(*args):
print("The numbers are:")
for num in args:
print(num)
display_numbers(1, 2, 3, 4)
display_numbers(10, 20, 30)
display_numbers(100)
31.Write a Python function to demonstrate keyword variable length
arguments.
print("Tanushree Nair\nMCA IInd SEM\nProgramming in Python\
n---------------------------------")
def describe_person(**kwargs):
print("Person details:")
for key, value in kwargs.items():
print(f"{key}: {value}")
# Calling the function with different keyword arguments
Tanushree Nair Page 18 of 40
MCA 206: Programming in Python MCA 2nd Semester
describe_person(name="Tanushree", age=23, city="Raipur")
print() # Just to separate outputs
describe_person(name="Anjali", profession="Professor")
print()
describe_person(country="India", hobby="Reading", language="Hindi")
32.Write a Python program to demonstrate global and local variables.
print("Tanushree Nair\nMCA IInd SEM\nProgramming in Python\
n---------------------------------")
message = "I am a global variable"
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)
33.Write a Python program to demonstrate global and local variables.
print("Tanushree Nair\nMCA IInd SEM\nProgramming in Python\
n---------------------------------")
count = 10
Tanushree Nair Page 19 of 40
MCA 206: Programming in Python MCA 2nd Semester
def local_example():
count = 5
print("Inside local_example (local count):", count)
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)
34.Write a Python program to demonstrate the use of lambda functions.
print("Tanushree Nair\nMCA IInd SEM\nProgramming in Python\
n---------------------------------")
add = lambda a, b: a + b
print("Sum of 5 and 3 is:", add(5, 3))
square = lambda x: x * x
print("Square of 4 is:", square(4))
is_even = lambda n: n % 2 == 0
print("Is 10 even?", is_even(10))
numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x ** 2, numbers))
print("Squares using lambda and map():", squares)
evens = list(filter(lambda x: x % 2 == 0, numbers))
print("Even numbers using lambda and filter():", evens)
Tanushree Nair Page 20 of 40
MCA 206: Programming in Python MCA 2nd Semester
35.Write a Python program to demonstrate the use of lambda functions and
reduce.
from functools import reduce
print("Tanushree Nair\nMCA IInd SEM\nProgramming in Python\
n---------------------------------")
numbers = [1, 2, 3, 4, 5]
sum_result = reduce(lambda x, y: x + y, numbers)
print("Sum of the list:", sum_result)
product_result = reduce(lambda x, y: x * y, numbers)
print("Product of the list:", product_result)
max_result = reduce(lambda x, y: x if x > y else y, numbers)
print("Maximum number in the list:", max_result)
36.Write a Python program to demonstrate the use of lambda functions and
reduce.
print("Tanushree Nair\nMCA IInd SEM\nProgramming in Python\
n---------------------------------")
from functools import reduce
numbers = list(map(int, input("Enter numbers separated by space: ").split()))
sum_result = reduce(lambda x, y: x + y, numbers)
print("Sum of the list:", sum_result)
product_result = reduce(lambda x, y: x * y, numbers)
print("Product of the list:", product_result)
max_result = reduce(lambda x, y: x if x > y else y, numbers)
print("Maximum number in the list:", max_result)
Tanushree Nair Page 21 of 40
MCA 206: Programming in Python MCA 2nd Semester
37.Write a Python program to demonstrate the various list processing
methods.
print("Tanushree Nair\nMCA IInd SEM\nProgramming in Python\
n---------------------------------")
fruits = ['apple', 'banana', 'cherry', 'banana', 'date']
print("Original list:", fruits)
fruits.append('elderberry')
print("After append:", fruits)
fruits.insert(2, 'fig')
print("After insert at index 2:", fruits)
fruits.remove('banana')
print("After removing 'banana':", fruits)
last_fruit = fruits.pop()
print("After pop (removed):", last_fruit)
print("List after pop:", fruits)
index_cherry = fruits.index('cherry')
print("Index of 'cherry':", index_cherry)
count_banana = fruits.count('banana')
print("Count of 'banana':", count_banana)
fruits.sort()
print("After sorting:", fruits)
fruits.reverse()
print("After reversing:", fruits)
fruits.clear()
print("After clearing the list:", fruits)
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)
39.Write a Python program to find common elements in two lists.
print("Tanushree Nair\nMCA IInd SEM\nProgramming in Python\
n---------------------------------")
list1 = list(map(int, input("Enter elements of the first list (space-separated): ").split()))
list2 = list(map(int, input("Enter elements of the second list (space-separated): ").split()))
common = list(set(list1) & set(list2))
print("Common elements:", common)
40.Write a Python program to demonstrate the various tuple processing
methods.
fruits = ('apple', 'banana', 'cherry', 'date', 'apple')
print("Tanushree Nair\nMCA IInd SEM\nProgramming in Python\
n---------------------------------")
print("Original tuple:", fruits)
print("Element at index 1:", fruits[1])
print("Slice from index 1 to 3:", fruits[1:4])
tuple1 = ('apple', 'banana')
tuple2 = ('cherry', 'date')
concat_tuple = tuple1 + tuple2
print("Concatenated tuple:", concat_tuple)
repeated_tuple = tuple1 * 3
print("Repeated tuple:", repeated_tuple)
print("Is 'banana' in the tuple?", 'banana' in fruits)
print("Count of 'apple' in the tuple:", fruits.count('apple'))
print("Index of 'cherry' in the tuple:", fruits.index('cherry'))
print("Length of the tuple:", len(fruits))
print("Iterating through the tuple:")
Tanushree Nair Page 23 of 40
MCA 206: Programming in Python MCA 2nd Semester
for fruit in fruits:
print(fruit)
nested_tuple = ('apple', (1, 2, 3), 'banana')
print("Accessing nested tuple element:", nested_tuple[1][2])
a, b, c, d, e = fruits
print("Unpacked elements:", a, b, c, d, e)
41.Write a Python program to demonstrate the use of dictionaries.
print("Tanushree Nair\nMCA IInd SEM\nProgramming in Python\
n---------------------------------")
student = {
'name': 'John',
'age': 21,
'major': 'Computer Science',
'grades': [85, 90, 88, 92]
}
print("Student's Name:", student['name'])
print("Student's Age:", student['age'])
print("Student's Major:", student['major'])
print("Student's Grades:", student['grades'])
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)
Tanushree Nair Page 24 of 40
MCA 206: Programming in Python MCA 2nd Semester
print("Is 'major' key in the dictionary?", 'major' in student)
print("Student's Major using get():", student.get('major'))
print("Student's GPA using get (default 0 if not found):", student.get('GPA', 0))
print("Iterating through dictionary:")
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 = {}
for letter in string:
if letter.isalpha(): # Checking if the character is a letter
letter = letter.lower() # Converting the letter to lowercase to make it case-insensitive
if letter in letter_count:
letter_count[letter] += 1
else:
letter_count[letter] = 1
print("Letter occurrences:", 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')
print("Words have been written to 'words.txt'.")
Tanushree Nair Page 26 of 40
MCA 206: Programming in Python MCA 2nd Semester
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.")
46.Python programs to demonstrate the creation and use of “modules”.
Tanushree Nair Page 27 of 40
MCA 206: Programming in Python MCA 2nd Semester
# mymodule.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
pi = 3.14159
# main.py
print("Tanushree Nair\nMCA IInd SEM\nProgramming in Python\
n---------------------------------")
import mymodule
x = 10
y=5
print("Addition:", mymodule.add(x, y))
print("Subtraction:", mymodule.subtract(x, y))
print("Value of pi:", mymodule.pi)
47.Exception Handling Program that uses try and except.
print("Tanushree Nair\nMCA IInd SEM\nProgramming in Python\
n---------------------------------")
try:
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))
result = num1 / num2
print("Result:", result)
except ValueError:
print("Invalid input! Please enter only numbers.")
except ZeroDivisionError:
print("Cannot divide by zero.")
Tanushree Nair Page 28 of 40
MCA 206: Programming in Python MCA 2nd Semester
48.Exception Handling Program that handles multiple types of exceptions.
print("Tanushree Nair\nMCA IInd SEM\nProgramming in Python\
n---------------------------------")
try:
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
result = num1 / num2
print("Result:", result)
file_name = input("Enter a file name to open: ")
with open(file_name, 'r') as file:
content = file.read()
print("File content:\n", content)
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)
49.Exception Handling Program that uses try, except and else.
print("Tanushree Nair\nMCA IInd SEM\nProgramming in Python\
n---------------------------------")
try:
num1 = int(input("Enter the numerator: "))
num2 = int(input("Enter the denominator: "))
result = num1 / num2
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
except ValueError:
Tanushree Nair Page 29 of 40
MCA 206: Programming in Python MCA 2nd Semester
print("Error: Please enter valid integers.")
else:
print("Division successful. Result:", result)
50.Exception Handling Program that uses finally with try.
print("Tanushree Nair\nMCA IInd SEM\nProgramming in Python\
n---------------------------------")
try:
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))
result = num1 / num2
print("Result:", result)
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
except ValueError:
print("Error: Please enter valid integers.")
finally:
print("This block always executes, whether an exception occurred or not.")
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)
aadhar_input = input("Enter Aadhar number: ")
name_input = input("Enter Name: ")
dob_input = input("Enter Date of Birth (DD-MM-YYYY): ")
person1 = Person(aadhar_input, name_input, dob_input)
print("\nPerson Details:")
person1.display_info()
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())
Tanushree Nair Page 31 of 40
MCA 206: Programming in Python MCA 2nd Semester
print("Tanushree Nair\nMCA IInd SEM\nProgramming in Python\
n---------------------------------")
x = int(input("Enter x-coordinate of corner: "))
y = int(input("Enter y-coordinate of corner: "))
width = int(input("Enter width of rectangle: "))
height = int(input("Enter height of rectangle: "))
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("Tanushree Nair\nMCA IInd SEM\nProgramming in Python\
n---------------------------------")
aadhar_input = input("Enter Aadhar number: ")
name_input = input("Enter Name: ")
dob_input = input("Enter Date of Birth (DD-MM-YYYY): ")
roll_no_input = input("Enter Roll Number: ")
class_input = input("Enter Class: ")
student1 = Students(aadhar_input, name_input, dob_input, roll_no_input, class_input)
print("\nStudent Details:")
student1.display_student()
54.Write a Python program to demonstrate “Multiple Inheritance”.
print("Tanushree Nair\nMCA IInd SEM\nProgramming in Python\
n---------------------------------")
class Father:
def skills(self):
print("Father's skills: Gardening, Carpentry")
class Mother:
def skills(self):
print("Mother's skills: Cooking, Painting")
Tanushree Nair Page 33 of 40
MCA 206: Programming in Python MCA 2nd Semester
class Child(Father, Mother):
def skills(self):
Father.skills(self)
Mother.skills(self)
print("Child's skills: Coding, Drawing")
# Example usage
c = Child()
c.skills()
55.Write a Python program to demonstrate “Method Overriding”.
class Animal:
def sound(self):
print("Animal makes a sound")
class Dog(Animal):
def sound(self):
print("Dog barks")
print("Tanushree Nair\nMCA IInd SEM\nProgramming in Python\
n---------------------------------")
a = Animal()
d = Dog()
a.sound() # Calls the method from Animal
d.sound() # Calls the overridden method from Dog
56.Write a Python program to demonstrate “Method Overloading”.
class Calculator:
def add(self, *args):
return sum(args)
Tanushree Nair Page 34 of 40
MCA 206: Programming in Python MCA 2nd Semester
print("Tanushree Nair\nMCA IInd SEM\nProgramming in Python\
n---------------------------------")
calc = Calculator()
print("Sum of 3 and 5:", calc.add(3, 5)) # Two arguments
print("Sum of 1, 2, 3, 4, 5:", calc.add(1, 2, 3, 4, 5)) # Multiple arguments
57. Write a Python program to demonstrate “Operator Overloading” [+ and
-] using a class “Book”.
print("Tanushree Nair\nMCA IInd SEM\nProgramming in Python\
n---------------------------------")
class Book:
def __init__(self, title, pages):
self.title = title
self.pages = pages
def __add__(self, other):
return Book(self.title + " & " + other.title, self.pages + other.pages)
def __sub__(self, other):
return abs(self.pages - other.pages)
def display(self):
print(f"Title: {self.title}, Pages: {self.pages}")
book1 = Book("The Python Guide", 250)
book2 = Book("Data Science Essentials", 300)
combined_book = book1 + book2
print("Combined Book Details:")
combined_book.display()
page_difference = book1 - book2
print(f"\nPage difference between the two books: {page_difference} pages")
Tanushree Nair Page 35 of 40
MCA 206: Programming in Python MCA 2nd Semester
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")
# Create a turtle object
t = turtle.Turtle()
t.speed(0)
# List of colors for the concentric circles
colors = ["red", "blue", "green", "yellow", "purple", "orange", "pink"]
# Function to draw concentric circles
def draw_concentric_circles():
radius = 20 # Starting radius
for color in colors:
t.penup() # Don't draw while moving to the start position
t.goto(0, -radius) # Move to starting position of the circle
t.pendown() # Start drawing
t.color(color)
t.circle(radius) # Draw the circle
radius += 20 # Increase radius for the next circle
# Draw the concentric circles
draw_concentric_circles()
# Hide the turtle and display the window
t.hideturtle()
turtle.done()
Tanushree Nair Page 36 of 40
MCA 206: Programming in Python MCA 2nd Semester
59.Use the “turtle” module to print the multiplication table.
import turtle
print("Tanushree Nair\nMCA IInd SEM\nProgramming in Python\
n---------------------------------")
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()
Tanushree Nair Page 37 of 40
MCA 206: Programming in Python MCA 2nd Semester
60. Use the “turtle” module to draw (not write) your name.
print("Tanushree Nair\nMCA IInd SEM\nProgramming in Python\
n---------------------------------")
import turtle
# Function to draw the letter 't'
def draw_t():
turtle.penup()
turtle.goto(-100, 0)
turtle.pendown()
turtle.setheading(90) # Point upwards
turtle.forward(100) # Draw the vertical line
turtle.right(90) # Turn right
turtle.forward(50) # Draw the horizontal line
turtle.backward(100)
turtle.penup()
# Function to draw the letter 'a'
def draw_a():
turtle.goto(-50, 0)
turtle.pendown()
turtle.setheading(75) # Angle for the left side
turtle.forward(100) # Draw left side
turtle.setheading(0) # Angle for the top
turtle.forward(50) # Draw top
turtle.setheading(285) # Angle for the right side
turtle.forward(100) # Draw right side
turtle.penup()
turtle.goto(-25, 40) # Move to the middle for the crossbar
turtle.setheading(0)
Tanushree Nair Page 38 of 40
MCA 206: Programming in Python MCA 2nd Semester
turtle.pendown()
turtle.forward(45) # Draw the crossbar
turtle.penup()
# Function to draw the letter 'n'
def draw_n():
turtle.goto(65, 0)
turtle.pendown()
turtle.setheading(90) # Point upwards
turtle.forward(100) # Draw the vertical line
turtle.setheading(300) # Angle for the diagonal
turtle.forward(115) # Draw the diagonal line
turtle.setheading(90) # Angle for the bottom
turtle.forward(100) # Draw the bottom line
turtle.penup()
# Function to draw the letter 'u'
def draw_u():
turtle.goto(150, 100)
turtle.pendown()
turtle.setheading(90) # Point upwards
turtle.backward(100) # Draw the left side
turtle.setheading(0) # Point left
turtle.forward(50) # Draw the bottom
turtle.setheading(90) # Point upwards
turtle.forward(100) # Draw the right side
turtle.penup()
# Set up the turtle
turtle.speed(1) # Set the speed of drawing
turtle.pensize(3) # Set the pen size
# Draw the letters
draw_t()
draw_a()
draw_n()
draw_u()
# Finish up
turtle.hideturtle() # Hide the turtle
turtle.done() # Finish the drawing
Tanushree Nair Page 39 of 40
MCA 206: Programming in Python MCA 2nd Semester
Tanushree Nair Page 40 of 40