0% found this document useful (0 votes)
2 views21 pages

Python Practicals Source Code

The document contains multiple Python programs covering various topics such as temperature conversion, pattern printing, student details, area calculations, prime number generation, factorial computation, even and odd number counting, string reversal, tuple and list operations, savings account management, file reading and writing, turtle graphics, and the Towers of Hanoi problem. Each program includes user interaction and output examples. The programs demonstrate fundamental programming concepts and techniques in Python.

Uploaded by

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

Python Practicals Source Code

The document contains multiple Python programs covering various topics such as temperature conversion, pattern printing, student details, area calculations, prime number generation, factorial computation, even and odd number counting, string reversal, tuple and list operations, savings account management, file reading and writing, turtle graphics, and the Towers of Hanoi problem. Each program includes user interaction and output examples. The programs demonstrate fundamental programming concepts and techniques in Python.

Uploaded by

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

‭Program 1 : Temperature Conversion‬

‭ rogram :‬
P
‭# Temperature conversion program: Fahrenheit <-> Celsius‬
‭print("Temperature Converter")‬
‭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 = (f - 32) * 5 / 9‬
‭print("Temperature in Celsius:", c)‬

‭elif choice == "2":‬


‭c = float(input("Enter temperature in Celsius: "))‬
‭f = (c * 9 / 5) + 32‬
‭print("Temperature in Fahrenheit:", f)‬
‭else:‬
‭print("Invalid choice. Please enter 1 or 2.")‬

‭Output 1:‬

‭ nter your choice (1 or 2): 1‬


E
‭Enter temperature in Fahrenheit: 98.6‬

‭Temperature in Celsius: 37.0‬

‭ utput 2:‬
O
‭Enter your choice (1 or 2): 2‬
‭Enter temperature in Celsius: 100‬

‭Temperature in Fahrenheit: 212.0‬


‭Program 2 : Pattern Printing‬

n‭ = int(input("Enter the number of rows for the upper half: "))‬


‭# Upper half‬
‭for i in range(1, n + 1):‬
‭spaces = n - i‬
‭stars = 2 * i - 1‬
‭print(' ' * spaces + '*' * stars)‬

#‭ Lower half‬
‭for i in range(n - 1, 0, -1):‬
‭spaces = n - i‬
‭stars = 2 * i - 1‬
‭print(' ' * spaces + '*' * stars)‬

‭OUTPUT‬

‭Enter the number of rows for the upper half: 4‬


‭*‬
‭***‬
‭*****‬
‭*******‬
‭*****‬
‭***‬
‭*‬
‭Program 3: Student Details‬

‭print("Enter marks for 5 subjects out of 100:")‬

#‭ Accepting marks from user‬


‭subject1 = int(input("Subject 1: "))‬
‭subject2 = int(input("Subject 2: "))‬
‭subject3 = int(input("Subject 3: "))‬
‭subject4 = int(input("Subject 4: "))‬
‭subject5 = int(input("Subject 5: "))‬

#‭ Total marks calculation‬


‭total = subject1 + subject2 + subject3 + subject4 + subject5‬

#‭ Percentage calculation‬
‭percentage = (total * 100) / 500‬

#‭ Grade assignment‬
‭if percentage >= 80:‬
‭grade = 'A'‬
‭elif percentage >= 70:‬
‭grade = 'B'‬
‭elif percentage >= 60:‬
‭grade = 'C'‬
‭elif percentage >= 40:‬
‭grade = 'D'‬
‭else:‬
‭grade = 'E'‬

#‭ Output‬
‭print("\n--- Result ---")‬
‭print("Total Marks:", total)‬
‭print("Percentage:", percentage, "%")‬
‭print("Grade:", grade)‬
‭ utput:‬
O
‭Subject 1: 75‬
‭Subject 2: 80‬
‭Subject 3: 65‬
‭Subject 4: 70‬
‭Subject 5: 85‬

‭ otal Marks: 375‬


T
‭Percentage: 75.0 %‬
‭Grade: B‬
‭Program 4‬‭. Find the area of rectangle, square, circle‬‭and triangle by accepting‬
‭suitable input parameters from the user.‬

‭Program code:‬

i‭mport math‬
‭print("Choose the 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 = length * breadth‬
‭print("Area of Rectangle =", area)‬

‭elif choice == 2:‬


‭side = float(input("Enter the side of the square: "))‬
‭area = side * side‬
‭print("Area of Square =", area)‬

‭elif choice == 3:‬


‭radius = float(input("Enter the radius of the circle: "))‬
‭area = [Link] * radius * radius‬
‭print("Area of Circle =", area)‬

‭elif choice == 4:‬


‭base = float(input("Enter the base of the triangle: "))‬
‭height = float(input("Enter the height of the triangle: "))‬
‭area = 0.5 * base * height‬
‭print("Area of Triangle =", area)‬

‭else:‬
‭print("Invalid choice!")‬
‭Output:‬

‭ nter your choice (1-4): 1‬


E
‭Enter the length of the rectangle: 10‬
‭Enter the breadth of the rectangle: 5‬

‭Area of Rectangle = 50.0‬

‭ nter your choice (1-4): 3‬


E
‭Enter the radius of the circle: 7‬

‭Area of Circle = 153.93804002589985‬


‭5. Write a Python script that prints prime numbers less than 20.‬

‭Program:‬

#‭ Function to check if a number is prime‬


‭def is_prime(num):‬
‭if num < 2:‬
‭return False‬
‭for i in range(2, num):‬
‭if num % i == 0:‬
‭return False‬
‭return True‬

#‭ Get user input‬


‭n = int(input("Enter a number: "))‬

‭print(f"Prime numbers less than {n} are:")‬

‭for i in range(2, n):‬


‭if is_prime(i):‬
‭print(i, end=" ")‬

‭ utput:‬
O
‭Enter a number: 10‬
‭Prime numbers less than 10 are:‬
‭2 3 5 7‬

‭ nter a number: 20‬


E
‭Prime numbers less than 20 are:‬
‭2 3 5 7 11 13 17 19‬
‭Program 6: To find the factorial of the given number using a recursive‬
‭function.‬

‭Program:‬

#‭ Recursive function to calculate factorial‬


‭def factorial(n):‬
‭if n == 0 or n == 1:‬
‭return 1‬
‭else:‬
‭return n * factorial(n - 1)‬

#‭ Get user input‬


‭num = int(input("Enter a number to find its factorial: "))‬

#‭ Check for negative input‬


‭if num < 0:‬
‭print("Factorial is not defined for negative numbers.")‬
‭else:‬
‭result = factorial(num)‬
‭print(f"The factorial of {num} is {result}")‬

‭Output :‬

‭Enter a number to find its factorial: 5‬

‭The factorial of 5 is 120‬

‭Enter a number to find its factorial: 0‬

‭The factorial of 0 is 1‬
‭Program 7: Write a Python program to count the number of even and odd‬
‭numbers from an array of N numbers.‬

‭Program:‬

‭# Get the number of elements from the user‬

‭n = int(input("Enter the number of elements: "))‬

‭# Initialize counters‬

‭even_count = 0‬

‭odd_count = 0‬

‭# Read n numbers from the user‬

‭print(f"Enter {n} numbers:")‬

‭for i in range(n):‬

‭num = int(input())‬

‭if num % 2 == 0:‬

‭even_count += 1‬

‭else:‬

‭odd_count += 1‬

‭# Display the results‬

‭print("Number of even numbers:", even_count)‬

‭print("Number of odd numbers:", odd_count)‬


‭Output :‬

‭Enter the number of elements: 5‬

‭Enter 5 numbers:‬

‭1‬

‭2‬

‭3‬

‭4‬

‭5‬

‭Number of even numbers: 2‬

‭Number of odd numbers: 3‬


‭Program 8: Write a Python class to reverse a string word by word.‬

‭Program:‬

‭class StringReverser:‬

‭def __init__(self, input_string):‬

‭self.input_string = input_string‬

‭def reverse_words(self):‬

‭words = self.input_string.split()‬

‭reversed_words = words[::-1]‬

‭return ' '.join(reversed_words)‬

‭# Accept user input‬

‭user_input = input("Enter a sentence: ")‬

‭# Create object and call method‬

‭reverser = StringReverser(user_input)‬

‭result = reverser.reverse_words()‬

‭# Display output‬

‭print("Reversed sentence word by word:")‬

‭print(result)‬

‭Output‬

‭Enter a sentence: Hello world‬

‭Reversed sentence word by word:‬

‭world Hello‬
‭Program 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.‬

‭Program:‬

#‭ Accept tuple elements from user‬


‭tuple_input = tuple(input("Enter elements of the tuple separated by spaces: ").split())‬

#‭ Accept list elements from user‬


‭list_input = input("Enter elements of the list separated by spaces: ").split()‬

#‭ Initialize counter‬
‭count = 0‬

#‭ Count occurrences of list items in the tuple‬


‭for item in list_input:‬
‭count += tuple_input.count(item)‬

#‭ Display result‬
‭print("Total occurrences of list items in tuple:", count)‬

‭ utput :‬
O
‭Enter elements of the tuple separated by spaces: a a c b d‬
‭Enter elements of the list separated by spaces: a b‬

‭Total occurrences of list items in tuple: 3‬


‭ rogram 10: Create a Savings Account class that behaves just like a Bank‬
P
‭Account, but also has an interest rate and a method that increases the balance‬
‭by the appropriate amount of interest (Hint: use Inheritance).‬

‭ rogram:‬
P
‭# Base class‬
‭class BankAccount:‬
‭def __init__(self, name, balance):‬
‭[Link] = name‬
‭[Link] = balance‬

‭def deposit(self, amount):‬


‭[Link] += amount‬

‭def display_balance(self):‬
‭print(f"Account holder: {[Link]}")‬
‭print(f"Current balance: {[Link]:.2f}")‬

#‭ Derived class‬
‭class SavingsAccount(BankAccount):‬
‭def __init__(self, name, balance, interest_rate):‬
‭super().__init__(name, balance)‬
‭self.interest_rate = interest_rate‬

‭def apply_interest(self):‬
‭interest = [Link] * (self.interest_rate / 100)‬
‭[Link] += interest‬
‭print(f"Interest of {interest:.2f} applied.")‬

#‭ --- User interaction ---‬


‭name = input("Enter account holder's name: ")‬
‭balance = float(input("Enter initial balance: "))‬
‭interest_rate = float(input("Enter interest rate (in %): "))‬

#‭ Create a SavingsAccount object‬


‭account = SavingsAccount(name, balance, interest_rate)‬

#‭ Apply interest and show results‬


‭account.apply_interest()‬
‭account.display_balance()‬
‭ utput 1:‬
O
‭Enter account holder's name: Alice‬
‭Enter initial balance: 1000‬
‭Enter interest rate (in %): 5‬

I‭ nterest of 50.00 applied.‬


‭Account holder: Alice‬
‭Current balance: 1050.00‬

‭ utput 2:‬
O
‭Enter account holder's name: Ravi‬
‭Enter initial balance: 2000‬
‭Enter interest rate (in %): 3‬

I‭ nterest of 60.00 applied.‬


‭Account holder: Ravi‬
‭Current balance: 2060.00‬
‭Program 11: Read a file content and copy only the contents at odd lines into a‬
‭new file.‬

‭Program:‬

#‭ Accept file names from user‬


‭input_file = input("Enter the input filename: ")‬
‭output_file = input("Enter the output filename: ")‬

‭try:‬
‭# Open files‬
‭with open(input_file, 'r') as infile, open(output_file, 'w') as outfile:‬
‭lines = [Link]()‬

#‭ Write only odd-numbered lines (index 0, 2, 4...)‬


‭for i in range(0, len(lines), 2):‬
‭[Link](lines[i])‬

‭print(f"Odd-numbered lines copied to '{output_file}' successfully.")‬

‭except FileNotFoundError:‬
‭print("The input file does not exist. Please check the filename and try again.")‬

‭ utput 1:‬
O
‭Line 1: Hello‬
‭Line 2: World‬
‭Line 3: Welcome‬
‭Line 4: To‬
‭Line 5: Python‬

‭ nter the input filename: [Link]‬


E
‭Enter the output filename: [Link]‬

‭ ine 1: Hello‬
L
‭Line 3: Welcome‬
‭Line 5: Python‬
‭Program 12: Create a Turtle graphics window with a specific size.‬

‭Program:‬

‭import turtle‬

‭def uppercircle():‬

‭[Link](100)‬

‭[Link](2)‬

‭[Link]('red')‬

‭for i in range(0,50,10):‬

‭[Link](i)‬

‭def lowercircle():‬

‭[Link](180)‬

‭[Link](4)‬

‭[Link]('green')‬

‭for i in range(0,50,10):‬

‭[Link](i)‬

‭#main program‬

‭t=[Link]()‬

‭[Link](500,500)‬

‭tm=[Link]()‬

‭[Link]('turtle')‬

‭uppercircle()‬

‭lowercircle()‬
‭Program 13: Write a Python program for Towers of Hanoi using recursion‬

‭Program:‬

‭def hanoi(n, source, auxiliary, target):‬

‭if n == 1:‬

‭print(f"Move disk 1 from {source} to {target}")‬

‭else:‬

‭hanoi(n-1, source, target, auxiliary)‬

‭print(f"Move disk {n} from {source} to {target}")‬

‭hanoi(n-1, auxiliary, source, target)‬

‭# Accept user input‬

‭num_disks = int(input("Enter the number of disks: "))‬

‭print(f"\nSteps to solve Towers of Hanoi for {num_disks} disks:")‬

‭hanoi(num_disks, 'A', 'B', 'C')‬

‭Output :‬

‭Enter the number of disks: 2‬

‭Steps to solve Towers of Hanoi for 2 disks:‬

‭Move disk 1 from A to B‬

‭Move disk 2 from A to C‬

‭Move disk 1 from B to C‬


‭Program 14: Create a menu driven Python program with a dictionary for‬
‭words and their meanings.‬

‭Program:‬

‭# Initialize empty dictionary‬

‭dictionary = {}‬

‭while True:‬

‭print("\n--- Dictionary Menu ---")‬

‭print("1. Add a word")‬

‭print("2. Search for a word")‬

‭print("3. Delete a word")‬

‭print("4. Display all words")‬

‭print("5. Exit")‬

‭choice = input("Enter your choice (1-5): ")‬

‭if choice == '1':‬

‭word = input("Enter the word: ")‬

‭meaning = input("Enter the meaning: ")‬

‭dictionary[word] = meaning‬

‭print(f"'{word}' added successfully.")‬

‭elif choice == '2':‬

‭word = input("Enter the word to search: ")‬

‭if word in dictionary:‬

‭print(f"Meaning of '{word}': {dictionary[word]}")‬

‭else:‬

‭print(f"'{word}' not found in dictionary.")‬


‭elif choice == '3':‬

‭word = input("Enter the word to delete: ")‬

‭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("\n--- All Words in Dictionary ---")‬

‭for word, meaning in [Link]():‬

‭print(f"{word}: {meaning}")‬

‭else:‬

‭print("Dictionary is empty.")‬

‭elif choice == '5':‬

‭print("Exiting program. Thank you!")‬

‭break‬

‭else:‬

‭print("Invalid choice! Please enter a number between 1 and 5.")‬


‭Output :‬

‭1‬

‭Enter the word: Python‬

‭Enter the meaning: A programming language‬

‭2‬

‭Enter the word to search: Python‬

‭'Python' was added successfully.‬

‭Meaning of 'Python': A programming language‬

You might also like