Python Question Bank
Python Question Bank
QUESTION BANK
1. Create a Python module named calculator.py that includes the following functions:
add(a, b) - Returns the sum of a and b.
subtract(a, b) - Returns the difference between a and b.
Write a script that imports this module and demonstrates the use of these functions with
sample inputs.
Create a Python package named math_operations with the following structure:
math_operations/
__init__.py
basic.py
advanced.py
Inside the package:
In basic.py, define a function that returns the product of a and b.
In advanced.py, define a function that returns base raised to the power of the exponent.
Write a script that imports and uses these functions from the math_operations package.
2. 1. Create a list with the elements 12, 45, 78, and 23.
2. Insert the number 30 at the second position and the number 10 at the first position in
the list.
3. Delete the last element of the list.
4. Reverse the list and display the result.
5. Find and print the maximum and minimum values in the list.
6. Sort the list in ascending order and display the result.
7. Create a list with the elements 'apple', 'banana', 'cherry', and 'date'. Append 'elderberry'
to the end of the list.
8. Remove 'banana' from the list and display the updated list.
9. Find the index of the element 'cherry' in the list.
10. Create a list with the numbers 5, 10, 15, 20, and 25. Extend the list with 30, 35, 40
and display the result.
3. Write a Python program that creates a dictionary to store fruit details (fruit name,
color, taste, and price per kg) and demonstrates the following operations:
1. Iterate through the values of the dictionary.
2. Iterate through the keys of the dictionary.
3. Convert two lists into a dictionary.
4. Create a dictionary where each key has a list of associated values.
5. Write a Python program that computes and prints the square root of 81.
6. Create a Python program to calculate and print the factorial of 7.
7. Write a Python program that calculates and prints the sine of 30 degrees
8. Write a Python program to raise 5 to the power of 4 and print the result.
9. Create a Python program that computes and prints the logarithm of 1000 to base
10.
10. Write a Python program that checks if a string ends with the specified substring
"ed" and returns True if it does.
4. 1. Create a dictionary with 'name', 'age', and city. Print the value of 'city'.
2. Add an 'email' key to the dictionary. Print the updated dictionary.
3. Update the 'age' in 'name': Anjali, 'age': 30 to 31. Print the updated dictionary.
4. Remove the 'city' key from 'name': 'Charlie', 'age': 35, 'city': 'Los Angeles'. Print the
result.
5. Check if 'name' exists in 'name': Asha, 'age': 40'. Print True or False.
6. Print all keys from the dictionary 'name': 'Ella', 'age': 22, 'city': 'San Francisco'.
7. Print all values from 'name': 'Frank', 'age': 27, 'email': '[email protected]'.
8. Print each key-value pair from 'name': 'Grace', 'age': 29, 'city': 'Seattle'} as "Key:
[key], Value: [value]".
9. Create and print a nested dictionary with keys 'person1' and 'person2', each containing
'name' and 'age'.
10. Convert 'name': 'Hannah', 'age': 33 to a list of tuples and print it.
5. Create a dictionary to store details about various vehicles. Each entry should include: Model,
Manufacturer, Year, Price
● Iterate through and print all the values.
● Iterate through and print all the keys.
● Convert two lists into a dictionary. Use one list for keys and another list for
corresponding values.
● Create a dictionary where each key is a manufacturer and the value is a list of vehicle
models from that manufacturer.
Write a Python program to:
1. Compute and print the fourth root of 16.
2. Calculate and print the factorial of 6.
3. Compute and print the tangent of 30 degrees.
4. Raise 7 to the power of 3 and print the result.
5. Compute and print the base-2 logarithm of 32.
6. Write a Python program to check if the string "exemplary" ends with the substring
"ary" and return True if it does.
6. 1. Create a set `setA` with `7`, `8`, `9`, `10`, and `11`. Print it.
2. Add `12` to `setA` which has `7`, `8`, `9`, `10`, and `11`. Print the updated set.
3. Remove `9` from `setA` containing `7`, `8`, `9`, `10`, and `11`. Print the result.
4. Find the difference between `setA` with `7`, `8`, `9` and `setB` with `9`, `10`, `11`.
Print it.
5. Calculate the symmetric difference between `setA` with `7`, `8`, `9` and `setB` with
`9`, `10`, `11`. Print it.
6. Find the intersection of `setA` with `7`, `8`, `9` and `setB` with `9`, `10`, `11`. Print
the common elements.
7. Get the union of `setA` with `7`, `8`, `9` and `setB` with `9`, `10`, `11`. Print the
combined set.
8. Determine the length of `setA` with `7`, `8`, `9`, and `10`. Print the number of
elements.
9. Remove `10` from `setA` using `discard()`. Print the resulting set.
10. Clear all elements from `setA` which has `7`, `8`, `9`, and `10`. Print the empty set.
7. 1. Create a list called fruits with 'apple', 'banana', and 'cherry'. Print the list.
2. In the list fruits with 'apple', 'banana', and 'cherry', insert 'kiwi' at index 1. Print the
list.
3. Remove the last item from the list fruits, which has 'apple', 'banana', 'cherry', and
'date'. Show the result.
4. Sort the list fruits with 'banana', 'apple', and 'cherry' in reverse alphabetical order. Print
the result.
5. Find the index of 'cherry' in the list fruits with 'apple', 'banana', and 'cherry'. Print the
index.
6. Count how many times 'apple' appears in fruits, which has 'apple', 'banana', 'apple',
'cherry', and 'apple'. Print the count.
7. Remove the first 'banana' from fruits, which includes 'apple', 'banana', 'cherry', and
'banana'. Print the list.
8. Create a list fruits with 'apple', 'banana', and 'cherry'. Clear the list. Print the empty
list.
9. Copy the list fruits with 'apple', 'banana', and 'cherry'. Print the copy.
10. Remove the item located at the third position from the list fruits, which has 'apple',
'banana', 'cherry', and 'date'. Print both the removed item and the updated list.
8.
9.
10.
14. Write a Python program that demonstrates simple inheritance. Create a base class Animal with
a method sound() that prints "Animal sound". Derive a class Dog from Animal that overrides
the sound() method to print "Bark".
Write a Python program that demonstrates multilevel inheritance. Create a base class Animal
with a method eat() that prints "Eating". Derive a class Mammal from Animal, and from
Mammal, derive a class Dog. The Dog class should have a method bark() that prints "Bark".
Write a Python program that demonstrates multiple inheritance. Create two classes: Bird with
a method fly() that prints "Flying", and Fish with a method swim() that prints "Swimming".
Create a third class Penguin that inherits from both Bird and Fish, and call both the fly() and
swim() methods.
Write a Python program that demonstrates hierarchical inheritance. Create a base class Vehicle
with a method start() that prints "Vehicle is starting". Derive two classes Car and Bike from
Vehicle. In the Car class, override the start() method to print "Car is starting", and in the Bike
class, override the start() method to print "Bike is starting". Create objects of both Car and
Bike classes and call their start() methods.
Question: Write a Python program that demonstrates method overloading. Create a class
Calculator with a method add() that can add either two or three numbers. If two arguments are
passed, the method should return their sum, and if three arguments are passed, it should return
the sum of all three. Call the add() method with both two and three arguments and display the
results.
Hint: Use default arguments or variable-length arguments to achieve method overloading, as
Python does not support it directly.
15. Write a Python program that defines a class called Car. Use a default constructor to initialize
the attributes make and model to "Toyota" and "Corolla", respectively. Create an object of the
Car class and print the values of the make and model attributes.
16. Create a class named Book with a parameterized constructor that initializes the attributes title
and author. Write a method called get_details() that returns a string with the book's title and
author. Instantiate the class with your favorite book's details and print the result of the
get_details() method.
17. Define a class called Rectangle that has two constructors: a default constructor that initializes
the width and height to 1, and a parameterized constructor that allows setting the width and
height to custom values. Implement a method called area() that returns the area of the rectangle.
Create instances of Rectangle using both constructors and print their areas.
18. Write a Python program that defines a class called Dog. The class should have:
19. Write a Python program that defines a class called Book. The class should have:
Attributes title and author, initialized through the constructor.
A method called get_summary() that returns a string in the format: "Title: {title}, Author:
{author}".
Create an instance of the Book class with a title and an author of your choice, and call the
get_summary() method. Print the result.
20. Write a Python program that does the following:
Reads the contents of a text file named example.txt.
Appends a new line to the file with the text "This is a new line.".
Closes the file and reopens it to print the updated contents.
21. Write a Python program that uses the with statement to open a text file sample.txt for reading.
It should print each line of the file to the console. Ensure the file is automatically closed after
reading.
22. Write a Python program that opens a text file seek_example.txt, moves the file pointer to the
5th character using seek(), and prints the character at that position. Use tell() to print the current
position of the file pointer after seeking.
23. Write a Python program that zips three files (file1.txt, file2.txt, and file3.txt) into a single zip
file named archive.zip. Then, write code to unzip the archive.zip file and extract the contents
to a directory called unzipped_files.
24. Write a Python program that reads the contents of an image file source_image.png in binary
mode and copies the data into another file copy_image.png. Ensure both files are identical after
the copy operation.
25. Write a Python program that performs the following tasks using the os module:
Get the current working directory and print it.
Create a subdirectory named mysub.
Create a subdirectory within mysub named mysub2.
Change the working directory to mysub/mysub2 and print the current working directory.
(Optional) Implement code to remove the mysub2 directory and then remove the mysub
directory.
(Optional) Implement code to rename the mysub directory to my_new_sub.
Requirements:
Ensure that the program checks for the existence of directories before creating or removing
them to avoid errors.
Use appropriate error handling (try-except blocks) to manage potential exceptions, such as
attempting to remove non-empty directories.
Example Output:
Original content: Hello, World!
Modified content: Hi, World!
Slicing Arrays
Given the array arr = np.array([1, 2, 3, 4, 5, 6, 7, 8]), write a code snippet to slice and print the
elements from index 2 to index 5 (inclusive).
2D Array Indexing
Create a 2D NumPy array as follows:
[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
Access and print the element at the first row and second column.
Creating Zeros and Ones Arrays
Write a program that creates a 3x4 array of zeros and a 2x3 array of ones, then print both
arrays.
Mathematical Operations
Create two 1D NumPy arrays: a = np.array([1, 2, 3]) and b = np.array([4, 5, 6]). Perform and
print the results of the following operations:
Element-wise addition
Element-wise multiplication
Element-wise subtraction
Comparing Arrays
Given two arrays: arr1 = np.array([10, 20, 30]) and arr2 = np.array([15, 20, 25]), write code to
compare the arrays element-wise to check which elements in arr1 are greater than the
corresponding elements in arr2. Print the boolean result.
Reshaping an Array
Create a 1D array with the elements np.array([1, 2, 3, 4, 5, 6]) and reshape it into a 2D array
with 2 rows and 3 columns. Print the reshaped array.
Flattening a Matrix
Given the 2D array matrix = np.array([[1, 2], [3, 4], [5, 6]]), write a code to flatten the matrix
into a 1D array and print the result.
Matrix Operations
Create two 2x2 matrices:
Matrix addition
Matrix multiplication (dot product)