UNIVERSITY OF MADRAS
BACHELOR OF COMPUTER APPLICATIONS (BCA)
BACHELOR OF COMPUTER SCIENCE (CS)
DEGREE PROGRAMME
SYLLABUS WITH EFFECT FROM 2023-2024
Year: I Semester:I
Core-II: Python Programming Practical
Code: 120C11 & 125C11
List of Programs
1. Program to convert the given temperature from Fahrenheit to Celsius and vice versa depending upon
user’s choice.
2. Write a Python program to construct the following pattern, using a nested loop
*
**
***
****
*****
****
***
**
*
3. Program to calculate total marks, percentage and grade of a student. Marks obtained in each of the
five subjects are to be input by user. Assign grades according to the following criteria: Grade A:
Percentage >=80 Grade B: Percentage >=70 and 80 Grade C: Percentage >=60 and =40 and < 40
4. Program, to find the area of rectangle, square, circle and triangle by accepting suitable input
parameters from user.
5. Write a Python script that prints prime numbers less than 20.
6. Program to find factorial of the given number using recursive function.
7. Write a Python program to count the number of even and odd numbers from array of N numbers.
8. Write a Python class to reverse a string word by word.
9. Given a tuple and a list as input, write a program to count the occurrences of all items of the list in the
tuple. (Input: tuple = ('a', 'a', 'c', 'b', 'd'), list = ['a', 'b'], Output: 3)
10. Create a Savings Account class that behaves just like a Bank Account, but also has an interest rate
and a method that increases the balance by the appropriate amount of interest (Hint: use Inheritance).
11. Read a file content and copy only the contents at odd lines into a new file.
12. Create a Turtle graphics window with specific size.
13. Write a Python program for Towers of Hanoi using recursion
14. Create a menu driven Python program with a dictionary for words and their meanings.
15. Devise a Python program to implement the Hangman Game.
1. Program to convert the given temperature from Fahrenheit to
Celsius and vice versa depending upon user’s choice.
def celsius_to_fahrenheit(celsius):
"""Converts temperature from Celsius to Fahrenheit."""
return (celsius * 9/5) + 32
def fahrenheit_to_celsius(fahrenheit):
"""Converts temperature from Fahrenheit to Celsius."""
return (fahrenheit - 32) * 5/9
def main():
"""Main function to handle user interaction and temperature conversion."""
print("Temperature Converter")
print("1. Convert Celsius to Fahrenheit")
print("2. Convert Fahrenheit to Celsius")
while True:
try:
choice = int(input("Enter your choice (1 or 2): "))
if choice in [1, 2]:
break
else:
print("Invalid choice. Please enter 1 or 2.")
except ValueError:
print("Invalid input. Please enter a number.")
if choice == 1:
while True:
try:
celsius_temp = float(input("Enter temperature in Celsius: "))
fahrenheit_temp = celsius_to_fahrenheit(celsius_temp)
print(f"{celsius_temp}°C is equal to {fahrenheit_temp:.2f}°F")
break
except ValueError:
print("Invalid input. Please enter a numeric value for temperature.")
elif choice == 2:
while True:
try:
fahrenheit_temp = float(input("Enter temperature in Fahrenheit: "))
celsius_temp = fahrenheit_to_celsius(fahrenheit_temp)
print(f"{fahrenheit_temp}°F is equal to {celsius_temp:.2f}°C")
break
except ValueError:
print("Invalid input. Please enter a numeric value for temperature.")
if __name__ == "__main__":
main()
2. Write a Python program to construct the following pattern, using
a nested loop
*
**
***
****
*****
****
***
**
*
def print_star_pattern(rows):
# Increasing part of the pattern
for i in range(1, rows + 1):
for j in range(i):
print("*", end="")
print()
# Decreasing part of the pattern
for i in range(rows - 1, 0, -1):
for j in range(i):
print("*", end="")
print()
# Call the function to print the pattern with 5 rows as the maximum
print_star_pattern(5)
3. Program to calculate total marks, percentage and grade of a
student. Marks obtained in each of the five subjects are to be input
by user. Assign grades according to the following criteria: Grade A:
Percentage >=80 Grade B: Percentage >=70 and 80 Grade C:
Percentage >=60 and =40 and < 40
def calculate_student_performance():
"""
Calculates the total marks, percentage, and grade of a student.
Marks obtained in five subjects are input by the user.
"""
subject_marks = []
num_subjects = 5
print(f"Enter marks for {num_subjects} subjects (out of 100 each):")
for i in range(num_subjects):
while True:
try:
mark = float(input(f"Enter marks for subject {i + 1}: "))
if 0 <= mark <= 100:
subject_marks.append(mark)
break
else:
print("Marks must be between 0 and 100. Please try again.")
except ValueError:
print("Invalid input. Please enter a number.")
total_marks = sum(subject_marks)
percentage = (total_marks / (num_subjects * 100)) * 100
grade = ""
if percentage >= 80:
grade = "A"
elif percentage >= 70:
grade = "B"
elif percentage >= 60:
grade = "C"
elif percentage >= 40:
grade = "D"
else:
grade = "E"
print("\n--- Student Performance Summary ---")
print(f"Total Marks: {total_marks:.2f}")
print(f"Percentage: {percentage:.2f}%")
print(f"Grade: {grade}")
# Call the function to run the program
calculate_student_performance()
4. write a python Program, to find the area of rectangle, square,
circle and triangle by accepting suitable input parameters from
user.
import math
def calculate_area():
"""Calculates and prints the area of a selected shape."""
print("Select a shape to calculate its area:")
print("1. Rectangle")
print("2. Square")
print("3. Circle")
print("4. Triangle")
choice = input("Enter your choice (1-4): ")
if choice == '1':
try:
length = float(input("Enter the length of the rectangle: "))
width = float(input("Enter the width of the rectangle: "))
area = length * width
print(f"The area of the rectangle is: {area:.2f}")
except ValueError:
print("Invalid input. Please enter numeric values for length and width.")
elif choice == '2':
try:
side = float(input("Enter the side length of the square: "))
area = side * side
print(f"The area of the square is: {area:.2f}")
except ValueError:
print("Invalid input. Please enter a numeric value for the side length.")
elif choice == '3':
try:
radius = float(input("Enter the radius of the circle: "))
area = [Link] * (radius ** 2)
print(f"The area of the circle is: {area:.2f}")
except ValueError:
print("Invalid input. Please enter a numeric value for the radius.")
elif choice == '4':
try:
base = float(input("Enter the base length of the triangle: "))
height = float(input("Enter the height of the triangle: "))
area = 0.5 * base * height
print(f"The area of the triangle is: {area:.2f}")
except ValueError:
print("Invalid input. Please enter numeric values for base and height.")
else:
print("Invalid choice. Please enter a number between 1 and 4.")
# Call the function to run the program
calculate_area()
5. Write a Python script that prints prime numbers less than 20.
def is_prime(num):
"""
Checks if a number is prime.
A number is prime if it is greater than 1 and has no divisors other than 1 and
itself.
"""
if num <= 1:
return False # Numbers less than or equal to 1 are not prime
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
return False # Found a divisor, so it's not prime
return True # No divisors found, so it's prime
print("Prime numbers less than 20:")
for number in range(2, 20): # Iterate from 2 up to (but not including) 20
if is_prime(number):
print(number)
6. Program to find factorial of the given number using recursive
function.
def factorial(n):
# Base case: Factorial of 0 is 1
if n == 0:
return 1
# Recursive step: n * factorial of (n-1)
else:
return n * factorial(n - 1)
# Example usage:
number = 5
result = factorial(number)
print(f"The factorial of {number} is: {result}")
7. Write a Python program to count the number of even and odd
numbers from array of N numbers.
def count_even_odd(numbers):
"""
Counts the number of even and odd numbers in a list.
Args:
numbers: A list of integers.
Returns:
A tuple containing (even_count, odd_count).
"""
even_count = 0
odd_count = 0
for num in numbers:
if num % 2 == 0: # Check if the number is even
even_count += 1
else: # If not even, it must be odd
odd_count += 1
return even_count, odd_count
# Example usage:
if __name__ == "__main__":
# Get the number of elements from the user
try:
n = int(input("Enter the number of elements in the array: "))
except ValueError:
print("Invalid input. Please enter an integer for the number of elements.")
exit()
if n < 0:
print("Number of elements cannot be negative.")
exit()
# Get the array elements from the user
input_numbers = []
print(f"Enter {n} numbers:")
for i in range(n):
try:
num = int(input(f"Enter number {i+1}: "))
input_numbers.append(num)
except ValueError:
print("Invalid input. Please enter an integer.")
exit()
even_nums, odd_nums = count_even_odd(input_numbers)
print(f"\nNumber of even numbers: {even_nums}")
print(f"Number of odd numbers: {odd_nums}")
8. Write a Python class to reverse a string word by word.
def count_even_odd(numbers):
"""
Counts the number of even and odd numbers in a list.
Args:
numbers: A list of integers.
Returns:
A tuple containing (even_count, odd_count).
"""
even_count = 0
odd_count = 0
for num in numbers:
if num % 2 == 0: # Check if the number is even
even_count += 1
else: # If not even, it must be odd
odd_count += 1
return even_count, odd_count
# Example usage:
if __name__ == "__main__":
# Get the number of elements from the user
try:
n = int(input("Enter the number of elements in the array: "))
except ValueError:
print("Invalid input. Please enter an integer for the number of elements.")
exit()
if n < 0:
print("Number of elements cannot be negative.")
exit()
# Get the array elements from the user
input_numbers = []
print(f"Enter {n} numbers:")
for i in range(n):
try:
num = int(input(f"Enter number {i+1}: "))
input_numbers.append(num)
except ValueError:
print("Invalid input. Please enter an integer.")
exit()
even_nums, odd_nums = count_even_odd(input_numbers)
print(f"\nNumber of even numbers: {even_nums}")
9. Given a tuple and a list as input, write a program to count the
occurrences of all items of the list in the tuple. (Input: tuple = ('a',
'a', 'c', 'b', 'd'), list = ['a', 'b'], Output: 3)
def count_list_items_in_tuple(input_tuple, input_list):
"""
Counts the total occurrences of all items from a list within a tuple.
Args:
input_tuple (tuple): The tuple to search within.
input_list (list): The list of items to count.
Returns:
int: The total count of occurrences.
"""
total_count = 0
for item in input_list:
total_count += input_tuple.count(item)
return total_count
# Example usage:
my_tuple = ('a', 'a', 'c', 'b', 'd')
my_list = ['a', 'b']
result = count_list_items_in_tuple(my_tuple, my_list)
print(result)
10. Create a Savings Account class that behaves just like a Bank
Account, but also has an interest rate and a method that increases
the balance by the appropriate amount of interest (Hint: use
Inheritance).
class BankAccount:
def __init__(self):
[Link] = 0
print("Welcome to the Machine")
def deposit(self):
amount = float(input("Enter amount to be
Deposited: "))
[Link] += amount
print("\nAmount Deposited:", amount)
def withdraw(self):
amount = float(input("Enter amount to be
Withdrawn: "))
if [Link] >= amount:
[Link] -= amount
print("\nYou Withdrew:", amount)
else:
print("\nInsufficient balance")
def display(self):
print("\nNet Available Balance =",
[Link])
# Driver code
if __name__ == "__main__":
s = BankAccount() # Create an object of
BankAccount
[Link]() # Deposit money
[Link]() # Withdraw money
[Link]() # Display balance
Output
Welcome to the Machine
Enter amount to be Deposited: 1000
Amount Deposited: 1000.0
Enter amount to be Withdrawn: 500
You Withdrew: 500.0
Net Available Balance = 500.0
11. Read a file content and copy only the contents at odd lines into a
new file.
def copy_odd_lines(input_file_path, output_file_path):
"""
Reads content from an input file and copies only the lines at
odd line numbers
into a new output file.
Args:
input_file_path (str): The path to the input file.
output_file_path (str): The path to the output file where
odd lines will be written.
"""
try:
with open(input_file_path, 'r') as infile,
open(output_file_path, 'w') as outfile:
for line_number, line in enumerate(infile, 1): #
Start enumeration from 1 for line numbers
if line_number % 2 != 0: # Check if the line
number is odd
[Link](line)
print(f"Odd lines from '{input_file_path}' successfully
copied to '{output_file_path}'.")
except FileNotFoundError:
print(f"Error: The file '{input_file_path}' was not
found.")
except Exception as e:
print(f"An error occurred: {e}")
# Example usage:
if __name__ == "__main__":
source_file = "[Link]" # Replace with your input file
name
destination_file = "odd_lines.txt" # Replace with your
desired output file name
# Create a dummy input file for demonstration
with open(source_file, 'w') as f:
[Link]("This is line 1.\n")
[Link]("This is line 2.\n")
[Link]("This is line 3.\n")
[Link]("This is line 4.\n")
[Link]("This is line 5.\n")
copy_odd_lines(source_file, destination_file)
# Verify the content of the output file
print("\nContent of the output file:")
with open(destination_file, 'r') as f:
print([Link]())
12. Create a Turtle graphics window with specific size.
import turtle
# Create a Screen object
screen = [Link]()
# Set the window size to 800 pixels wide and 600 pixels high
[Link](width=800, height=600)
# Optional: Set a title for the window
[Link]("My Custom Sized Turtle Window")
# Optional: Change the background color
[Link]("lightgray")
# Create a Turtle object (optional, for drawing)
pen = [Link]()
[Link](3)
[Link](100)
# Keep the window open until clicked
[Link]()
13. Write a Python program for Towers of Hanoi using recursion
def tower_of_hanoi(n, source_rod, target_rod, auxiliary_rod):
"""
Solves the Tower of Hanoi puzzle using recursion.
Args:
n (int): The number of disks to move.
source_rod (str): The name of the source rod.
target_rod (str): The name of the target rod.
auxiliary_rod (str): The name of the auxiliary rod.
"""
if n == 1:
print(f"Move disk 1 from {source_rod} to {target_rod}")
return
# Move n-1 disks from source to auxiliary, using target as auxiliary
tower_of_hanoi(n - 1, source_rod, auxiliary_rod, target_rod)
# Move the nth disk from source to target
print(f"Move disk {n} from {source_rod} to {target_rod}")
# Move n-1 disks from auxiliary to target, using source as auxiliary
tower_of_hanoi(n - 1, auxiliary_rod, target_rod, source_rod)
# Example usage:
if __name__ == "__main__":
num_disks = 3 # You can change this to test with different numbers of disks
print(f"Steps to solve Tower of Hanoi with {num_disks} disks:")
tower_of_hanoi(num_disks, 'A', 'C', 'B')
14. Create a menu driven Python program with a dictionary for
words and their meanings.
def display_menu():
"""Displays the menu options to the user."""
print("\n--- Dictionary Menu ---")
print("1. Add a new word and meaning")
print("2. Look up a word's meaning")
print("3. Update a word's meaning")
print("4. Delete a word")
print("5. Display all words and meanings")
print("6. Exit")
def main():
"""Main function to run the menu-driven dictionary program."""
word_dictionary = {}
while True:
display_menu()
choice = input("Enter your choice (1-6): ")
if choice == '1':
word = input("Enter the word: ").lower()
meaning = input(f"Enter the meaning of '{word}': ")
word_dictionary[word] = meaning
print(f"'{word}' added successfully.")
elif choice == '2':
word = input("Enter the word to look up: ").lower()
if word in word_dictionary:
print(f"Meaning of '{word}': {word_dictionary[word]}")
else:
print(f"'{word}' not found in the dictionary.")
elif choice == '3':
word = input("Enter the word to update: ").lower()
if word in word_dictionary:
new_meaning = input(f"Enter the new meaning for '{word}': ")
word_dictionary[word] = new_meaning
print(f"Meaning of '{word}' updated successfully.")
else:
print(f"'{word}' not found in the dictionary.")
elif choice == '4':
word = input("Enter the word to delete: ").lower()
if word in word_dictionary:
del word_dictionary[word]
print(f"'{word}' deleted successfully.")
else:
print(f"'{word}' not found in the dictionary.")
elif choice == '5':
if word_dictionary:
print("\n--- All Words and Meanings ---")
for word, meaning in word_dictionary.items():
print(f"{word}: {meaning}")
else:
print("The dictionary is empty.")
elif choice == '6':
print("Exiting the program. Goodbye!")
break
else:
print("Invalid choice. Please enter a number between 1 and 6.")
if __name__ == "__main__":
main()
15. Devise a Python program to implement the Hangman Game.
import random
def choose_word():
"""Selects a random word from a predefined list."""
words = ["python", "programming", "hangman", "challenge", "computer",
"keyboard", "developer"]
return [Link](words).upper()
def display_hangman(tries):
"""Displays the hangman figure based on remaining tries."""
stages = [
"""
-----
| |
O |
/|\\ |
/ \\ |
---------
""",
"""
-----
| |
O |
/|\\ |
/ |
---------
""",
"""
-----
| |
O |
/|\\ |
---------
""",
"""
-----
| |
O |
/| |
---------
""",
"""
-----
| |
O |
|
|
---------
""",
"""
-----
| |
---------
""",
"""
-----
| |
---------
"""
]
print(stages[tries])
def play_hangman():
"""Main function to run the Hangman game."""
word = choose_word()
word_completion = ["_"] * len(word)
guessed_letters = []
guessed_words = []
tries = 6 # Number of incorrect guesses allowed
guessed = False
print("Let's play Hangman!")
display_hangman(tries)
print(" ".join(word_completion))
while not guessed and tries > 0:
guess = input("Please guess a letter or word: ").upper()
if len(guess) == 1 and [Link]():
if guess in guessed_letters:
print(f"You already guessed the letter '{guess}'.")
elif guess not in word:
print(f"'{guess}' is not in the word.")
tries -= 1
guessed_letters.append(guess)
else:
print(f"Good guess! '{guess}' is in the word.")
guessed_letters.append(guess)
for i in range(len(word)):
if word[i] == guess:
word_completion[i] = guess
elif len(guess) == len(word) and [Link]():
if guess in guessed_words:
print(f"You already guessed the word '{guess}'.")
elif guess != word:
print(f"'{guess}' is not the word.")
tries -= 1
guessed_words.append(guess)
else:
guessed = True
else:
print("Invalid guess. Please guess a single letter or a word of the correct
length.")
display_hangman(tries)
print(" ".join(word_completion))
print(f"Guessed letters: {', '.join(guessed_letters)}")
print(f"Tries remaining: {tries}")
if "_" not in word_completion:
guessed = True
if guessed:
print(f"Congratulations! You guessed the word: {word}")
else:
print(f"You ran out of tries. The word was: {word}")
if __name__ == "__main__":
play_hangman()