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

Python Question & Answers - May-2024 Question Paper

The document contains a series of Python programming tasks and solutions, including algorithms for finding numbers divisible by 7, calculating factorials, analyzing strings, computing simple interest, and generating random numbers. Each task is accompanied by code snippets and explanations of how the programs work. The document serves as a comprehensive guide for learning basic Python programming concepts and techniques.

Uploaded by

Ayyanar Manickam
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 views18 pages

Python Question & Answers - May-2024 Question Paper

The document contains a series of Python programming tasks and solutions, including algorithms for finding numbers divisible by 7, calculating factorials, analyzing strings, computing simple interest, and generating random numbers. Each task is accompanied by code snippets and explanations of how the programs work. The document serves as a comprehensive guide for learning basic Python programming concepts and techniques.

Uploaded by

Ayyanar Manickam
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
You are on page 1/ 18

Question: 1 (MAY-24)

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 = []

# Iterate through the range 2000 to 3000 (inclusive)


for number in range(2000, 3001):
if number % 7 == 0 and number % 5 != 0:
results.append(number)

# Output the result


print(results)

Explanation:

number % 7 == 0 checks if the number is divisible by 7.

number % 5 != 0 ensures it is not a multiple of 5.

The range includes both 2000 and 3000.

Write a python program to read a number and display its factorial.

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

# Initialize factorial result


factorial = 1

# 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

for char in input_string:


if 'A' <= char <= 'Z':
uppercase_count += 1
elif 'a' <= char <= 'z':
lowercase_count += 1
elif '0' <= char <= '9':
digit_count += 1

print("String entered:", input_string)


print("Uppercase characters:", uppercase_count)
print("Lowercase characters:", lowercase_count)
print("Digits:", digit_count)

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

n = int(input("Enter number of items: "))


cost = 0

if n >= 100 :
cost = n * 70
elif n >= 10 :
cost = n * 100
else :
cost = n * 120

print("Total Cost =", cost)

Output

Enter number of items: 58


Total Cost = 5800

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

# Get input from the user


user_input = input("Enter a string: ")

# Remove vowels
modified_string = remove_vowels(user_input)

# Display the result


print("String after removing vowels:", modified_string)
This Python code defines a function remove_vowels that takes a string as input and returns a new
string with all vowels removed. It iterates through the input string, and if a character is not in
the vowels string, it's added to the result. The main part of the code prompts the user for input, calls
the remove_vowels function, and prints the modified string.
Question : 8
Write a program that asks the user to enter a string. The program should create a new string called
new_string from the user's string such that the second character is changed to an asterisk and three
exclamation points are attached to the end of the string.Finally,print new _string.Typical output is
shown below :Enter your string :Qbert Q*ert!!!

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

# Check if the string has at least two characters


if len(user_string) >= 2:
# Create the new string
new_string = user_string[:1] + "*" + user_string[2:] + "!!!"
print(new_string)
else:
# Handle cases where the string has fewer than two characters
print("The input string must have at least two characters.")

# Call the function to execute the program


modify_string()
Explanation:
1. Input: The program prompts the user to enter a string using input("Enter your string: ").

2. String Modification:
The code checks if the input string has at least two characters.

If the string has at least two characters:


new_string = user_string[:1] + "*" + user_string[2:] + "!!!" creates the
modified string:
user_string[:1] takes the first character of the input string.
`"*" ` adds an asterisk.
user_string[2:] takes all characters from the third character onwards (the original
second character is replaced).
"!!!" adds three exclamation points.
If the string has fewer than two characters:
An error message is printed.
3. Output: The program prints the new_string using print(new_string).
How it works:
The program utilizes string slicing and concatenation to modify the input string. String slicing allows you
to extract parts of a string based on their index, while the + operator joins strings together.

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.

ython Program: Simple Interest Calculator

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

# Determine the rate based on age


if age > 60:
rate = 12.0
print("Senior Citizen: Eligible for 12% interest rate.")
else:
rate = 10.0
print("Regular Customer: Eligible for 10% interest rate.")

# Calculate simple interest


interest = calculate_simple_interest(principal, rate, time)
total_amount = principal + interest

# Display the results


print("\n--- Account Summary ---")
print(f"Principal Amount: ₹{principal:.2f}")
print(f"Interest Rate: {rate}%")
print(f"Time Period: {time} year(s)")
print(f"Simple Interest: ₹{interest:.2f}")
print(f"Total Amount Payable: ₹{total_amount:.2f}")
except ValueError:
print("Invalid input. Please enter numeric values for principal, age, and time.")

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.

Simple Interest Calculation: Using the formula:

Simple Interest=Principal×Rate×Time100 \text{Simple Interest} = \frac{\text{Principal} \times


\text{Rate} \times \text{Time}}{100}Simple Interest=100Principal×Rate×Time​

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.

--- Account Summary ---


Principal Amount: ₹10000.00
Interest Rate: 12.0%
Time Period: 2.0 year(s)
Simple Interest: ₹2400.00
Total Amount Payable: ₹12400.00

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

# Print the list


print("Generated List:", numbers)

# (i) Calculate and print the average


average = sum(numbers) / len(numbers)
print("Average:", average)

# (ii) Find and print the largest and smallest values


largest = max(numbers)
smallest = min(numbers)
print("Largest Value:", largest)
print("Smallest Value:", smallest)

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

# (iv) Count and print the number of even numbers


even_count = sum(1 for num in numbers if num % 2 == 0)
print("Number of Even Numbers:", even_count)

🔍 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?"
]

# Define a list of corresponding answers


answers = [
"Paris",
"Jupiter",
"William Shakespeare",
"100",
"Leonardo da Vinci"
]

# Use zip() to pair questions with answers


qa_pairs = zip(questions, answers)

# Display the question-answer pairs


for question, answer in qa_pairs:
print(f"Q: {question}")
print(f"A: {answer}\n")
Question : 13
Write a program that has a dictionary of names of students and a list of their marks in 4 courses.
create another dictionary from this dictionary that has the name of the students and their total marks.
Find out the topper and his/her score.

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

# Sample student data (replace with your own)


student_data = {
"Alice": [85, 92, 78, 90],
"Bob": [90, 88, 95, 80],
"Charlie": [75, 82, 88, 92],
"David": [88, 94, 90, 98]
}

# Create a new dictionary to store total marks


total_marks = {}
for name, marks in student_data.items():
total_marks[name] = sum(marks)

# Find the topper and their score


topper = None
max_marks = -1
for name, total in total_marks.items():
if total > max_marks:
max_marks = total
topper = name

# Print the results


print("Student Total Marks:")
for name, total in total_marks.items():
print(f"{name}: {total}")

print(f"\nTopper: {topper} with a total score of {max_marks}")

# Run the function


find_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

Common modes include:

'r' – Read (default)

'w' – Write (creates a new file or truncates existing)

'a' – Append (adds to the end of the file)

'x' – Create (fails if file exists)

'b' – Binary mode

't' – Text mode (default)

'+' – Read and writeGeeksforGeeks+14Programiz+14Python Land+14FreeCodeCamp+3Python Land+3Programiz+3

Using the with statement is recommended as it ensures proper resource management:

python
CopyEdit
with open("example.txt", "r") as file:
data = file.read()
print(data)

📖 2. Reading from a File

After opening a file in read mode, you can read its contents using various methods:Real
Python+5w3resource+5HostingSeekers+5

read(): Reads the entire file.

python
CopyEdit
with open("example.txt", "r") as file:
content = file.read()
print(content)

readline(): Reads one line at a time.w3resource

python
CopyEdit
with open("example.txt", "r") as file:
line = file.readline()
print(line)

readlines(): Reads all lines into a list.

python
CopyEdit
with open("example.txt", "r") as file:
lines = file.readlines()
print(lines)

✍️3. Writing to a File

To write to a file, open it in write ('w') or append ('a') mode:Spark By


{Examples}+3Squash+3w3resource+3HostingSeekers

Write Mode ('w'): Overwrites existing content or creates a new file.HostingSeekers

python
CopyEdit
with open("example.txt", "w") as file:
file.write("This is a new line.\n")

Append Mode ('a'): Adds content to the end of the file.

python
CopyEdit
with open("example.txt", "a") as file:
file.write("This line is appended.\n")

write a python program that handles following types of exception:


ZeroDivisionError,NameError,IOError.

Question : 15
write a python program that handles following types of exception:
ZeroDivisionError,NameError,IOError.

1. ZeroDivisionError: Occurs when attempting to divide by zero.


2. NameError: Occurs when referencing a variable that hasn't been defined.

3. IOError: Occurs during input/output operations, such as file handling errors.

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:

📘 Common File Modes in Python

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.

🧪 Examples of File Modes

1. Read Mode ('r')

Opens a file for reading. The file must exist.GeeksforGeeks+6GeeksforGeeks+6W3Schools+6

python
CopyEdit
with open('example.txt', 'r') as file:
content = file.read()
print(content)

2. Write Mode ('w')


Opens a file for writing. Creates a new file if it does not exist or truncates the file if it exists.Spark
Tutorial Point+6llego.dev+6CodeRivers+6GeeksforGeeks+1Stack Overflow+1

python
CopyEdit
with open('example.txt', 'w') as file:
file.write('Hello, World!')

3. Append Mode ('a')

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

4. Exclusive Creation Mode ('x')


Creates a new file. Raises an error if the file already exists.Programiz+2Tutorial+2Stack Overflow+2

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

6. Write and Read Mode ('w+')


Opens a file for both writing and reading. Creates a new file if it does not exist or truncates the file if it
exists.Python Land+7llego.dev+7CodeRivers+7GeeksforGeeks+1Tutorial+1

python
CopyEdit
with open('example.txt', 'w+') as file:
file.write('Writing and reading.')
file.seek(0)
print(file.read())

7. Append and Read Mode ('a+')


Opens a file for both appending and reading. Creates a new file if it does not
exist.TutorialsPoint+1llego.dev+1

python
CopyEdit
with open('example.txt', 'a+') as file:
file.write('\nAppending and reading.')
file.seek(0)
print(file.read())

8. Binary Read Mode ('rb')

Opens a file for reading in binary mode.W3Schools

python
CopyEdit
with open('example.bin', 'rb') as file:
content = file.read()
print(content)

9. Binary Write Mode ('wb')

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

10. Binary Append Mode ('ab')

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 Program: Count Lines, Words, and 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

Assuming example.txt contains:

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

You might also like