Python Sample 1
Python Sample 1
1.a) Write a Python program to generate Electricity Bill and develop a flow chart for the
same.
Algorithm:
1. Start
2. Input the number of units consumed.
3. Define the cost per unit for different tiers:
For the first 100 units: rate1
Python Program:
def calculate_bill(units):
rate1 = 1.5 # Rate per unit for the first 100 units
rate2 = 2.5 # Rate per unit for the next 200 units
rate3 = 4.0 # Rate per unit for units above 300
return total_bill
bill = calculate_bill(units_consumed)
print(f"Total Electricity Bill: ₹{bill:.2f}")
Example Output:
Enter the number of units consumed: 350
Total Electricity Bill: ₹775.00
b) Develop a Python program to find the Biggest of 3 numbers using nested if...else
statement.
Algorithm:
1. Start.
2. Input three numbers: a, b, and c.
3. Compare a with b:
Python Program:
def find_biggest(a, b, c):
if a >= b:
if a >= c:
biggest = a
else:
biggest = c
else:
if b >= c:
biggest = b
else:
biggest = c
return biggest
Example Output:
Enter the first number: 25
Enter the second number: 42
Enter the third number: 18
The biggest number among 25.0,
******************************************************************************
3. a) Develop a Python program to read two numbers as input and Swap the Two Numbers
(using three variables).
Algorithm:
1. Start.
2. Input two numbers, a and b.
7. End.
Python Program:
def swap_numbers(a, b):
# Using a temporary variable to swap
temp = a
a = b
b = temp
return a, b
Example Output:
Enter the first number: 5
Enter the second number: 10
After swapping:
First number: 10.0
Second number: 5.0
b) Develop a Python Program to read numerator and denominator and print their quotient
and remainder.
Algorithm:
1. Start.
2. Input the numerator and the denominator.
3. Calculate the quotient using integer division (// operator).
Python Program:
def calculate_quotient_and_remainder(numerator, denominator):
quotient = numerator // denominator
remainder = numerator % denominator
return quotient, remainder
numerator = int(input("Enter the numerator: "))
denominator = int(input("Enter the denominator: "))
quotient, remainder = calculate_quotient_and_remainder(numerator, denominator)
print(f"Quotient: {quotient}")
print(f"Remainder: {remainder}")
Example Output:
Enter the numerator: 17
Enter the denominator: 5
Quotient: 3
Remainder: 2
**************************************************************************
5.a) Write a python program to get the 5 subjects marks and display the grade for the
same.
Algorithm:
1. Start.
2. Input marks for 5 subjects.
3. Calculate the total marks.
4. Calculate the percentage.
5. Determine the grade based on the percentage.
6. Print the percentage and the grade.
7. End.
Python Program:
def calculate_grade(percentage):
if percentage >= 90:
grade = 'A'
elif percentage >= 80:
grade = 'B'
elif percentage >= 70:
grade = 'C'
elif percentage >= 60:
grade = 'D'
else:
grade = 'F'
return grade
marks = []
for i in range(1, 6):
mark = float(input(f"Enter the mark for subject {i}: "))
marks.append(mark)
total_marks = sum(marks)
percentage = (total_marks / 500) * 100
grade = calculate_grade(percentage)
print(f"Total Marks: {total_marks}/500")
print(f"Percentage: {percentage:.2f}%")
print(f"Grade: {grade}")
Example Output:
Enter the mark for subject 1: 85
Enter the mark for subject 2: 90
Enter the mark for subject 3: 78
Enter the mark for subject 4: 88
Enter the mark for subject 5: 92
Total Marks: 433.0/500
Percentage: 86.60%
Grade: B
5. End.
Python Program:
def swap_numbers(a, b):
# Swap without using a temporary variable
a = a + b
b = a - b
a = a - b
return a, b
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
num1, num2 = swap_numbers(num1, num2)
Example Output:
Enter the first number: 5
Enter the second number: 10
After swapping:
First number: 10.0
Second number: 5.0
****************************************************************************
6.a) To write a python program to find the sum of first ‘n’ natural number.
Algorithm:
1. Start.
2. Input the value of n.
6. End.
Python Program:
def sum_of_natural_numbers(n):
sum = 0
for i in range(1, n + 1):
sum += i
return sum
total_sum = sum_of_natural_numbers(n)
Example Output:
Enter the value of n: 10
The sum of the first 10 natural numbers is: 55
b) Write a Python program to select a random element from a list, set, dictionary (value)
and a file from a directory. Use random.choice().
Algorithm:
1. Import the required modules: random and os.
4. Convert the set to a list and use random.choice() to select a random element.
6. Get a list of files from a specified directory and use random.choice() to select a
random file.
7. Print the selected random elements and file.
Python Program:
import random
import os
sample_list = [1, 2, 3, 4, 5]
sample_set = {10, 20, 30, 40, 50}
sample_dict = {1: 'a', 2: 'b', 3: 'c'}
random_list_element = random.choice(sample_list)
random_set_element = random.choice(list(sample_set))
random_dict_value = random.choice(list(sample_dict.values()))
directory = "F:/Python" # Change this to your directory path
if os.path.exists(directory):
files = [file for file in os.listdir(directory) if
os.path.isfile(os.path.join(directory, file))]
if files:
random_file = random.choice(files)
else:
random_file = "No files found in the directory"
else:
random_file = "Directory does not exist"
print(f"Random element from list: {random_list_element}")
print(f"Random element from set: {random_set_element}")
print(f"Random value from dictionary: {random_dict_value}")
print(f"Random file from directory: {random_file}")
Example Output:
Random element from list: 3
Random element from set: 20
Random value from dictionary: b
Random file from directory: test.txt
*****************************************************************************
7.a) write a program to create, concatenate and print a string and accessing sub-string
from given string.
Algorithm:
1. Import the required modules: random and os.
4. Convert the set to a list and use random.choice() to select a random element.
6. Get a list of files from a specified directory and use random.choice() to select a
random file.
7. Print the selected random elements and file.
Python Program:
import random
import os
sample_list = [1, 2, 3, 4, 5]
sample_set = {10, 20, 30, 40, 50}
sample_dict = {1: 'a', 2: 'b', 3: 'c'}
Example Output:
Random element from list: 3
Random element from set: 20
Random value from dictionary: b
Random file from directory: test.txt
Python Program:
def is_palindrome(s):
s = s.lower()
return s == s[::-1]
Example Output:
Enter a string: Madam
'Madam' is a palindrome.
***************************************************************************
10. a) Write a Python program to Find the Duplicate Element from a List.
Algorithm:
1. Start.
2. Input the list of elements.
3. Create an empty set to track seen elements.
4. Iterate through each element in the list:
If the element is in the set, it's a duplicate.
If the element is not in the set, add it to the set.
5. Print the duplicate elements.
6. End.
Python Program:
def find_duplicates(input_list):
seen = set()
duplicates = set()
for element in input_list:
if element in seen:
duplicates.add(element)
else:
seen.add(element)
return duplicates
Example Output:
Enter the elements of the list separated by spaces: 1 2 3 4 5 2 6 7 8 3
Duplicate elements: 2, 3
Python Program:
def find_two_largest(input_list):
first_largest = second_largest = float('-inf')
for element in input_list:
if element > first_largest:
second_largest = first_largest
first_largest = element
elif element > second_largest and element != first_largest:
second_largest = element
return first_largest, second_largest
Example Output:
Enter the elements of the list separated by spaces: 10 20 4 45 99 78 66
First largest element: 99
Second largest element: 78
***************************************************************************Alg
12. Code a Python Program to Find the Factorial of a Given Number Using Recursion.
Alorithm:
1. Start.
2. Define a recursive function factorial that takes one argument n.
Python Program:
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
Example Output:
Enter a number: 5
The factorial of 5 is 120
*************************************************************************
12.a) Code a Python Program to Find the Factorial of a Given Number Using Recursion.
Algorithm:
1. Start.
2. Define a recursive function factorial that takes one argument n.
Python Program:
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
Example Output:
Enter a number: 5
The factorial of 5 is 120
b) Write a Python program to find the first repeated word in a given string.
Algorithm:
1. Start.
2. Input the string.
3. Split the string into words.
4. Create an empty set to track seen words.
5. Iterate through each word in the list:
If the word is in the set, it is the first repeated word.
If the word is not in the set, add it to the set.
6. Print the first repeated word or a message indicating no repeated word is found.
7. End.
Python Program:
def find_first_repeated_word(s):
words = s.split()
seen = set()
for word in words:
if word in seen:
return word
else:
seen.add(word)
return "No repeated words found"
**************************************************************************
16. a) Write a program that Input a Text File. The program should print all of the unique
words in the file in Alphabetical order.
Algorithm:
1. Start.
2. Input the file name.
3. Open the file in read mode.
4. Read the contents of the file.
5. Split the contents into words.
6. Remove punctuation and convert words to lowercase.
7. Store the words in a set to ensure uniqueness.
8. Convert the set to a list and sort it alphabetically.
9. Print the sorted list of unique words.
10. End.
Python Program:
import string
def extract_unique_words(file_name):
with open(file_name, 'r') as file:
content = file.read().lower()
words = content.split()
table = str.maketrans('', '', string.punctuation)
stripped_words = [word.translate(table) for word in words]
unique_words = sorted(set(stripped_words))
return unique_words
Example Output:
Enter the file name: sample.txt
Unique words in alphabetical order:
a
alphabetical
file
in
order
print
the
unique
words
Python Program:
def calculate_average(a, b, c):
return (a + b + c) / 3
Example Output:
Enter the first number: 10
Enter the second number: 20
Enter the third number: 30
The average of 10.0, 20.0, and 30.0 is
**************************************************************************
17. a) Write a script named copyfile.py. This script should prompt the user for the names
of two text files. the contents of the first file should be input and written to the second file.
Algorithm:
1. Start.
2. Prompt the user for the name of the first text file.
3. Prompt the user for the name of the second text file.
4. Open the first file in read mode.
5. Read the contents of the first file.
6. Open the second file in write mode.
7. Write the contents of the first file to the second file.
8. Close both files.
9. Print a message indicating the contents have been copied.
10. End.
Python Program
# Prompt the user for the names of the two text files
source_file = input("Enter the name of the source file: ")
destination_file = input("Enter the name of the destination file: ")
# Open the source file in read mode and destination file in write mode
with open(source_file, 'r') as src:
contents = src.read()
Example Output:
Enter the name of the source file: source.txt
Enter the name of the destination file: destination.txt
Contents of 'source.txt' have been copied to 'destination.txt'
b) Develop a Python program to find the Sum of Digits in an Integer using While
Statement by getting the input from the user.
Algorithm:
1. Start.
2. Input an integer from the user.
3. Initialize a variable sum to 0.
Remove the last digit of the integer by performing integer division by 10.
5. Print the sum of the digits.
6. End.
Python Program:
def sum_of_digits(n):
sum = 0
while n > 0:
digit = n % 10
sum += digit
n = n // 10
return sum
Example Output:
Enter an integer: 12345
The sum of the digits in 12345 is 15
18. a) Develop a program for Voter’s age validity. Validate using Exceptional handling
feature in python. ( Ex: age of the voter is > 18 or not)
Algorithm:
1. Start.
2. Input the age of the voter.
3. Check if the age is 18 or older.
4. If yes, print "You are eligible to vote."
5. If no, print "You are not eligible to vote."
6. End.
Python Program:
age = int(input("Enter your age: "))
Example Output:
Enter your age: 20
You are eligible to vote.
***************************************************************************
20. a) Simulate Bouncing Ball Using Pygame
Algorithm:
1. Start.
2. Initialize Pygame.
3. Set up the display window.
4. Define ball properties (position, velocity, and radius).
5. Create a game loop:
Handle events.
Update ball position.
Check for collisions with window edges and reverse the velocity if needed.
Clear the screen.
Draw the ball.
Update the display.
6. End.
Python Program:
import pygame
import sys
# Initialize Pygame
pygame.init()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
ball_pos[0] += ball_vel[0]
ball_pos[1] += ball_vel[1]
window.fill(bg_color)
pygame.display.flip()
pygame.time.Clock().tick(60)
Example Output:
The program opens a window with a red ball bouncing around, reversing direction upon hitting
the edges of the window.
b) Write a Python program to remove Duplicates from a list
Algorithm:
1. Start.
2. Input the list of elements.
3. Convert the list to a set to remove duplicates.
4. Convert the set back to a list to maintain the list format.
5. Print the list with duplicates removed.
6. End.
Python Program:
def remove_duplicates(input_list):
return list(set(input_list))
Example Output:
Enter the elements of the list separated by spaces: 1 2 2 3 4 4 4 5
List after removing duplicates: ['1', '2', '3', '4', '5']ss