0% found this document useful (0 votes)
11 views12 pages

Question Bank For Python

The document is a comprehensive question bank for Python covering various topics including data types, control structures, functions, and libraries like NumPy and Pandas. It contains true/false questions, code completion tasks, and programming exercises designed to test knowledge and skills in Python programming. The questions range from basic syntax to more complex concepts such as array manipulation and file I/O operations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views12 pages

Question Bank For Python

The document is a comprehensive question bank for Python covering various topics including data types, control structures, functions, and libraries like NumPy and Pandas. It contains true/false questions, code completion tasks, and programming exercises designed to test knowledge and skills in Python programming. The questions range from basic syntax to more complex concepts such as array manipulation and file I/O operations.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

Question Bank for Python

Q1A
1. True/False: Python is a statically typed language, requiring explicit
declaration of variable data types before use. (True/False)
2. True/False: Python supports dynamic typing, where variable types are
inferred at runtime without prior declaration.
3. Complete the code snippet: Fill in the blank to print "Hello, World!":
________("Hello, World!")
4. Complete the code snippet: Fill in the blank to output "Python
Programming": print(________)
5. The input() function in Python always returns a value of type ________,
which may need type casting for numerical operations.
6. The print() function outputs to the console and by default adds a
________ at the end (newline).
7. True/False: The range(1, 5) function generates numbers starting from 1
up to but not including 5. (True/False)
8. True/False: range(0, 10, 2) produces even numbers from 0 to 8
inclusive. (True/False)
9. Indentation in Python is used to define ________ blocks of code, such
as those inside if or for statements.
10. Indentation errors in Python lead to ________ exceptions during
execution (IndentationError).
11. Complete the code snippet: Fill in the blank to print "Sum: 15" for
a=10, b=5: a = 10; b = 5; print("Sum:", ___________)
12. Complete the code snippet: Fill in the blank to display "Difference: 5"
for x=15, y=10: print("Difference:", __________)
13. True/False: The == operator checks for equality between two values,
while = is used for assignment. (True/False)
14. True/False: The 'is' operator checks for object identity, while '=='
checks for value equality. (True/False)
15. The while loop continues executing as long as its ________ evaluates
to True.
16. A for loop iterates over a sequence based on its ________, not a
condition like while. (elements)
17. True/False: Variables in Python must be declared with a data type
before assignment.
18. True/False: Python variables are case-sensitive, so 'Age' and 'age' are
distinct. (True/False)
19. Complete the code snippet: Fill in the blank to print "Even" if num is
even: num = 4; if ____________: print(________)
20. Complete the code snippet: Fill in the blank to print "Odd" if num is
odd: num = 3; if num % 2 ________: print("Odd")
21. The break statement is used in loops to ________ the loop prematurely.
22. The continue statement in loops causes execution to skip to the
________ of the next iteration. (beginning)
23. True/False: f-strings in Python allow embedding expressions inside
string literals using curly braces {}
24. True/False: Format specifiers in f-strings like {value:.2f} control
decimal precision. (True/False)

Q1B
1. Predict the output of the following code and explain the relational
operators: a = 15; b = 10; print(a >= b and a != 15)
2. Predict the output of the following code and explain the logical
operators: p = True; q = False; print(p or q and not p)
3. Differentiate between for and while loops with a brief example of each
printing numbers 1 to 10.
4. Differentiate between do-while (simulated in Python) and while loops
with an example summing numbers until user stops.
5. Write a program to print the following pattern:
1
21
321
4321
54321
6. Write a program to print the following pattern:
A
BA
CBA
DCBA
7. Describe basic I/O operations. Write code to input a name and age, then
print a greeting using formatted output.
8. Describe file I/O basics (open, read, write). Write code to write "Hello"
to a file and read it back.
9. Explain the difference between arithmetic and relational operators in
Python. Provide one example for each.
10. Explain the difference between assignment and equality operators.
Provide code examples for each.
11. Write a program to print the following pattern:
1
12
123
1234
12345
12. Write a program to print the following pattern:
*
**
***
****
*****
13. Predict the output of the following code and explain the execution: age
= 20; if age >= 18: print("Adult"); else: print("Minor")
14. Predict the output of the following code and explain the execution:
mark = 75; if mark >= 90: print("A"); elif mark >= 80: print("B"); else:
print("C")
15. Describe the use of continue in a loop. Write a for loop example that
prints numbers 1 to 5, skipping 3
16. Describe the use of break in a loop. Write a while loop example that
prints numbers 1 to 10, breaking at 6.
17. List the logical operators in Python and give an example using or in a
conditional.
18. List the bitwise operators in Python and give an example using & in a
conditional.
19. Write a program to print the following pattern:
1
22
333
4444

20. Write a program to print the following pattern:


5
44
333
2222
11111

21. Predict the output of the following code and explain the logical
operator: x = 6; y = 4; print(x > 5 and y < 5)
22. Predict the output of the following code and explain the logical
operator: m = 10; n = 5; print(m < 15 or n > 10)
23. Explain type casting in Python. Write code to convert a string "42" to
an integer and add 8 to it.
24. Explain implicit vs. explicit type conversion in Python. Write code to
add int 5 and float 3.5.

Q2A
1. True/False: The reduce() function from functools combines all elements
of an iterable into a single value using a lambda.
2. True/False: The sorted() function can sort lists, tuples, and even custom
objects with a key.
3. Sets in Python are unordered collections that automatically handle
________ by not allowing duplicate elements.
4. Lists in Python maintain insertion ________, allowing reliable indexing.
(order)
5. Keyword arguments in functions allow passing values by ________,
ignoring the order of parameters.
6. Positional arguments in functions must be passed in the exact ________
order. (parameter)
7. Complete the code snippet: Fill in the blank to get the value for key
"age" or "Unknown" if not found: student = {"name": "Alex"};
print(student.________("age", "Unknown"))
8. Complete the code snippet: Fill in the blank to remove key "color" from
dict if exists: colors.pop(________, None)
9. True/False: Tuples in Python are mutable, allowing elements to be
changed after creation.
10. True/False: Lists are mutable, but strings are immutable sequences.
(True/False)
11. Complete the code snippet: Fill in the blank to add "Orange" to the end
of the list: fruits = ["apple", "banana", "cherry"];
fruits.________("Orange")
12. Complete the code snippet: Fill in the blank to remove "banana" from
the list: fruits.remove(________)
13. True/False: In a dictionary, keys must be unique, but values can be
duplicated.
14. True/False: Dictionary values can be any immutable type, but keys
must be hashable. (True/False)
15. The map() function applies a specified function to every item in an
________, returning an iterator of results.
16. The filter() function applies a test to items in an ________, returning
those that pass. (iterable)
17. True/False: Lists support indexing, allowing access to elements by
position, while sets do not.
18. True/False: Tuples support slicing like lists, returning new tuples.
(True/False)
19. Complete the code snippet: Fill in the blank to sort the list in ascending
order: numbers = [3, 1, 4, 1, 5]; numbers.________()
20. Complete the code snippet: Fill in the blank to reverse the list in place:
numbers.reverse(________) # No arg needed
21. Default arguments in functions provide a value for a parameter if none
is ________ during the function call.
22. Variable arguments using *args collect extra ________ arguments into
a tuple. (positional)
23. True/False: The items() method on a dictionary returns a view of tuples
containing key-value pairs.
24. True/False: The keys() method returns a view object that reflects
dictionary changes. (True/False)

Q2B
1. Explain the difference between lists and sets in Python, focusing on
ordering, mutability, and duplicates. Provide a code example to
demonstrate adding elements to each.
2. Explain the difference between tuples and lists in Python, focusing on
mutability and performance. Provide code to create and modify each.
3. Write a Python function calculate_discount(price, rate=10) using a
default argument to compute the discounted price. Call it with and without
the rate argument.
4. Write a Python function add_numbers(a=0, b=0) using default
arguments to return their sum. Call it with one, both, or no arguments.
5. Predict the output of the following code and explain the role of filter():
from functools import reduce; numbers = [1, 2, 3, 4, 5]; evens =
list(filter(lambda x: x % 2 == 0, numbers)); print(evens)
6. Predict the output of the following code and explain the role of map():
odds = list(map(lambda x: x**2 if x%2!=0 else x, [1,2,3,4])); print(odds)
7. Describe slicing in lists with negative indices. Write code to reverse the
list colors = ["red", "green", "blue"] using slicing.
8. Describe slicing in tuples with step values. Write code to get every
second element from nums = (1,2,3,4,5,6) starting from index 1.
9. Compare tuples and dictionaries in terms of mutability and access
methods. Write code to create a tuple of coordinates and access the second
element.
10. Compare lists and dictionaries in terms of access speed and structure.
Write code to create a list of scores and access the third, then a dict
version.
11. Write a lambda function to check if a number is even, then use it with
map() on a list [1, 2, 3, 4] to create a new list of boolean results.
12. Write a lambda function to square a number, then use it with filter() on
[1,5,2,8,3] to keep squares greater than 10.
13. Predict the output of the following code and explain the map()
function: nums = [5, 10, 15]; doubled = list(map(lambda x: x * 2, nums));
print(doubled)
14. Predict the output of the following code and explain the reduce()
function: from functools import reduce; prod = reduce(lambda x,y: x*y,
[1,2,3]); print(prod)
15. Explain operations on sets like union and intersection. Write code for
two sets a = {1, 2, 3} and b = {3, 4, 5} to print their union.
16. Explain operations on sets like difference and symmetric difference.
Write code for two sets c = {1,2} d = {2,3} to print c - d.
17. Describe indexing and slicing for tuples. Write code to slice the first
three elements from data = (10, 20, 30, 40, 50).
18. Describe indexing and slicing for strings. Write code to slice the last
three characters from text = "Hello World".
19. Define a function greet_person(name, city="Unknown") using
keyword and default arguments. Demonstrate calling it with keyword
arguments.
20. Define a function calc_area(length=1, width=1) using defaults.
Demonstrate calling with positional and keyword args.
21. Predict the output of the following code and explain reduce(): from
functools import reduce; values = [2, 3, 4]; sum_val = reduce(lambda x, y:
x + y, values); print(sum_val)
22. Predict the output of the following code and explain filter(): primes =
list(filter(lambda x: all(x%d!=0 for d in range(2,int(x**0.5)+1)),
[2,3,4,5,6])); print(primes)
23. Explain mutability in lists vs. tuples with an example. Attempt to
modify a tuple and handle the resulting error in your explanation.
24. Explain mutability in dicts vs. sets with an example. Attempt to add to
a frozenset and explain the error.

Q3A
1. True/False: NumPy arrays are homogeneous, meaning all elements must
be of the same data type.
2. True/False: Pandas DataFrames can hold mixed data types across
columns.
3. Fill in the blank: The function np._______(0, 10, 5) creates an array [0,
2, 4, 6, 8].
4. Fill in the blank: np.linspace(________, 20, 6) creates [0., 4., 8., 12.,
16., 20.].
5. Write the NumPy syntax to create a 3x3 array filled with 1s (integer
type).
6. Write the NumPy syntax to create a 2x2 array filled with 0s (float type).
7. Identify the output: np.arange(5, 15, 2) → ______ (one-line array).
8. Identify the output: np.linspace(1, 5, 3) → ______ (one-line array).
9. True/False: Broadcasting in NumPy allows operations between arrays of
different shapes without explicit looping.
10. True/False: NumPy's vectorized operations are faster than Python
loops due to C backend. (True/False)
11. Match: np.zeros() : A) Identity matrix B) Array of evenly spaced
values C) Array filled with zeros
12. Match: np.ones() : A) Uninitialized array B) Array of 1s C) Random
array
13. Write the syntax for slicing the first two elements of a 1D NumPy
array arr.
14. Write the syntax for slicing the last element of a 1D NumPy array arr.
15. Pandas syntax to create a DataFrame from a list of tuples:
pd.DataFrame(______, columns=['ID', 'Name']).
16. Pandas syntax to create a Series from a dict: pd.Series(________).
17. Fill in the blank: A Pandas _______ is a one-dimensional labeled array
that can hold data of any type.
18. Fill in the blank: A Pandas DataFrame is a two-dimensional ________
with labeled axes. (table)
19. True/False: pd.read_excel() can load data from both .xlsx and .csv
files.
20. True/False: pd.read_csv() requires specifying the separator for tab-
delimited files. (True/False)
21. Write the NumPy syntax to create a 3x3 array filled with 1s (integer
type).
22. Write the NumPy syntax to create a 4x1 column vector of zeros.
23. Identify the output: np.arange(5, 15, 2) → ______ (one-line array).
24. Identify the output: np.zeros((2,3)) → ______ (2D array shape).

Q3B
1. Explain the difference between np.zeros(), np.ones(), and np.empty() for
creating NumPy arrays, including when to use each.
2. Explain the difference between np.array() and np.asarray() for array
creation, including copy behavior.
3. Describe array creation from lists in NumPy, including how dimensions
affect the resulting array (1D, 2D, 3D).
4. Describe array reshaping in NumPy, including how -1 infers
dimensions. Code: np.arange(6).reshape(2,3)
5. What is broadcasting in NumPy? Explain with a brief example how it
allows operations between arrays of different shapes without explicit
looping.
6. What is vectorization in NumPy? Explain with an example of element-
wise multiplication on two arrays.
7. For arr = np.array([[1,2,3],[4,5,6]]), write code to print arr[1, :] and
arr[:,1]. Predict outputs and explain 2D slicing.
8. For arr = np.array([[10,20],[30,40]]), write code to print arr[:,0] and
arr[0:1,:]. Predict outputs and explain slicing.
9. Discuss the attributes of NumPy arrays like ndim, shape, size, dtype,
and itemsize, with examples of their use.
10. Discuss the methods of NumPy arrays like sum(), mean(), and
argmax(), with examples on a 1D array.
11. Explain 1D array indexing and slicing in NumPy, including negative
indices and step values.
12. Explain 2D array transposition in NumPy. Code: arr = np.array([[1,2],
[3,4]]); print(arr.T)
13. Code: df = pd.DataFrame({'A':[1,2], 'B':[3,np.nan]});
df['B'].fillna(df['B'].mean()). Predict the Output & explain imputation.
14. Code: s = pd.Series([1, np.nan, 3]); s.interpolate(). Predict the output
and explain linear interpolation.
15. Describe array indexing in NumPy. What is the difference between
basic indexing and fancy indexing? Give a simple example using a 2D
array.
16. Describe boolean indexing in NumPy. Give an example using a mask
on arr = np.array([1,2,3,4]) to select >2.
17. Describe 2D array indexing in NumPy, covering row/column selection
and subarray slicing.
18. Describe advanced slicing in NumPy with ellipsis (...). Example: arr =
np.random.rand(3,4,5); print(arr[...,1])
19. Explain the concept of a NumPy array. How does it differ from a
standard Python list in terms of performance and functionality? Provide
one example of creating a 1D array.
20. Explain ufuncs in NumPy. How do they differ from Python functions?
Example: np.add([1,2],[3,4])
21. Code: import numpy as np; a=np.array([1,2]); b=3; print(a+b). Predict
the output and explain broadcasting.
22. Code: import numpy as np; x=np.array([[1],[2]]); y=np.array([10,20]);
print(x+y). Predict and explain broadcasting.
23. Code: df = pd.DataFrame({'Group':['G1','G2'], 'Val':[10,20]});
print(df.groupby('Group')['Val'].sum()). Predict the output and explain
groupby aggregation.
24. Code: df = pd.DataFrame({'Cat':['A','A','B'], 'Score':[85,90,75]});
print(df.groupby('Cat')['Score'].mean()). Predict and explain groupby with
mean.

You might also like