0% found this document useful (0 votes)
22 views60 pages

Python Programming Lab

The document outlines various Python programming tasks, including temperature conversion, pattern generation, student grade calculation, area computation for geometric shapes, prime number identification, factorial calculation, counting even and odd numbers, and string reversal. Each task includes an aim, algorithm, and program code demonstrating the implementation. The document serves as a comprehensive guide for executing fundamental programming exercises in Python.

Uploaded by

kanisri08122000
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views60 pages

Python Programming Lab

The document outlines various Python programming tasks, including temperature conversion, pattern generation, student grade calculation, area computation for geometric shapes, prime number identification, factorial calculation, counting even and odd numbers, and string reversal. Each task includes an aim, algorithm, and program code demonstrating the implementation. The document serves as a comprehensive guide for executing fundamental programming exercises in Python.

Uploaded by

kanisri08122000
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

INDEX

S.NO DATE LIST OF PROGRAMS PAGE SIGNATURE


NO
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 <70
Grade D: Percentage >=40 and <60
Grade E: Percentage < 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. Python Program to convert the given temperature from Fahrenheit to Celsius and vice
versa.

AIM:

The program prompts the user to choose either Fahrenheit to Celsius conversion or Celsius
to Fahrenheit conversion and performs the respective conversion based on the user's choice.

ALGORITHM:

1. Print the menu options for temperature conversion.


2. Prompt the user to enter their choice.
3. If the choice is 1:
a. Prompt the user to enter the temperature in Fahrenheit.
b. Perform the Fahrenheit to Celsius conversion using the formula:
(5/9) * (f - 32)
c. Print the converted temperature in Celsius.
4. If the choice is 2:
a. Prompt the user to enter the temperature in Celsius.
b. Perform the Celsius to Fahrenheit conversion using the formula:
(9/5) * c + 32
c. Print the converted temperature in Fahrenheit.
5. If the choice is neither 1 nor 2, print a message indicating that the choice is invalid.
6. The algorithm guides the program's flow, ensuring that the appropriate temperature
conversion is performed based on the user's choice.
PROGRAM CODE:

print("1. Fahrenheit to Celsius Conversion")

print("2. Celsius to Fahrenheit Conversion")

ch = int(input("Enter Your Choice: "))

if ch == 1:

f = int(input("Enter the temperature in Fahrenheit: "))

c = (5 / 9) * (f - 32)

print(f, "Degree Fahrenheit is equal to %.2f" % c, "Degree Celsius")

elif ch == 2:

c = int(input("Enter the temperature in Celsius: "))

f = (9 / 5) * c + 32

print(c, "Degree Celsius is equal to %.2f" % f, "Degree Fahrenheit")

else:

print("Wrong Choice.")

OUTPUT:
RESULT:

This python code executed user selected option 1. For Fahrenheit to Celsius conversion and
entered a temperature of 189 degrees Fahrenheit. The program then calculated and
displayed the equivalent temperature in Celsius as 87.22 degrees.

2. Write a python program to construct the following pattern, using a nested loop
*
**
***
****
*****
****
***
**
*
AIM:

Program is to construct a specific pattern using nested loops in Python.

ALGORITHM:

1. Start by defining the number of rows for the pattern.


2. Use the first loop to iterate from 1 to the number of rows (inclusive).
3. Inside the first loop, use the second loop to print asterisks based on the current row number.
4. Print a newline character (\n) after printing the asterisks for each row in the first loop.
5. After the first loop completes, use a third loop to iterate from rows - 1 down to 1.
6. Inside the third loop, use a fourth loop to print asterisks based on the current row number.
7. Print a newline character after printing the asterisks for each row in the third loop.
8. The pattern construction is complete.
PROGRAM CODE:

rows = 5 # Number of rows in the pattern

for i in range(1, rows + 1):

for j in range(i):

print("*", end="")

print()

for i in range(rows - 1, 0, -1):

for j in range(i):

print("*", end="")

print()
OUTPUT:

RESULT:

This program uses nested loops to first print the increasing pattern from 1 to rows, and then
it prints the decreasing pattern from rows - 1 to 1, resulting in the desired pattern.
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 <70 Grade D: Percentage >=40 and <60
Grade E: Percentage < 40

AIM:

Program is to calculate the total marks, percentage, and grade of a student based on the
marks obtained in five subjects, which will be input by the user. The program will then
assign grades to the student according to the given criteria.

ALGORITHM:

1. Start the program.


2. Initialize variables to store the marks of five subjects and other necessary variables like
totalMarks, percentage, and grade.
3. Prompt the user to input marks for each subject one by one.
4. Calculate the totalMarks by adding up the marks obtained in all five subjects.
5. Calculate the percentage by dividing the totalMarks by 500 (assuming each subject is out of
100 marks) and multiplying by 100.
6. Determine the grade based on the percentage using the following criteria:
7. If percentage >= 80, assign grade as "A".
8. If 70 <= percentage < 80, assign grade as "B".
9. If 60 <= percentage < 70, assign grade as "C".
10. If 40 <= percentage < 60, assign grade as "D".
11. If percentage < 40, assign grade as "E".
12. Display the totalMarks, percentage, and grade to the user.
13. End the program.

PROGRAM CODE:
College = input("Enter the College Name: ")

Department = input("Enter the Department Name: ")

Roll_No = int(input("Enter the Roll Number: "))

Stud_Name = input("Enter the Student Name: ")

print("Enter Marks Obtained in 5 Subjects: ")

Tamil = int(input("Enter the Tamil Obtained Mark:"))

English = int(input("Enter the English Obtained Mark:"))

Python_Programming = int(input("Enter the Python_Programming Obtained Mark:"))

Mathematics = int(input("Enter the Mathematics Obtained Mark:"))

Python_Lab = int(input("Enter the Python Programming Practical Obtained Mark:"))

Total = Tamil + English + Python_Programming + Mathematics + Python_Lab

Percentage = Total / 5

print("Total:", Total)

print("Percentage:", Percentage)

if Percentage >= 80 and Percentage <= 100:

print("Your Grade is A")

elif Percentage >= 70 and Percentage < 80:

print("Your Grade is B")

elif Percentage >= 60 and Percentage < 70:

print("Your Grade is C")

elif Percentage >= 40 and Percentage < 60:

print("Your Grade is D")

elif Percentage < 40:

print("Your Grade is E")


else:

print("Invalid Input!")

OUTPUT:
RESULT:

The program was successfully executed. It calculates the total marks, percentage, and grade
of a student based on marks obtained in five subjects and displays the result according to
the given grading criteria.
4. Program, to find the area of rectangle, square, circle and triangle by accepting
suitable input parameters from user.

AIM:

Program is to calculate the area of different geometric shapes (rectangle, square, circle, and
triangle) based on the input parameters provided by the user.

ALGORITHM:

1. Display a menu to the user with options to choose the shape for which they want to calculate
the area: Rectangle, Square, Circle, or Triangle.
2. Based on the user's input, prompt for the necessary parameters required to calculate the area
of the chosen shape.
3. Perform the area calculation based on the formula for each shape.
4. Display the calculated area to the user.

PROGRAM CODE:
import math

print("----- Area Calculation Program -----")

# Rectangle
length = float(input("Enter the length of rectangle: "))
breadth = float(input("Enter the breadth of rectangle: "))
area_rectangle = length * breadth

# Square
side = float(input("\nEnter the side of square: "))
area_square = side * side

# Circle
radius = float(input("\nEnter the radius of circle: "))
area_circle = math.pi * radius * radius

# Triangle
base = float(input("\nEnter the base of triangle: "))
height = float(input("Enter the height of triangle: "))
area_triangle = 0.5 * base * height

# -------- Result --------


print("\n------ Results ------")
print(f"Area of Rectangle : {area_rectangle:.2f}")
print(f"Area of Square : {area_square:.2f}")
print(f"Area of Circle : {area_circle:.2f}")
print(f"Area of Triangle : {area_triangle:.2f}")
OUTPUT:

RESULT:

This python code to find the area of rectangle, square, circle and triangle by accepting
suitable input parameters from user, executed successfully.

5. Write a Python script that prints prime numbers less than 20.
AIM:
This Python script is to find and print all prime numbers less than 20 using the trial division
method.

ALGORITHM:

1. Define a function is_prime(number) that takes a positive integer number as input and checks
if it is prime.
2. In the is_prime function, first, handle the special cases where the number is less than 2 (not
prime) or equal to 2 (prime).
3. For numbers greater than 2, check divisibility by integers from 2 up to the number itself
(exclusive).
4. If the number is divisible by any integer in the range, it is not prime, and the function returns
False.
5. If the number is not divisible by any integer in the range, it is prime, and the function returns
True.
6. In the main part of the script, set the limit to 20 and use a list comprehension to find all
prime numbers less than the limit using the is_prime function.
7. Print the list of prime numbers.
PROGRAM CODE:

def is_prime(number):

if number < 2:

return False

for i in range(2, number):

if number % i == 0:

return False

return True

if __name__ == "__main__":

limit = 20

prime_numbers = [num for num in range(2, limit) if is_prime(num)]

print("Prime numbers less than", limit, "are:")

print(prime_numbers)
OUTPUT:

RESULT:

It will correctly print the prime numbers less than 20 using the trial division method to
check for primality. However, as mentioned earlier, this method becomes inefficient for
larger numbers

6. Program to find factorial of the given number using recursive function.


AIM:
The aim of this Python code is to calculate the factorial of a given input number 'n' using
recursion.

ALGORITHM:

1. Define the function factorial(v) that takes a positive integer 'v' as input and returns its
factorial.
2. Inside the factorial() function:
a. Check if 'v' is less than or equal to 1. If true, return 1, as the factorial of 0 and 1 is 1.
b. If 'v' is greater than 1, calculate the factorial by multiplying 'v' with the factorial of 'v-
1'. This is done by recursively calling the factorial() function with the argument 'v-1'.
c. The recursive calls will continue until 'v' reaches 1 or 0, and then the function will start
returning the calculated factorial values back up the recursion stack.
3. Ask the user to input a value 'n' and store it in the variable 'n'.
4. Call the factorial(n) function to calculate the factorial of 'n'.
5. Print the result as "The factorial of [n] is [factorial_value]".

PROGRAM CODE:

def factorial(v):
if v<=1:
return 1
else:
return v*factorial(v-1)
n=int(input("Enter the value of n:"))
print("The factorial of",n,"is",factorial(n))

OUTPUT:
RESULT:
This program to find factorial of the given number is 10!= 3628800, using recursive
function.

7. Write a Python program to count the number of even and odd numbers from array
of N numbers

AIM:
To design a program that counts the number of even and odd numbers in an array of N
numbers.

ALGORITHM:

1. Start the program.


2. Define a function count_even_odd(arr) that takes an array (arr) as input.
3. Initialize two variables even_count and odd_count to 0 to store the counts of even and odd
numbers, respectively.
4. Iterate through each element in the array arr.
a. Check if the element is even or odd using the modulus operator (%).
b. If the element is even, increment the even_count by 1.
c. If the element is odd, increment the odd_count by 1.
5. After iterating through all the elements in the array, return the even_count and odd_count.
6. In the main section of the program:
a. Take input from the user as a space-separated list of numbers.
b. Convert the input into a list of integers.
c. Call the count_even_odd function with the list of numbers as an argument and store the
results in variables even and odd.
d. Print the counts of even and odd numbers.

PROGRAM CODE:

def count_even_odd(arr):

even_count = 0

odd_count = 0
for num in arr:

if num % 2 == 0:

even_count += 1

else:

odd_count += 1

return even_count, odd_count

# Example usage:

if __name__ == "__main__":

try:

# Input your N numbers separated by spaces

input_numbers = input("Enter the numbers separated by spaces: ")

numbers_list = list(map(int, input_numbers.split()))

even, odd = count_even_odd(numbers_list)

print(f"Number of even numbers: {even}")

print(f"Number of odd numbers: {odd}")

except ValueError:

print("Invalid input. Please enter valid integer numbers separated by spaces.")

OUTPUT:
RESULT:

The input array contains five even numbers (66, 78, 64, 106, and 906) and three odd
numbers (77, 99, and 99). The program correctly counts and displays these results.

8. Write a Python class to reverse a string word by word.

AIM:

The goal is to create a Python class that provides a method to reverse the order of words in
a given string. For example, the input "hello world" should become "world hello".

ALGORITHM:

1. Define a class: Create a class, for instance, StringReverser, to encapsulate the word-
reversal logic.

2. Define a method: Within the class, create a method (e.g., reverse_words) that takes a
string as input.
3. Reverse the list of words: Reverse the order of the words in the list. This can be done
efficiently using Python's slice notation [::-1] on the list or by using
the reversed() function.

4. Join the words: Use the join() method with a space (' ') as the separator to combine the
reversed list of words back into a single string.

5. Return the result: The method should return the newly formed string with the words in
reversed order.

6. Instantiate and call: Create an instance of the StringReverser class and call
the reverse_words method with the string you want to reverse to get the final output.

PROGRAM CODE:

class StringReverser:

def reverse_words(self, s: str) -> str:

words = s.split()

reversed_words = words[::-1]

return " ".join(reversed_words)

input_string = "Python is a powerful language"


reverser = StringReverser()

reversed_string = reverser.reverse_words(input_string)

print(f"Original string: '{input_string}'")

print(f"Reversed string: '{reversed_string}'")

OUTPUT:
RESULT:

Original string: 'Python is a powerful language'


Reversed string: 'language powerful a is Python'

This output demonstrates that the class successfully takes a string, reverses the order of its
words, and returns the new string with the words arranged from last to first, separated by
single spaces.

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)

AIM:

This program is to count the occurrences of all items from a given list in a given tuple.

ALGORITHM:

1. Create a function called count_occurrences(tuple_data, list_data) to count occurrences.


2. Initialize a dictionary called occurrences_dict to store the count of each item from the list.
3. Loop through each item in the list data:
a. For each item, initialize its count to 0 in the occurrences_dict.
4. Loop through each item in the tuple_data:
a. If the item is present in the occurrences_dict, increment its count by 1.
5. After counting all occurrences, sum up the counts of all items from the list_data present in
the occurrences_dict.
6. Return the total count.

PROGRAM CODE:

def count_occurrences(tuple_data, list_data):

occurrences_dict = {item: 0 for item in list_data}

for item in tuple_data:

if item in occurrences_dict:

occurrences_dict[item] += 1

total_count = sum(occurrences_dict.values())

return total_count
# Test the function with the provided input

tuple_input = ('a', 'a', 'c', 'b', 'd')

list_input = ['a', 'b']

output = count_occurrences(tuple_input, list_input)

print("Count the occurrences of all items of the list in the tuple:", output)

OUTPUT:
RESULT:

When you run the program, the output will be:

Count of occurrences of items from the list in the tuple: 3

This means that the items 'a' and 'b' from the list appear a total of 3 times in the given tuple.

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

AIM:
To create a SavingsAccount class that inherits from a BankAccount class, includes an
interest rate attribute, and provides a method to apply interest to the account balance.

ALGORITHM:

1. Define the BankAccount class with attributes like account_number, holder_name,


and balance.

2. Create constructor __init__ in BankAccount to initialize the attributes.

3. Add methods to BankAccount:

o deposit(amount)

o withdraw(amount)

o get_balance()

4. Define the SavingsAccount class as a subclass of BankAccount.

5. Add an interest_rate attribute in the SavingsAccount constructor and call the


superclass constructor.

6. Create method apply_interest() that calculates interest and adds it to the balance.

7. Create an object of SavingsAccount, perform deposit/withdraw/apply interest


operations, and display results.

PROGRAM CODE:

class BankAccount:

def __init__(self, account_number, account_holder, balance):


self.account_number = account_number

self.account_holder = account_holder

self.balance = balance

def deposit(self, amount):

self.balance += amount

return f"Deposited ${amount}. New balance: ${self.balance}"

def withdraw(self, amount):

if amount <= self.balance:

self.balance -= amount

return f"Withdrew ${amount}. New balance: ${self.balance}"

else:

return "Insufficient funds"

def get_balance(self):

return f"Current balance: ${self.balance}"

class SavingsAccount(BankAccount):

def __init__(self, account_number, account_holder, balance, interest_rate):

super().__init__(account_number, account_holder, balance)

self.interest_rate = interest_rate

def calculate_interest(self):

interest = self.balance * self.interest_rate


self.balance += interest

return f"Interest added: ${interest}. New balance: ${self.balance}"

# Creating instances of SavingsAccount

savings_account = SavingsAccount("90435642", "Vijay Shankar E1000, 0.05)

print(savings_account.get_balance())

print(savings_account.deposit(500))

print(savings_account.calculate_interest())

print(savings_account.withdraw(2000))

OUTPUT:
RESULT:

This shows that the SavingsAccount behaves like a BankAccount with the added benefit of
interest accumulation, achieving the desired functionality using inheritance.

11. Read a file content and copy only the contents at odd lines into a new file.

AIM:
This task is to selectively copy the contents of an input file's odd-numbered lines into an
output file. This is done to filter and manipulate the data in the file, considering only the
lines with odd line numbers.

ALGORITHM:

1. Specify Input and Output Files: Define the paths to the input file (from which you want to
read) and the output file (where you want to save the odd lines).
2. Open Input File: Use the open() function to open the input file in read mode ('r'). This
creates a file object that allows reading the content.
3. Read Input File Lines: Use the readlines() method on the file object to read all lines from
the input file into a list. Each element of the list corresponds to a line from the file.
4. Filter Odd Lines: Iterate through the list of lines using a loop. For each line, use the index
(line number) to determine if it's an odd line. Lines are indexed starting from 0, so lines
with even indexes (0, 2, 4, ...) are considered odd lines.
5. Write Odd Lines to Output File: Create or open the output file in write mode ('w'). Use the
writelines() method to write the selected odd lines into the output file.
6. Close Files: Close both the input and output files using the close() method on their
respective file objects. This is important for proper file handling.

PROGRAM CODE:

def copy_odd_lines(input_file, output_file):

with open(input_file, 'r') as source_file, open(output_file, 'w') as target_file:


lines = source_file.readlines()

odd_lines = [line for idx, line in enumerate(lines) if idx % 2 == 0]

target_file.writelines(odd_lines)

# Provide input and output file paths

input_file_path = r" C:\Users\SriYogaSankar\OneDrive\Desktop\input.txt"

output_file_path = r" C:\Users\SriYogaSankar\OneDrive\Desktop\ odd_lines_output.txt"

copy_odd_lines(input_file_path, output_file_path)

OUTPUT:
RESULT:

The provided code is intended to read an input file, copy only the contents of the odd-
numbered lines, and then save those contents to an output file. It's important to note that I
can't directly execute code or access files on your computer, so I can't show you the exact
output on your machine. However, I can guide you through what the expected results would
be based on the code you provided.

12. Create a Turtle graphics window with specific size.

AIM:
This code is to create a Turtle graphics window with the specified width and height.

ALGORITHM:

1. Import the turtle module.


2. Create a function called fill_circle that takes a color as input.
3. In the fill_circle function, set the fill color to the specified color.
4. Call the begin_fill() function.
5. Call the circle() function with the radius of the circle as the argument.
6. Call the end_fill() function.
7. In the main function, create a turtle graphics window.
8. Set the turtle speed to 10.
9. Lift the turtle pen.
10.Move the turtle to the origin.
11.Lower the turtle pen.
12.Call the fill_circle function with the color "red" as the argument.
13.Wait for the user to click on the screen to close the window.

PROGRAM CODE:

import turtle
def create_turtle_window(width, height):
#Creates a Turtle graphics window with the specified width and height.
screen = turtle.Screen()
screen.bgcolor("yellow")
screen.setup(width, height)
return screen

def fill_circle(color):
#Fills a circle with the specified color.
turtle.fillcolor(color)
turtle.begin_fill()
turtle.circle(100)
turtle.end_fill()

if __name__ == "__main__":
screen = create_turtle_window(800, 500)

turtle.speed(10)
turtle.penup()
turtle.goto(0, 0)
turtle.pendown()
fill_circle("red")
screen.exitonclick()

OUTPUT:
RESULT:

This code will create a Turtle graphics window with the specified width and height. The
user can then use the Turtle graphics library to draw the red circle on the screen.

13. Write a Python program for Towers of Hanoi using recursion.


AIM :
The Towers of Hanoi is a classic puzzle that involves moving a tower of disks from one
peg to another peg, with the help of a spare peg, subject to the following rules:
1. Only one disk can be moved at a time.
2. Each move consists of taking the top disk from one of the stacks and placing it on top of
another stack.
3. No disk may be placed on top of a smaller disk.

ALGORITHM:
The recursive solution to the Towers of Hanoi puzzle involves breaking down the problem
into smaller sub-problems:
1. Move n-1 disks from the source peg to the spare peg, using the destination peg as the
auxiliary peg.
2. Move the nth disk from the source peg to the destination Tower.
3. Move the n-1 disks from the spare Tower to the destination Tower, using the source Tower
as the auxiliary Tower.
4. This process is repeated recursively until the base case is reached, which is when there's only
one disk left to move.

PROGRAM CODE:
def towers_of_hanoi(n, source, destination, spare):
if n == 1:
print(f"Move disk 1 from {source} to {destination}")
return
towers_of_hanoi(n - 1, source, spare, destination)
print(f"Move disk {n} from {source} to {destination}")
towers_of_hanoi(n - 1, spare, destination, source)
# Driver code
num_disks = int(input("Enter the number of disks: "))
towers_of_hanoi(num_disks, 'A', 'C', 'B') # 'A', 'B', 'C' are the source, spare, destination
towers

OUTPUT:
RESULT:
In this program, the towers_of_hanoi function takes the number of disks (n) and the Tower
labels (source, destination, spare) as arguments and prints the steps required to solve the
puzzle. When you run the program, it will prompt you to enter the number of disks, and
then it will show the sequence of steps to solve the Towers of Hanoi puzzle for that number
of disks.
14. Create a menu driven Python program with a dictionary for words and their
meanings.
AIM:
Program is to provide an interactive dictionary-like experience to the user. It allows the user
to look up the meanings of words, add new words and their meanings to the dictionary, and
exit the program when desired.
ALGORITHM:
1. Initialize an empty dictionary called word_meanings to store words and their meanings.
2. Define the display_menu() function to show the user the available options:
a. Look up a word
b. Add a new word and its meaning
c. Exit
3. Define the look_up_word() function to:
a. Prompt the user to enter a word.
b. Check if the entered word exists in the word_meanings dictionary:
a. If it exists, display the meaning of the word.
b. If it doesn't exist, inform the user that the word is not found in the dictionary.
4. Define the add_new_word() function to:
a. Prompt the user to enter a new word and its meaning.
b. Add the new word and its meaning to the word_meanings dictionary.
5. Implement a main program loop that runs indefinitely:
a. Display the menu options using the display_menu() function.
b. Prompt the user to enter their choice.
c. Based on the user's choice:
a. If the choice is "Look up a word," call the look_up_word() function.
b. If the choice is "Add a new word and its meaning," call the add_new_word()
function.
c. If the choice is "Exit," break out of the loop.
d. If the choice is invalid, inform the user.
6. When the user chooses to exit the program, display a message indicating the program is
exiting, and break out of the main loop.

PROGRAM CODE:
# Dictionary to store words and meanings
word_meanings = {}
def display_menu():
print("Menu:")
print("1. Look up a word")
print("2. Add a new word and its meaning")
print("3. Exit")
def look_up_word():
word = input("Enter the word to look up: ")
if word in word_meanings:
print(f"Meaning of '{word}': {word_meanings[word]}")
else:
print(f"'{word}' not found in the dictionary.")
def add_new_word():
word = input("Enter the new word: ")
meaning = input(f"Enter the meaning of '{word}': ")
word_meanings[word] = meaning
print(f"'{word}' and its meaning added to the dictionary.")
# Main program loop
while True:
display_menu()
choice = input("Enter your choice: ")
if choice == '1':
look_up_word()
elif choice == '2':
add_new_word()
elif choice == '3':
print("Exiting the program.")
break
else:
print("Invalid choice. Please select a valid option.")
OUTPUT:

RESULT:
The program's focuses on providing a user-friendly interface for looking up word meanings
and updating the dictionary as needed. The main loop ensures that the user can interact with
the program as long as they want, and the defined functions modularize the different tasks,
making the code more readable and maintainable.
15. Devise a Python program to implement the Hangman Game.

AIM :
The Hangman game is to create an interactive word guessing game where one player thinks
of a word, and the other player (or the computer) attempts to guess the word by suggesting
letters. The player's objective is to guess the word correctly within a limited number of
attempts while minimizing the number of incorrect guesses.

ALGORITHM :
Initialization:
a. Create a list of words from which the random word will be chosen.
b. Set the maximum number of attempts (e.g., 6) before the player loses.
c. Initialize an empty list to keep track of guessed letters.
d. Select a random word from the list of words to be guessed.
Main Game Loop:
a. Display a welcome message to the player.
b. Enter a loop that continues until the game is won or lost.
Display Word:
a. Create a function that takes the current word and the list of guessed letters as input and
returns a display string with underscores (_) for unguessed letters and the actual letters for
guessed letters.
Player's Turn:
a. Display the current state of the word using the display string.
b. Prompt the player to input a letter guess.
c. Validate the input to ensure it's a single letter.
d. Check if the guessed letter has already been guessed.
Letter Check:
a. If the guessed letter is in the word, inform the player that it's a good guess and update the
guessed letters list.
b. If the guessed letter is not in the word, inform the player that it's an incorrect guess,
decrement the remaining attempts, and update the guessed letters list.
Game Over Conditions:
a. If the remaining attempts become zero, display a message that the player has lost along with
the correct word.
b. If all letters in the word have been correctly guessed, display a message that the player has
won.
Game Over:
a. Break out of the loop once the game is won or lost.
Play Again:
a. Ask the player if they want to play again. If yes, go back to step 1.
Enhancements:
This basic algorithm can be enhanced in several ways:
a. Implement graphics for the hangman figure using ASCII art or images.
b. Provide a more extensive word list.
c. Implement scoring based on the number of attempts taken to guess the word.
d. Allow players to choose a difficulty level (easy, medium, hard) that affects the word
selection or number of attempts.
e. Create a graphical user interface (GUI) for a more interactive experience.
Remember that this is a simplified version of the Hangman game. More advanced versions
can include features like multiplayer modes, more complex scoring systems, and integration
with external word APIs for a wider variety of words to guess.

PROGRAM CODE:
import random
def choose_random_word():
word_list = ["apple", "banana", "cherry", "dog", "elephant", "fruit", "grape", "house",
"icecream", "jungle"]
return random.choice(word_list)

def display_word(word, guessed_letters):


display = ''
for letter in word:
if letter in guessed_letters:
display += letter
else:
display += '_'
return display

def hangman():
max_attempts = 6
guessed_letters = []
word_to_guess = choose_random_word()

print("Welcome to Hangman!")

while True:
print("\n" + display_word(word_to_guess, guessed_letters))
guess = input("Guess a letter: ").lower()

if len(guess) != 1 or not guess.isalpha():


print("Please enter a valid letter.")
continue
if guess in guessed_letters:
print("You already guessed that letter.")
continue

guessed_letters.append(guess)

if guess in word_to_guess:
print("Good guess!")
else:
print("Incorrect guess.")
max_attempts -= 1

if max_attempts == 0:
print("\nSorry, you lost! The word was:", word_to_guess)
break
if set(guessed_letters) == set(word_to_guess):
print("\nCongratulations! You guessed the word:", word_to_guess)
break
if __name__ == "__main__":
hangman()

OUTPUT:
Welcome to Hangman!
_____
Guess a letter: j
Incorrect guess.

_____
Guess a letter: a
Good guess!

a____
Guess a letter: p
Good guess!

app__
Guess a letter: l
Good guess!

appl_
Guess a letter: e
Good guess!

apple
Guess a letter: b
Incorrect guess.

apple
Guess a letter: a
You already guessed that letter.

apple
Guess a letter: f
Incorrect guess.

apple
Guess a letter: n
Incorrect guess.

apple
Guess a letter: l
You already guessed that letter.

apple
Guess a letter: j
You already guessed that letter.

apple
Guess a letter: l
You already guessed that letter.

apple
Guess a letter: j
You already guessed that letter.

apple
Guess a letter: k
Incorrect guess.

apple
Guess a letter: l
You already guessed that letter.

apple
Guess a letter: n
You already guessed that letter.

apple
Guess a letter: ,
Please enter a valid letter.

apple
Guess a letter: b
You already guessed that letter.
apple
Guess a letter: m
Incorrect guess.
Sorry, you lost! The word was: apple
RESULT:
The player made a series of guesses. They guessed some letters correctly and some
incorrectly. Unfortunately, they reached the maximum number of attempts and lost the
game. The correct word was "apple."

You might also like