CONVERSION OF FAHRENHEIT TO CELSIUS AND CELSIUS TO FAHRENHEIT
PROGRAM
def fahrenheit_to_celsius(f):
return (f - 32) * 5 / 9
def celsius_to_fahrenheit(c):
return (c * 9 / 5) + 32
print("Temperature Conversion Program")
print("1. Fahrenheit to Celsius")
print("2. Celsius to Fahrenheit")
choice = input("Enter your choice (1 or 2): ")
if choice == '1':
f = float(input("Enter temperature in Fahrenheit: "))
c = fahrenheit_to_celsius(f)
print(f"{f}°F is equal to {c:.2f}°C")
elif choice == '2':
c = float(input("Enter temperature in Celsius: "))
f = celsius_to_fahrenheit(c)
print(f"{c}°C is equal to {f:.2f}°F")
else:
print("Invalid choice! Please enter 1 or 2.")
OUTPUT
Temperature Conversion Program
1. Fahrenheit to Celsius
2. Celsius to Fahrenheit
Enter your choice (1 or 2): 1
Enter temperature in Fahrenheit: 98.6
98.6°F is equal to 37.00°C
PRINT THE TRIANGLE USING NESTED LOOP
PROGRAM
rows = 5
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
*
**
***
****
*****
****
***
**
*
CALCULATE THE TOTAL MARKS, PERCENTAGE AND GRADE OF A STUDENT
PROGRAM
marks = []
for i in range(1, 6):
mark = float(input(f"Enter marks for subject {i}: "))
marks.append(mark)
total_marks = sum(marks)
percentage = total_marks / 5
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--- Result ---")
print(f"Total Marks = {total_marks}/500")
print(f"Percentage = {percentage:.2f}%")
print(f"Grade = {grade}")
OUTPUT
Enter marks for subject 1: 75
Enter marks for subject 2: 82
Enter marks for subject 3: 68
Enter marks for subject 4: 90
Enter marks for subject 5: 77
--- Result ---
Total Marks = 392.0/500
Percentage = 78.40%
Grade = B
FIND THE AREA OF A RECTANGLE, SQUARE, CIRCLE AND TRIANGLE
PROGRAM
import math
def area_rectangle(length, breadth):
return length * breadth
def area_square(side):
return side * side
def area_circle(radius):
return math.pi * radius * radius
def area_triangle(base, height):
return 0.5 * base * height
print("Choose a shape to calculate area:")
print("1. Rectangle")
print("2. Square")
print("3. Circle")
print("4. Triangle")
choice = int(input("Enter your choice (1-4): "))
if choice == 1:
length = float(input("Enter the length of the rectangle: "))
breadth = float(input("Enter the breadth of the rectangle: "))
area = area_rectangle(length, breadth)
print(f"Area of Rectangle = {area:.2f}")
elif choice == 2:
side = float(input("Enter the side of the square: "))
area = area_square(side)
print(f"Area of Square = {area:.2f}")
elif choice == 3:
radius = float(input("Enter the radius of the circle: "))
area = area_circle(radius)
print(f"Area of Circle = {area:.2f}")
elif choice == 4:
base = float(input("Enter the base of the triangle: "))
height = float(input("Enter the height of the triangle: "))
area = area_triangle(base, height)
print(f"Area of Triangle = {area:.2f}")
else:
print("Invalid choice. Please run the program again and select a valid option.")
OUTPUT
Choose a shape to calculate area:
1. Rectangle
2. Square
3. Circle
4. Triangle
Enter your choice (1-4): 1
Enter the length of the rectangle: 10
Enter the breadth of the rectangle: 5
Area of Rectangle = 50.00
FIND THE PRIME NUMBERS LESS THAN 20
PROGRAM
print("Prime numbers less than 20 are:")
for num in range(2, 20):
is_prime = True
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
is_prime = False
break
if is_prime:
print(num)
OUTPUT
Prime numbers less than 20 are:
2
3
5
7
11
13
17
19
FACTORIAL OF A NUMBER USING RECURSION
PROGRAM
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
num = int(input("Enter a number to find its factorial: "))
if num < 0:
print("Factorial is not defined for negative numbers.")
else:
result = factorial(num)
print(f"Factorial of {num} is {result}")
OUTPUT
Enter a number to find its factorial: 5
Factorial of 5 is 120
COUNT THE EVEN AND ODD NUMBERS FROM AN ARRAY OF N NUMBERS
PROGRAM
def count_even_odd(numbers):
even_count = 0
odd_count = 0
for num in numbers:
if num % 2 == 0:
even_count += 1
else:
odd_count += 1
return even_count, odd_count
N = int(input("Enter the number of elements in the array: "))
numbers = []
for i in range(N):
val = int(input(f"Enter element {i + 1}: "))
numbers.append(val)
even, odd = count_even_odd(numbers)
print(f "Even numbers count: {even}")
print(f "Odd numbers count: {odd}")
OUTPUT
Enter the number of elements in the array: 5
Enter element 1: 10
Enter element 2: 21
Enter element 3: 32
Enter element 4: 43
Enter element 5: 54
Even numbers count: 3
Odd numbers count: 2
REVERSE A STRING WORD BY WORD
PROGRAM
class StringReverser:
def __init__(self, text):
self.text = text
def reverse_words(self):
words = self.text.split()
reversed_words = words[::-1]
return ' '.join(reversed_words)
input_string = input("Enter a string: ")
reverser = StringReverser(input_string)
result = reverser.reverse_words()
print("Reversed string (word by word):", result)
OUTPUT
Enter a string: Python is fun
Reversed string (word by word): fun is Python
COUNT THE NUMBER OF OCCURRENCES USING TUPLE AND A LIST
PROGRAM
def count_occurrences(input_tuple, input_list):
count = 0
for item in input_list:
count += input_tuple.count(item)
return count
input_tuple = ('a', 'a', 'c', 'b', 'd')
input_list = ['a', 'b']
result = count_occurrences(input_tuple, input_list)
print("Total occurrences of list items in tuple:", result)
OUTPUT
Total occurrences of list items in tuple: 3
IMPLEMENTATION OF A SAVINGS ACCOUNT USING INHERITANCE
PROGRAM
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.balance = balance
def deposit(self, amount):
if amount > 0:
self.balance += amount
print(f"Deposited {amount}. New balance is {self.balance}.")
else:
print("Deposit amount must be positive.")
def withdraw(self, amount):
if 0 < amount <= self.balance:
self.balance -= amount
print(f"Withdrew {amount}. New balance is {self.balance}.")
else:
print("Invalid withdrawal amount or insufficient funds.")
def display_balance(self):
print(f"{self.owner}'s account balance: {self.balance}")
class SavingsAccount(BankAccount):
def __init__(self, owner, balance=0, interest_rate=0.02):
super().__init__(owner, balance)
self.interest_rate = interest_rate # e.g., 0.02 for 2%
def apply_interest(self):
interest = self.balance * self.interest_rate
self.balance += interest
print(f"Interest of {interest:.2f} applied. New balance is {self.balance:.2f}.")
account = SavingsAccount("Alice", 1000, 0.05)
account.display_balance()
account.deposit(500)
account.apply_interest()
account.withdraw(200)
account.display_balance()
OUTPUT
Alice's account balance: 1000
Deposited 500. New balance is 1500.
Interest of 75.00 applied. New balance is 1575.00.
Withdrew 200. New balance is 1375.0.
Alice's account balance: 1375.0
READ A FILE AND COPY ONLY THE ODD LINES INTO A NEW FILE
PROGRAM
def copy_odd_lines(source_file, dest_file):
with open(source_file, 'r') as src, open(dest_file, 'w') as dst:
for line_number, line in enumerate(src, start=1):
if line_number % 2 == 1: # odd lines
dst.write(line)
source = 'input.txt'
destination = 'odd_lines.txt'
copy_odd_lines(source, destination)
print(f"Odd lines copied from '{source}' to '{destination}'.")
OUTPUT:
Odd lines copied from 'input.txt' to 'odd_lines.txt'.
AFTER WRITING IN THE FILE
CREATE A TURTLE GRAPHICS WINDOW WITH THE SPECIFIED SIZE
PROGRAM
import turtle
screen = turtle.Screen()
screen.title("Turtle Graphics Window")
screen.setup(width=800, height=600) # Set window size to 800x600 pixels
t = turtle.Turtle()
t.write("Hello Turtle!", font=("Arial", 24, "normal"))
turtle.done()
OUTPUT:
TOWERS OF HANOI USING RECURSION
PROGRAM
def towers_of_hanoi(n, source, auxiliary, target):
if n == 1:
print(f"Move disk 1 from {source} to {target}")
return
towers_of_hanoi(n - 1, source, target, auxiliary)
print(f"Move disk {n} from {source} to {target}")
towers_of_hanoi(n - 1, auxiliary, source, target)
num_disks = int(input("Enter the number of disks: "))
towers_of_hanoi(num_disks, 'A', 'B', 'C')
OUTPUT
Enter the number of disks: 3
Move disk 1 from A to C
Move disk 2 from A to B
Move disk 1 from C to B
Move disk 3 from A to C
Move disk 1 from B to A
Move disk 2 from B to C
Move disk 1 from A to C
MENU DRIVEN PYTHON PROGRAM WITH A DICTIONARY OF WORDS AND
THEIR MEANINGS
PROGRAM
def menu():
print("\nDictionary Menu:")
print("1. Add a word")
print("2. Look up a word")
print("3. Delete a word")
print("4. View all words")
print("5. Exit")
def main():
dictionary = {}
while True:
menu()
choice = input("Enter your choice (1-5): ")
if choice == '1':
word = input("Enter the word to add: ").strip()
meaning = input(f"Enter the meaning of '{word}': ").strip()
dictionary[word] = meaning
print(f"'{word}' added successfully!")
elif choice == '2':
word = input("Enter the word to look up: ").strip()
meaning = dictionary.get(word)
if meaning:
print(f"{word}: {meaning}")
else:
print(f"'{word}' not found in dictionary.")
elif choice == '3':
word = input("Enter the word to delete: ").strip()
if word in dictionary:
del dictionary[word]
print(f"'{word}' deleted successfully!")
else:
print(f"'{word}' not found in dictionary.")
elif choice == '4':
if dictionary:
print("\nWords in dictionary:")
for word, meaning in dictionary.items():
print(f"{word}: {meaning}")
else:
print("Dictionary is empty.")
elif choice == '5':
print("Exiting program. Goodbye!")
break
else:
print("Invalid choice. Please enter a number between 1 and 5.")
if __name__ == "__main__":
main()
OUTPUT:
Dictionary Menu:
1. Add a word
2. Look up a word
3. Delete a word
4. View all words
5. Exit
Enter your choice (1-5): 1
Enter the word to add: Python
Enter the meaning of 'Python': It is a Programming Language
'Python' added successfully!
Dictionary Menu:
1. Add a word
2. Look up a word
3. Delete a word
4. View all words
5. Exit
Enter your choice (1-5): 2
Enter the word to look up: Python
Python: It is a Programming Language
Dictionary Menu:
1. Add a word
2. Look up a word
3. Delete a word
4. View all words
5. Exit
Enter your choice (1-5): 3
Enter the word to delete: Python
'Python' deleted successfully!
IMPLEMENTATION OF HANGMAN GAME USING PYTHON
PROGRAM
import random
def hangman():
words = ['python', 'programming', 'hangman', 'challenge', 'openai', 'computer', 'science']
word = random.choice(words).lower()
guessed_letters = set()
attempts_left = 6
word_letters = set(word)
print("Welcome to Hangman!")
print(f"You have {attempts_left} attempts to guess the word.")
while attempts_left > 0 and word_letters:
display_word = [letter if letter in guessed_letters else '_' for letter in word]
print("\nWord: " + ' '.join(display_word))
guess = input("Guess a letter: ").lower()
if not guess.isalpha() or len(guess) != 1:
print("Please enter a single alphabetical character.")
continue
if guess in guessed_letters:
print("You already guessed that letter. Try again.")
continue
guessed_letters.add(guess)
if guess in word_letters:
word_letters.remove(guess)
print(f"Good job! '{guess}' is in the word.")
else:
attempts_left -= 1
print(f"Sorry, '{guess}' is not in the word.")
print(f"Attempts left: {attempts_left}")
if not word_letters:
print(f"\nCongratulations! You guessed the word: {word}")
else:
print(f"\nGame Over! The word was: {word}")
if __name__ == "__main__":
hangman()
OUTPUT:
Welcome to Hangman!
You have 6 attempts to guess the word.
Word: _ _ _ _ _ _ _ _ _ _ _
Guess a letter:
Please enter a single alphabetical character.
Word: _ _ _ _ _ _ _ _ _ _ _
Guess a letter: r
Good job! 'r' is in the word.
Word: _ r _ _ r _ _ _ _ _ _
Guess a letter: o
Good job! 'o' is in the word.
Word: _ r o _ r _ _ _ _ _ _
Guess a letter: m
Good job! 'm' is in the word.
Word: _ r o _ r _ m m _ _ _
Guess a letter: i
Good job! 'i' is in the word.
Word: _ r o _ r _ m m i _ _
Guess a letter: p
Good job! 'p' is in the word.
Word: p r o _ r _ m m i _ _
Guess a letter: g
Good job! 'g' is in the word.
Word: p r o g r _ m m i _ g
Guess a letter: a
Good job! 'a' is in the word.
Word: p r o g r a m m i _ g
Guess a letter: n
Good job! 'n' is in the word.
Congratulations! You guessed the word: programming