Python Question & Answers - May-2024 Question Paper
Python Question & Answers - May-2024 Question Paper
Here is a simple algorithm (in Python) that finds all numbers between 2000 and 3000 that are divisible
by 7 but not a multiple of 5:
python
CopyEdit
# Initialize an empty list to hold the results
results = []
Explanation:
ChatGPT said:
Question: 2 (MAY-24)
Here's a simple Python program to read a number from the user and display its factorial:
python
CopyEdit
# Read input from the user
num = int(input("Enter a number: "))
# Calculate factorial
if num < 0:
print("Factorial does not exist for negative numbers.")
elif num == 0:
print("The factorial of 0 is 1.")
else:
for i in range(1, num + 1):
factorial *= i
print(f"The factorial of {num} is {factorial}.")
This program handles input, calculates the factorial using a loop, and provides appropriate messages
for negative inputs and zero.
Question : 3
construct a program to read a string untill a is encountered. also count the number of uppercase
characters,lower case characters and digits in the given string using branching statement.
Here is a program that reads a string until the character 'a' is encountered, and counts the number of
uppercase characters, lowercase characters, and digits in the string using branching statements.
Python
def analyze_string():
input_string = ""
while True:
char = input("Enter a character (enter 'a' to stop): ")
if char == 'a':
break
input_string += char
uppercase_count = 0
lowercase_count = 0
digit_count = 0
analyze_string()
Question : 4
A store charges ₹120 per item if you buy less than 10 items. If you buy between 10 and 99 items, the
cost is ₹100 per item. If you buy 100 or more items, the cost is ₹70 per item. Write a program that asks
the user how many items they are buying and prints the total cost.
Answer
if n >= 100 :
cost = n * 70
elif n >= 10 :
cost = n * 100
else :
cost = n * 120
Output
Question : 5
Write a program that uses a for loop to print the following series: 100,98,96,....4.
To print the series 100, 98, 96, ..., down to 4 using a for loop in Python, you can utilize the range()
function with a negative step value. Here's how you can do it:
python
CopyEdit
for i in range(100, 3, -2):
print(i)
Explanation:
range(start, stop, step) generates a sequence starting from start (inclusive) to stop (exclusive),
incrementing or decrementing by step.
In this case, start is 100, stop is 3, and step is -2, which means the loop will decrement by 2 each time,
stopping before it reaches 3.Numerade
Output:
CopyEdit
100
98
96
94
92
90
88
86
84
82
80
78
76
74
72
70
68
66
64
62
60
58
56
54
52
50
48
46
44
42
40
38
36
34
32
30
28
26
24
22
20
18
16
14
12
10
8
6
4
This approach effectively prints all even numbers from 100 down to 4.
Question : 6
Composing a program that uses variable length arguments to add the values passed to the function
Here is a program that uses variable-length arguments to add the values passed to the
function.
Python
def add_values(*args):
"""
This function takes a variable number of arguments and returns their
sum.
"""
total = 0
for num in args:
total += num
return total
# Example usage
sum_of_numbers = add_values(1, 2, 3, 4, 5)
print(f"The sum of the numbers is: {sum_of_numbers}")
sum_of_two_numbers = add_values(10,20)
print(f"The sum of the numbers is: {sum_of_two_numbers}")
sum_of_no_numbers = add_values()
print(f"The sum of the numbers is: {sum_of_no_numbers}")
The add_values function is defined to accept a variable number of arguments using
the *args syntax. Inside the function, a variable total is initialized to 0. The code iterates through
each num in args, adding it to total. Finally, the function returns the calculated total. The example
demonstrates how to call the function with different numbers of arguments and prints the result.
Question : 7
Write a program that accepts string from user and redisplays the same string after removing vowels
from it.
Python
def remove_vowels(text):
vowels = "aeiouAEIOU"
result = ""
for char in text:
if char not in vowels:
result += char
return result
# Remove vowels
modified_string = remove_vowels(user_input)
Python
def modify_string():
"""
Asks the user for a string, modifies it by changing the second character
to an asterisk and adding three exclamation points, and then prints the
modified string.
"""
user_string = input("Enter your string: ")
2. String Modification:
The code checks if the input string has at least two characters.
Example:
If the user enters "Qbert", the program will output "Q*ert!!!".
Question : 9
Write a program using function to calculate simple interest. if the customer is a senior citizen (age
greater than 60) then he is being offered 12 percent rate of interest ; for all other customers , the rate
of interest is 10 percent.
python
CopyEdit
def calculate_simple_interest(principal, rate, time):
"""
Calculate simple interest using the formula:
SI = (Principal * Rate * Time) / 100
"""
return (principal * rate * time) / 100
def main():
try:
# Input from the user
principal = float(input("Enter the principal amount (₹): "))
age = int(input("Enter the customer's age: "))
time = float(input("Enter the time period in years: "))
if __name__ == "__main__":
main()
🔍 How It Works
Interest Rate Determination: The program checks the customer's age. If the age is greater than 60, it
assigns a 12% interest rate; otherwise, it assigns a 10% rate.
User Interaction: The program prompts the user to enter the principal amount, age, and time period.
It then calculates and displays the simple interest and the total amount payable.
📌 Example Output
yaml
CopyEdit
Enter the principal amount (₹): 10000
Enter the customer's age: 65
Enter the time period in years: 2
Senior Citizen: Eligible for 12% interest rate.
In this example, a senior citizen aged 65 depositing ₹10,000 for 2 years earns ₹2,400 in interest at a
rate of 12%.
Question : 10
build a program that generates a list of 20 random numbers between 1 and 100. (i) print the average
of the elements in the list. (ii) print the largest and smallest value in the list.(iii) print the second
largest and second smallest entries in the list.(iv) print how many even numbers are in the list.
Python Program
python
CopyEdit
import random
# Generate a list of 20 random integers between 1 and 100
numbers = [random.randint(1, 100) for _ in range(20)]
# (iii) Find and print the second largest and second smallest values
sorted_numbers = sorted(numbers)
second_smallest = sorted_numbers[1]
second_largest = sorted_numbers[-2]
print("Second Smallest Value:", second_smallest)
print("Second Largest Value:", second_largest)
🔍 Explanation
Random Number Generation: The random.randint(1, 100) function generates a random integer
between 1 and 100. Using a list comprehension, we create a list of 20 such numbers.
Average Calculation: The average is computed by dividing the sum of the list by its length.
Finding Extremes: The max() and min() functions identify the largest and smallest values in the list,
respectively.
Second Extremes: By sorting the list, the second smallest and second largest values are located at
positions 1 and -2, respectively.
Even Number Count: A generator expression iterates through the list, incrementing a count for each
even number found.
Question : 11
Construct a program that has a list of numbers (both positives as well as negative).make a new tuple
that has only positive values from the list.
Python
def get_positive_tuple(number_list):
"""
Creates a new tuple containing only the positive numbers from a given list.
Args:
number_list: A list of numbers (positive and negative).
Returns:
A tuple containing only the positive numbers from the input list.
"""
positive_numbers = tuple(num for num in number_list if num > 0)
return positive_numbers
# Example usage:
number_list = [1, -2, 3, -4, 5, 0, -6, 7]
positive_tuple = get_positive_tuple(number_list)
print(positive_tuple) # Output: (1, 3, 5, 7)
Question : 12
Develop a python program that has two sequences.first sequence stores some questions and the
second stores the corresponding answers. use the zip () function to form a valid question answer
serires.
Python Program: Question-Answer Pairing Using zip()
python
CopyEdit
# Define a list of questions
questions = [
"What is the capital of France?",
"What is the largest planet in our solar system?",
"Who wrote 'Romeo and Juliet'?",
"What is the boiling point of water in Celsius?",
"Who painted the Mona Lisa?"
]
Python
def find_topper():
"""
This function takes a dictionary of student names and their marks in 4
courses,
creates a new dictionary with total marks, and identifies the topper.
"""
Question : 14
Describe the different file operations in python with examples
Python provides a comprehensive set of functions to perform various file operations such as creating,
reading, writing, appending, and deleting files. Below is an overview of these operations with
examples:
📂 1. Opening a File
To work with a file, you first need to open it using the open() function, which returns a file
object.Programiz+4learnbyexample.org+4Spark By {Examples}+4
python
CopyEdit
file = open("example.txt", "r") # Opens the file in read mode
python
CopyEdit
with open("example.txt", "r") as file:
data = file.read()
print(data)
After opening a file in read mode, you can read its contents using various methods:Real
Python+5w3resource+5HostingSeekers+5
python
CopyEdit
with open("example.txt", "r") as file:
content = file.read()
print(content)
python
CopyEdit
with open("example.txt", "r") as file:
line = file.readline()
print(line)
python
CopyEdit
with open("example.txt", "r") as file:
lines = file.readlines()
print(lines)
python
CopyEdit
with open("example.txt", "w") as file:
file.write("This is a new line.\n")
python
CopyEdit
with open("example.txt", "a") as file:
file.write("This line is appended.\n")
Question : 15
write a python program that handles following types of exception:
ZeroDivisionError,NameError,IOError.
python
CopyEdit
# Handling ZeroDivisionError
try:
numerator = 10
denominator = 0
result = numerator / denominator
print(f"Result: {result}")
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
# Handling NameError
try:
print(value) # 'value' is not defined
except NameError:
print("Error: 'value' is not defined.")
# Handling IOError
try:
with open("non_existent_file.txt", "r") as file:
content = file.read()
print(content)
except IOError:
print("Error: File not found or cannot be opened.")
Question : 16
llustrate various modes of opening files with suitable examples (python)
In Python, the open() function is used to open files, and the mode parameter determines how the file
will be opened. Below is a comprehensive guide to various file opening modes in Python, along with
examples:
Descriptio
Mode
n
'r' Read (default): Opens a file for reading. Raises an error if the file does not exist.
'w' Write: Opens a file for writing. Creates a new file if it does not exist or truncates the file if
it exists.
'a' Append: Opens a file for appending. Creates a new file if it does not exist.
'x' Exclusive creation: Creates a new file. Raises an error if the file already exists.
'b' Binary: Opens a file in binary mode.
't' Text: Opens a file in text mode (default).
'+' Read and Write: Opens a file for updating (reading and writing).
These modes can be combined, such as 'rb' for reading a binary file or 'w+' for writing and reading a file.
python
CopyEdit
with open('example.txt', 'r') as file:
content = file.read()
print(content)
python
CopyEdit
with open('example.txt', 'w') as file:
file.write('Hello, World!')
Opens a file for appending. Creates a new file if it does not exist.GeeksforGeeks+1Tutorial+1
python
CopyEdit
with open('example.txt', 'a') as file:
file.write('\nThis is an appended line.')
python
CopyEdit
try:
with open('example.txt', 'x') as file:
file.write('This file is newly created.')
except FileExistsError:
print('File already exists.')
5. Read and Write Mode ('r+')
Opens a file for both reading and writing. The file must exist.llego.devGeeksforGeeks
python
CopyEdit
with open('example.txt', 'r+') as file:
content = file.read()
file.write('\nAdding a new line.')
python
CopyEdit
with open('example.txt', 'w+') as file:
file.write('Writing and reading.')
file.seek(0)
print(file.read())
python
CopyEdit
with open('example.txt', 'a+') as file:
file.write('\nAppending and reading.')
file.seek(0)
print(file.read())
python
CopyEdit
with open('example.bin', 'rb') as file:
content = file.read()
print(content)
Opens a file for writing in binary mode. Creates a new file if it does not exist or truncates the file if it
exists.
python
CopyEdit
with open('example.bin', 'wb') as file:
file.write(b'Binary data')
Opens a file for appending in binary mode. Creates a new file if it does not exist.
python
CopyEdit
with open('example.bin', 'ab') as file:
file.write(b'\nMore binary data')
Question : 17
Build a python program to calculate the number of lines , number of words and number of characters
in a file.
python
CopyEdit
def count_file_stats(filename):
try:
with open(filename, 'r', encoding='utf-8') as file:
lines = file.readlines()
num_lines = len(lines)
num_words = sum(len(line.split()) for line in lines)
num_chars = sum(len(line) for line in lines)
print(f"Lines: {num_lines}")
print(f"Words: {num_words}")
print(f"Characters: {num_chars}")
except FileNotFoundError:
print(f"Error: The file '{filename}' was not found.")
except Exception as e:
print(f"An error occurred: {e}")
# Example usage:
filename = 'example.txt' # Replace with your file path
count_file_stats(filename)
✅ Sample Output
kotlin
CopyEdit
Hello, this is a sample text file.
It contains multiple lines.
Counting vowels, lines, and characters.
The output will be:
makefile
CopyEdit
Lines: 3
Words: 13
Characters: 101