0% found this document useful (0 votes)
52 views20 pages

Python Sample 1

1st semester python practical questions

Uploaded by

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

Python Sample 1

1st semester python practical questions

Uploaded by

poketype007
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 20

PYTHON LAB-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

 For the next 200 units: rate2

 For units above 300: rate3


4. Calculate the total bill based on the units consumed.
5. Display the total electricity bill.
6. End

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

if units <= 100:


total_bill = units * rate1
elif units <= 300:
total_bill = (100 * rate1) + ((units - 100) * rate2)
else:
total_bill = (100 * rate1) + (200 * rate2) + ((units - 300) * rate3)

return total_bill

units_consumed = int(input("Enter the number of units consumed: "))

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:

 If a is greater than or equal to b, compare a with c:

 If a is greater than or equal to c, then a is the biggest number.

 Otherwise, c is the biggest number.

 Otherwise, compare b with c:

 If b is greater than or equal to c, then b is the biggest number.

 Otherwise, c is the biggest number.


4. Print the biggest number.
5. End.

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

num1 = float(input("Enter the first number: "))


num2 = float(input("Enter the second number: "))
num3 = float(input("Enter the third number: "))

biggest_number = find_biggest(num1, num2, num3)

print(f"The biggest number among {num1}, {num2}, and {num3} is:


{biggest_number}")

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.

3. Use a temporary variable temp to hold the value of a.

4. Assign the value of b to a.

5. Assign the value of temp to b.

6. Print the swapped values of 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

num1 = float(input("Enter the first number: "))


num2 = float(input("Enter the second number: "))

num1, num2 = swap_numbers(num1, num2)


print(f"After swapping:\nFirst number: {num1}\nSecond number: {num2}")

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

4. Calculate the remainder using the modulus (% operator).

5. Print the quotient and the remainder.


6. End.

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. b. Python program to swap two numbers (using two variables).


Algorithm:
1. Start.
2. Input two numbers, a and b.

3. Swap the values of a and b using arithmetic operations.

4. Print the swapped values of a and 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)

print(f"After swapping:\nFirst number: {num1}\nSecond number: {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.

3. Initialize a variable sum to 0.

4. Use a loop to iterate from 1 to n:

 Add the current number to sum.

5. Print the sum of the first n natural numbers.

6. End.

Python Program:
def sum_of_natural_numbers(n):
sum = 0
for i in range(1, n + 1):
sum += i
return sum

n = int(input("Enter the value of n: "))

total_sum = sum_of_natural_numbers(n)

print(f"The sum of the first {n} natural numbers is: {total_sum}")

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.

2. Create a list, set, and dictionary with sample data.


3. Use random.choice() to select a random element from the list.

4. Convert the set to a list and use random.choice() to select a random element.

5. Use random.choice() to select a random value from the dictionary values.

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.

2. Create a list, set, and dictionary with sample data.


3. Use random.choice() to select a random element from the list.

4. Convert the set to a list and use random.choice() to select a random element.

5. Use random.choice() to select a random value from the dictionary values.

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'}

# Select a random element from a list


random_list_element = random.choice(sample_list)

# Select a random element from a set (convert set to list first)


random_set_element = random.choice(list(sample_set))

# Select a random value from a dictionary


random_dict_value = random.choice(list(sample_dict.values()))

# Directory to select a random file from


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 the results


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

b) Develop a Python program to check if the given string is palindrome or not.


Algorithm:
1. Start.
2. Input the string.
3. Convert the string to lowercase.
4. Reverse the string.
5. Compare the original string with the reversed string.
6. If they are the same, print that the string is a palindrome.
7. If they are different, print that the string is not a palindrome.
8. End.

Python Program:
def is_palindrome(s):
s = s.lower()
return s == s[::-1]

input_string = input("Enter a string: ")


if is_palindrome(input_string):
print(f"'{input_string}' is a palindrome.")
else:
print(f"'{input_string}' is not a palindrome.")

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

input_list = input("Enter the elements of the list separated by spaces:


").split()
duplicates = find_duplicates(input_list)
if duplicates:
print(f"Duplicate elements: {', '.join(duplicates)}")
else:
print("No duplicate elements found.")

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

b) Code a Program to Python Find the 1st,2nd Largest Element in a List.


Algorithm:
1. Start.
2. Input the list of elements.
3. Initialize two variables first_largest and second_largest to hold the first and
second largest elements.
4. Iterate through each element in the list:
 If the current element is greater than first_largest, update
second_largest to first_largest and then update first_largest
to the current element.
 Else if the current element is greater than second_largest and not equal to
first_largest, update second_largest to the current element.

5. Print the first and second largest elements.


6. End.

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

input_list = list(map(int, input("Enter the elements of the list separated by


spaces: ").split()))
first_largest, second_largest = find_two_largest(input_list)

print(f"First largest element: {first_largest}")


print(f"Second largest element: {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.

3. If n is 0 or 1, return 1 (base case).

4. Otherwise, return n multiplied by factorial(n-1) (recursive case).

5. Input the number for which the factorial is to be calculated.


6. Call the factorial function with the input number.
7. Print the result.
8. End.

Python Program:
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)

number = int(input("Enter a number: "))


result = factorial(number)
print(f"The factorial of {number} is {result}")

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.

3. If n is 0 or 1, return 1 (base case).

4. Otherwise, return n multiplied by factorial(n-1) (recursive case).

5. Input the number for which the factorial is to be calculated.


6. Call the factorial function with the input number.
7. Print the result.
8. End.

Python Program:
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)

number = int(input("Enter a number: "))


result = factorial(number)
print(f"The factorial of {number} is {result}")

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"

input_string = input("Enter a string: ")


first_repeated = find_first_repeated_word(input_string)
print(f"The first repeated word is: {first_repeated}")
Example Output:
Enter a string: this is a test this is only a test
The first repeated word is: this

**************************************************************************

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

file_name = input("Enter the file name: ")


unique_words = extract_unique_words(file_name)

print("Unique words in alphabetical order:")


for word in unique_words:
print(word)

Example Output:
Enter the file name: sample.txt
Unique words in alphabetical order:
a
alphabetical
file
in
order
print
the
unique
words

b) Develop a Python program to find the average of Three Numbers.


Algorithm:
1. Start.
2. Input three numbers.
3. Calculate the sum of the three numbers.
4. Divide the sum by 3 to find the average.
5. Print the average.
6. End.

Python Program:
def calculate_average(a, b, c):
return (a + b + c) / 3

num1 = float(input("Enter the first number: "))


num2 = float(input("Enter the second number: "))
num3 = float(input("Enter the third number: "))

average = calculate_average(num1, num2, num3)


print(f"The average of {num1}, {num2}, and {num3} is {average:.2f}")

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

with open(destination_file, 'w') as dest:


dest.write(contents)

print(f"Contents of '{source_file}' have been copied to '{destination_file}'")

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.

4. Use a while loop to iterate as long as the integer is greater than 0:


 Extract the last digit of the integer using the modulus operator.
 Add the digit to sum.

 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

number = int(input("Enter an integer: "))


result = sum_of_digits(number)
print(f"The sum of the digits in {number} is {result}")

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: "))

if age >= 18:


print("You are eligible to vote.")
else:
print("You are not eligible to vote.")

Example Output:
Enter your age: 20
You are eligible to vote.

Enter your age: 16


You are not eligible to vote.

b) Write a Python program to convert a tuple to a string.


Algorithm
1. Input a tuple: Start with a tuple containing elements.
2. Convert each element to a string: Use the str() function or other formatting
techniques to ensure all elements of the tuple are strings.
3. Join elements: Use a string method, such as join(), to concatenate the elements into a
single string.
4. Output the result: Print or return the resulting string.
Python Program
# Function to convert a tuple to a stringdef tuple_to_string(input_tuple):
# Convert tuple elements to a single string
result = ''.join(map(str, input_tuple))
return result
# Example usage
my_tuple = ('H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd')
converted_string = tuple_to_string(my_tuple)
# Print the resultprint("Converted String:", converted_string)
Example Input and Output
Input:
python
Copy code
my_tuple = ('H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd')
Output:
Converted String: Hello World
Algorithm
1. Input a tuple: Start with a tuple containing elements.
2. Convert each element to a string: Use the str() function or other formatting
techniques to ensure all elements of the tuple are strings.
3. Join elements: Use a string method, such as join(), to concatenate the elements into a
single string.
4. Output the result: Print or return the resulting string.
Python Program
# Function to convert a tuple to a stringdef tuple_to_string(input_tuple):
# Convert tuple elements to a single string
result = ''.join(map(str, input_tuple))
return result
# Example usage
my_tuple = ('H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd')
converted_string = tuple_to_string(my_tuple)
# Print the resultprint("Converted String:", converted_string)
Example Input and Output
Input:
my_tuple = ('H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd')
Output:
Converted String: Hello World

***************************************************************************
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()

# Set up the display window


width, height = 800, 600
window = pygame.display.set_mode((width, height))
pygame.display.set_caption("Bouncing Ball Simulation")

# Define ball properties


ball_pos = [width // 2, height // 2]
ball_vel = [5, 5]
ball_radius = 20
ball_color = (255, 0, 0)
bg_color = (0, 0, 0)

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]

# Check for collisions with window edges


if ball_pos[0] <= ball_radius or ball_pos[0] >= width - ball_radius:
ball_vel[0] = -ball_vel[0]
if ball_pos[1] <= ball_radius or ball_pos[1] >= height - ball_radius:
ball_vel[1] = -ball_vel[1]

window.fill(bg_color)

pygame.draw.circle(window, ball_color, ball_pos, ball_radius)

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

input_list = input("Enter the elements of the list separated by spaces:


").split()
unique_list = remove_duplicates(input_list)
print(f"List after removing duplicates: {unique_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

You might also like