0% found this document useful (0 votes)
2 views

Python Question Bank

The document is a question bank for a Python Programming Laboratory course, detailing various programming tasks and exercises. It covers topics such as creating modules, lists, dictionaries, sets, and classes, as well as implementing basic arithmetic operations and demonstrating inheritance. Each section provides specific instructions for coding exercises aimed at enhancing Python programming skills.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Python Question Bank

The document is a question bank for a Python Programming Laboratory course, detailing various programming tasks and exercises. It covers topics such as creating modules, lists, dictionaries, sets, and classes, as well as implementing basic arithmetic operations and demonstrating inheritance. Each section provides specific instructions for coding exercises aimed at enhancing Python programming skills.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Faculty of Engineering and Technology

B.Tech (CS & E) Programme


Semester V

Subject: Python Programming Laboratory (2601505)

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.

11. Write a Python program that performs the following tasks:


● Create a function named divide_numbers(a, b) that takes two arguments and returns the result
of dividing a by b.
● Demonstrate a compile-time error by writing code that has a syntax error.
● Demonstrate a runtime error by calling the divide_numbers function with b as 0, and explain
why this causes an error.
● Implement a try block to catch the runtime error and handle it using an except block.
● Use a try-except block to catch a ZeroDivisionError specifically, and print a custom message
when this error occurs.
● Extend the try-except block to include an else block that prints a success message when no
error occurs.
● Finally, add a finally block that prints a message indicating that the error handling is
complete, regardless of whether an error occurred.
12. ● Write a Python program to perform basic arithmetic operations (addition, subtraction,
multiplication, division).
● Write a Python program to calculate and print the area of a triangle given its base and
height.
● Write a Python program to solve a quadratic equation and find its roots.
● Write a Python program to swap the values of two variables.
● Write a Python program to generate and print a random number within a given range.
● Write a Python program to convert a distance from kilometers to miles.
● Write a Python program to convert a temperature from Celsius to Fahrenheit.
● Write a Python program to display the current month's calendar.
● Write a Python program to determine if a number is positive, negative, or zero.
● Write a Python program to check if a number is odd or even.
● Write a Python program to determine if a year is a leap year.
● Write a Python program to check if a number is a prime number.
● Write a Python program to print all prime numbers within a given interval.
● Write a Python program to find and print the factorial of a given number.
● Write a Python program to display the multiplication table for a given number.
● Write a Python program to generate and print the Fibonacci sequence up to a given
number of terms.
● Write a Python program to check if a number is an Armstrong number.
● Write a Python program to find and print all Armstrong numbers within a given
interval.
● Write a Python program to find and print the sum of the first ten natural numbers.
● Write a Python program to reverse and print a given string.
● Write a Python program to calculate and print the sum of the first ten natural numbers.

13. ● Write a Python program to create a string and print it.


● Given the string "GLS FET B.Tech-(CS&E)", write a Python program to print the first 3
characters and the last 3 characters using indexing and slicing.
● Write a Python program to repeat the string "GLS" 5 times and print the result.
● Write a Python program to check if the substring "B.Tech" is present in the string "GLS
FET B.Tech-(CS&E)".
● Write a Python program to compare two strings "GLS" and "gls" and print whether they
are equal or not.
● Write a Python program to remove all spaces from the string "GLS FET B.Tech-(CS&E)".
● Write a Python program to find and count the occurrences of the substring "CS" in the
string "GLS FET B.Tech-(CS&E)".
● Write a Python program to demonstrate the immutability of strings by trying to change
the first character of the string "GLS".
● Write a Python program to replace the substring "B.Tech" with "M.Tech" in the string
"GLS FET B.Tech-(CS&E)".
● Write a Python program to split the string "GLS-FET-B.Tech-(CS&E)" into a list of words
and then join them back with spaces.
● Write a Python program to convert the string "gls fet b.tech-(cs&e)" to uppercase.
● Write a Python program to check if the string "GLS FET B.Tech-(CS&E)" starts with
"GLS" and ends with "(CS&E)".
● Write a Python program to check if the string "GLS123" is alphanumeric.
● Write a Python program to format the string "GLS" and "CS&E" into the format "Welcome
to GLS FET, Department of CS&E" using the format() method.
● Write a Python program to iterate over each character in the string "GLS FET" and print
them one by one.
● Write a Python program to sort the characters of the string "CS&E" in alphabetical order.
● Write a Python program to search for the substring "Tech" in the string "GLS FET
B.Tech-(CS&E)" and print its position.
● Write a Python program to count the number of characters and words in the string "GLS
FET B.Tech-(CS&E)".
● Write a Python program to insert the substring "-Computer Science" into the string "GLS
FET B.Tech-(CS&E)" after "B.Tech".

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:

An attribute name initialized through the constructor.


A method called bark() that returns a string saying "Woof! My name is {name}.".
Create an instance of the Dog class with a name of your choice and call the bark() method.
Print the result.

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.

26. Write a Python program that uses mmap() to:


Open a large binary file named largefile.bin.
Randomly access and print a portion of its data without loading the entire file into memory.
27. Write a Python program that:
Opens a text file named data.txt and moves the file pointer to the 50th byte using seek().
Reads and prints the next 20 characters.
Prints the current position of the file pointer using tell().
28. Write a Python program that demonstrates the use of the mmap module to modify a text file.
Your program should:
Create a text file named example.txt and write the string "Hello, World!" into it.
Use the mmap module to open the file in read/write binary mode.
Memory-map the entire file and modify the first two characters to "Hi".
Print the modified contents of the file to verify that the changes have been made.
Clean up by closing the memory map and the file properly.
Requirements:
Ensure that you handle file creation and opening with appropriate error handling.
After modification, read the content of the file to confirm that the changes were successfully
saved.

Example Output:
Original content: Hello, World!
Modified content: Hi, World!

29. Array Creation and Element Access


Create a NumPy array with the elements [10, 20, 30, 40, 50]. Access and print the second and
fourth elements of the array.

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:

matrix1 = np.array([[1, 2],


[3, 4]])
matrix2 = np.array([[5, 6],
[7, 8]])
Perform and print the results of:

Matrix addition
Matrix multiplication (dot product)

Using Linspace and Logspace


Write a code snippet to create an array of 5 evenly spaced numbers between 0 and 1 using
linspace, and another array of 5 logarithmically spaced numbers from 10^1 to 10^3 using
logspace. Print both arrays.

You might also like