Python Programming Lab
Python Programming Lab
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:
if ch == 1:
c = (5 / 9) * (f - 32)
elif ch == 2:
f = (9 / 5) * c + 32
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:
ALGORITHM:
for j in range(i):
print("*", end="")
print()
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:
PROGRAM CODE:
College = input("Enter the College Name: ")
Percentage = Total / 5
print("Total:", Total)
print("Percentage:", Percentage)
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
# 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:
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
if number % i == 0:
return False
return True
if __name__ == "__main__":
limit = 20
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
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:
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
# Example usage:
if __name__ == "__main__":
try:
except ValueError:
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.
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:
words = s.split()
reversed_words = words[::-1]
reversed_string = reverser.reverse_words(input_string)
OUTPUT:
RESULT:
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:
PROGRAM CODE:
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
print("Count the occurrences of all items of the list in the tuple:", output)
OUTPUT:
RESULT:
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:
o deposit(amount)
o withdraw(amount)
o get_balance()
6. Create method apply_interest() that calculates interest and adds it to the balance.
PROGRAM CODE:
class BankAccount:
self.account_holder = account_holder
self.balance = balance
self.balance += amount
self.balance -= amount
else:
def get_balance(self):
class SavingsAccount(BankAccount):
self.interest_rate = interest_rate
def calculate_interest(self):
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:
target_file.writelines(odd_lines)
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.
AIM:
This code is to create a Turtle graphics window with the specified width and height.
ALGORITHM:
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.
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 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()
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."