0% found this document useful (0 votes)
29 views72 pages

Python Variables and Data Types Quiz

The document contains a quiz on Python programming, covering topics such as string manipulation, data types, control flow, and functions. Each question presents multiple-choice answers, testing the reader's knowledge of Python syntax and concepts. The quiz is structured in a way that encourages discussion and understanding of the material.

Uploaded by

miralous
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)
29 views72 pages

Python Variables and Data Types Quiz

The document contains a quiz on Python programming, covering topics such as string manipulation, data types, control flow, and functions. Each question presents multiple-choice answers, testing the reader's knowledge of Python syntax and concepts. The quiz is structured in a way that encourages discussion and understanding of the material.

Uploaded by

miralous
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

Python Variables Quiz

Question 1
How do you concatenate two strings in Python?
 A
str1 . str2
 B
str1 + str2
 C
str1 , str2
 D
concat(str1, str2)
Discuss it
Question 2
What is the purpose of the __dict__ attribute in Python?
 A
To access the dictionary of a list
 B
To store the attributes of an object
 C
To define a dictionary in Python
 D
To convert a dictionary to a list
Discuss it
Question 3
How do you create a dictionary using a comprehension in Python?
 A
{key: value for key, value in iterable}
 B
dict(iterable)
 C
create_dict(iterable)
 D
{key, value in iterable}
Discuss it
Question 4
How do you create a multiline string in Python?
 A
"This is a multiline string"
 B
'This is a multiline string'
 C
"""This is a multiline string"""
 D
(a and b)
Discuss it
Question 5
How do you convert a floating-point number to an integer in Python?
 A
int(number)
 B
float_to_int(number)
 C
[Link]()
 D
convert(int, number)
Discuss it
Question 6
How do you convert a list of strings to a single string in Python?
 A
"".join(list)
 B
str(list)
 C
convert(list, str)
 D
" ".join(list)
Discuss it
Question 7
What is the output of the following code?
x = [1, 2, 3, 4]
y = filter(lambda a: a % 2 == 0, x)
print(list(y))

 A
[1, 3]
 B
[2, 4]
 C
[1, 2, 3, 4]
 D
[]
Discuss it
Question 8
What is the purpose of the enumerate() function in Python?
 A
To get the index and value of each item in an iterable
 B
To count the occurrences of an element in an iterable
 C
To enumerate through a list
 D
To enumerate through a dictionary
Discuss it
Question 9
How do you check if a key is present in a dictionary?

 A
key in dictionary
 B
[Link](dictionary)
 C
[Link](key)
 D
has_key(key, dictionary)
Discuss it
Question 10
How do you find the length of a list in Python?
 A
len(list)
 B
length(list)
 C
[Link]()
 D
count(list)
Discuss it
Question 11
What is the purpose of the max() function in Python?
 A
To find the maximum value in a list
 B
To get the maximum length of a string
 C
To compare two variables
 D
To find the maximum of two numbers
Discuss it
Question 12
What is the output of the following code?
x = "Hello"
print(x[1:4])

 A
"Hell"
 B
"ello"
 C
"ell"
 D
Error
Discuss it
Question 13
What is a variable in Python?
 A
A reserved word
 B
A data type
 C
A location in memory to store data
 D
A function
Discuss it
Question 14
What is the output of the following code?
x=5
y=2
print(x // y)

 A
2.5
 B
2
 C
2.0
 D
3
Discuss it
Question 15
What is the correct way to check if a variable is of a specific type in Python?
 A
type(var) == "int"
 B
[Link]() == "int"
 C
isinstance(var, int)
 D
[Link]()
Discuss it
Question 16
How do you convert a string to an integer in Python?
 A
int(string)
 B
convert(int, string)
 C
str_to_int(string)
 D
stringToInt(string)
Discuss it
Question 17
What is the scope of a global variable in Python?
 A
Limited to the function it is defined in
 B
Limited to the module it is defined in
 C
Limited to the class it is defined in
 D
Limited to the block it is defined in
Discuss it
Question 18
What does the type() function return in Python?
 A
The value of the variable
 B
The type of the variable
 C
The memory address of the variable
 D
The length of the variable
Discuss it
Question 19
What is the output of the following code?
x = 10
y=5
z=x+y
print(z)
 A
10
 B
15
 C
"10+5"

 D
Error
Discuss it
Question 20
Which of the following data types is immutable in Python?
 A
List
 B
Tuple
 C
Set
 D
Dictionary
Discuss it
Question 21
How do you swap the values of two variables in Python without using a third variable?
 A
x = y; y = x
 B
x, y = y, x
 C
temp = x; x = y; y = temp
 D
x + y; y = x; x = y
Discuss it
Question 22
Which of the following is a valid variable name in Python?
 A
1variable
 B
my_variable
 C
global
 D
variable-1
Discuss it
Question 23
What is the correct way to comment a single line in Python?
 A
// This is a comment
 B
# This is a comment
 C
/* This is a comment */
 D
-- This is a comment
Discuss it
Question 24
How do you declare a variable in Python?
 A
var x
 B
x = variable
 C
declare x
 D
x=4

Python Data Type


Last Updated : Jan 10, 2025

Discuss
Comments

Question 1
Which of these is not a core data type?
 A
Lists
 B
Dictionary
 C
Tuples
 D
Class
Discuss it
Question 2
What data type is this-> li = [1, 23, ‘hello’, 1]
 A
List
 B
Dictionary
 C
Tuple
 D
Array
Discuss it
Question 3
Which of the following function convert a string x to a float in python?
 A
int(x [,base])
 B
long(x [,base] )
 C
float(x)
 D
str(x)
Discuss it
Question 4
Which Python datatype maintains the order of elements inserted?
 A
set
 B
list
 C
dict
 D
Both B and C

Python Output Type


Last Updated : Jan 4, 2025
Discuss
Comments
Question 1
What is the output of the following program :
def myfunc(a):
a=a+2
a=a*2
return a

print myfunc(2)
 A
8
 B
16
 C
Indentation Error
 D
Runtime Error
Discuss it
Question 2
What is the output of the expression : 3*1**3
 A
27
 B
9
 C
3
 D
1
Discuss it
Question 3
What is the output of the following program :
print('{0:.2}'.format(1.0 / 3))
 A
0.333333
 B
0.33
 C
0.333333:-2
 D
Error
Discuss it
Question 4
What is the output of the following program :
print ('{0:-2%}'.format(1.0 / 3))
 A
0.33
 B
0.33%
 C
33.33%
 D
33%
Discuss it
Question 5
What is the output of the following program :
i=0
while i < 3:
print(i,end=' ')
i += 1
else:
print(0)
 A
01230
 B
0120
 C
012
 D
Error
Discuss it
Question 6
What is the output of the following program :
i=0
while i < 5:
print(i)
i += 1
if i == 3:
break
else:
print(0)
 A
0120
 B
012
 C
Error
 D
None of the above
Discuss it
Question 7
What is the output of the following program :
print('cd'.partition('cd'))
 A
(‘cd’)
 B
(”)
 C
(‘cd’, ”, ”)
 D
(”, ‘cd’, ”)
Discuss it
Question 8
What is the output of the following program :
print('abef'.partition('cd'))
 A
(‘abef’)
 B
(‘abef’, ‘cd’, ”)
 C
(‘abef’, ”, ”)
 D
Error
Discuss it
Question 9
What is the output of the following program :
print('abcefd'.replace('cd', '12'))
 A
ab1ef2
 B
abcefd
 C
ab1efd
 D
ab12ed2
Discuss it
Question 10
What will be displayed by the following code?
def f(value, values):
v=1
values[0] = 44
a=3
v = [1, 2, 3]
f(a, v)
print(a, v[0])
 A
11
 B
1 44
 C
31
 D
3 44
Discuss it
Question 11
What is the output of the following code?
print(tuple[1:3] if tuple == ( 'abcd', 786 , 2.23, 'john', 70.2 ) else tuple())
 A
( \'abcd\', 786 , 2.23, \'john\', 70.2 )
 B
abcd
 C
(786, 2.23)
 D
None of the above
Discuss it

Python Operators
Last Updated : Jan 3, 2025
Discuss
Comments
Question 1
What is the output of the following code :
print(9//2)
 A
4.5
 B
4.0
 C
4
 D
Error
Discuss it
Question 2
Which function overloads the >> operator?
 A
more()
 B
gt()
 C
ge()
 D
None of the above
Discuss it
Question 3
Which special method overloads the bitwise OR (|) operator in Python?
 A
__or__()
 B
__and__()
 C
__xor__()
 D
__rshift__()
Discuss it
Question 4
What is the output of the following program :
i=0
while i < 3:
print(i)
i++
print(i+1)
 A
021324
 B
012345
 C
Error
 D
102435
Discuss it

Python Control Flow & Conditional Logic quiz


Last Updated : Jan 10, 2025
Discuss
Comments
Question 1
What is the purpose of the if statement in Python?
 A
To define a function
 B
To declare a variable
 C
To execute a block of code conditionally
 D
To create a loop
Discuss it
Question 2
Which of the following operators is used for equality comparison in Python?
 A
==
 B
=
 C
===
 D
>
Discuss it
Question 3
What will be the output of the following code snippet?
x=5
if x > 0:
print("Positive")
else:
print("Negative")

 A
Positive
 B
Negative
 C
Zero
 D
Error
Discuss it
Question 4
How do you represent the logical AND operator in Python?
 A
&&
 B
and
 C
AND
 D
&
Discuss it
Question 5
What is the purpose of the elif statement in Python?
 A
To handle exceptions
 B
To create a loop
 C
To define a function
 D
To check additional conditions after the initial if statement
Discuss it
Question 6
In Python, what is the purpose of the else statement within an if-else block?
 A
To define a function
 B
To check additional conditions
 C
To execute a block of code when the if condition is false
 D
To create a loop
Discuss it
Question 7
What is the output of the following code snippet?
x = 10
if x > 5:
print("Greater than 5")
elif x > 8:
print("Greater than 8")
else:
print("Less than or equal to 5")

 A
Greater than 5
 B
Greater than 8
 C
Less than or equal to 5
 D
No output
Discuss it
Question 8
Which statement is used to exit a loop prematurely in Python?
 A
break
 B
exit
 C
return
 D
continue
Discuss it
Question 9
In Python, what is the purpose of the try-except block?
 A
To create a loop
 B
To check multiple conditions
 C
To handle exceptions
 D
To define a function
Discuss it
Question 10
What is the output of the following code snippet?
for i in range(5):
if i == 3:
continue
print(i)

 A
01234
 B
0124
 C
012
 D
0123
Python for loop quiz
Last Updated : Apr 2, 2024
Discuss
Comments
Question 1
What is the purpose of the range function in a for loop?
 A
To create a list of numbers
 B
To define the start and end of the loop
 C
To generate a sequence of numbers
 D
To specify the step size of the loop
Discuss it
Question 2
What is the purpose of the enumerate function in a for loop?
 A
To create an enumerated list
 B
To generate a sequence of numbers
 C
To iterate over two lists simultaneously
 D
To access both the index and the value of elements in an iterable
Discuss it
Question 3
How can you iterate over a string in reverse order using a for loop?
 A
for char in reversed(string):
 B
for char in string[::-1]:
 C
for char in [Link]():
 D
Reverse iteration is not possible on strings
Discuss it
Question 4
What will the following code output?
numbers = [3, 7, 2, 8, 5]
for i, num in enumerate(numbers):
if i == num:
break
print(num, end=' ')

 A
37285
 B
37
 C
372
 D
728
Discuss it
Question 5
What is the purpose of the else clause in a for loop?
 A
To execute an alternative block of code
 B
To handle exceptions
 C
To specify the step size of the loop
 D
To execute code when the loop is terminated normally
Discuss it
Question 6
What will the following code output?
for char in 'hello':
if char == 'l':
break
print(char, end=' ')

 A
he
 B
hel
 C
hell
 D
hello
Discuss it
Question 7
What will the following code output?
numbers = [1, 2, 3, 4, 5]
for i, num in enumerate(numbers):
if i % 2 == 0:
continue
print(num, end=' ')

 A
135
 B
24
 C
12345
 D
01234
Discuss it
Question 8
What will the following code output?
numbers = [1, 2, 3, 4, 5]
for i in range(len(numbers) - 1, -1, -1):
print(numbers[i], end=' ')

 A
54321
 B
12345
 C
55555
 D
135
Discuss it
Question 9
How can you iterate over the indices and values of a list using a for loop?
 A
for i, value in enumerate(list):
 B
for index, value in list:
 C
for index in [Link]():
 D
for value in [Link]():
Discuss it
Question 10
How can you iterate over a tuple using a for loop?
 A
for element in tuple:
 B
for in in range(len(tuple)):
 C
for i, element in enumerate(tuple):
 D
for i in tuple:
Discuss it
Question 11
What will the following code output?
for i in range(3):
for j in range(2):
print(i, j)

 A
(0, 0) (0, 1) (1, 0) (1, 1) (2, 0) (2, 1)
 B
012012
 C
001122
 D
001112
Discuss it
Question 12
What is the output of the following code?
total = 0
for num in range(1, 6):
total += num
print(total)

 A
10
 B
11
 C
15
 D
5
Discuss it
Question 13
What is the purpose of a for loop in Python?
 A
To define a function
 B
To iterate over a sequence or iterable
 C
To create a conditional statement
 D
To perform arithmetic operations
Discuss it
Question 14
What will the following code output?
for i in range(5):
print(i, end=' ')

 A
01234
 B
12345
 C
0123
 D
1234
Discuss it
Question 15
How do you iterate over the characters of a string using a for loop?
 A
for char in string:
 B
for i in range(len(string)):
 C
for i, char in enumerate(string):
 D
for i in string:
Discuss it
Question 16
What is the significance of the break and else combination in a for loop?
 A
Executes else only if loop wasn't exited by break.
 B
It is a syntax error; break and else cannot be used together.
 C
It skips the current iteration.
 D
It restarts the loop.
Discuss it
Question 17
How can you iterate over the keys and values of a dictionary using a for loop?
 A
for key, value in [Link]():
 B
for key in [Link]():
 C
for key in dictionary:
 D
for value in [Link]():
Discuss it
Question 18
What is the purpose of the pass statement in a for loop?
 A
To terminate the loop
 B
To create an infinite loop
 C
To skip the current iteration and move to the next
 D
To do nothing and continue to the next iteration
Discuss it
Question 19
What is the difference between a for loop and a while loop?
 A
For loops iterate over sequences, while while loops run based on a condition.
 B
For loops are better than while loop.
 C
They are not interchangeable.
 D
For loop is faster than while loop.
Discuss it
Question 20
What is the purpose of the continue keyword in a for loop?
 A
To exit the loop
 B
To skip the remaining code and move to the next iteration
 C
To restart the loop from the beginning
 D
To print the current iteration and continue
Discuss it
Question 21
How can you iterate over the elements of a list in reverse order using a for loop?
 A
Using the reversed function
 B
Using the reverse method
 C
Using a negative step in the range function
 D
Python doesn't support iterating in reverse order
Discuss it
Question 22
What will the following code output?
for i in range(3):
print(i, end =' ')

 A
012
 B
123
 C
0123
 D
1234
Discuss it
Question 23
In a for loop, how can you access both the index and the value of each element in a
list?
 A
Using a while loop
 B
Using the enumerate function
 C
Using the index method
 D
Using the iter function
Discuss it
Question 24
How is the range function typically used in a for loop?
 A
range(start, end)
 B
range(end)
 C
range(start, end, step)
 D
range(step)
Discuss it

Python While Loop Quiz


Last Updated : Apr 2, 2024
Discuss
Comments
Question 1
What does the following Python code do?
count = 0
while count < 5:
print("Count:", count)
count += 1
if count == 3:
continue
print("After Continue")

 A
Prints "Count: 0" to "Count: 4" with "After Continue" after each line.
 B
Prints "Count: 0" to "Count: 2" with "After Continue" after each line.
 C
Prints "Count: 0" to "Count: 4" without "After Continue" after "Count: 3".
 D
Raises a SyntaxError.
Discuss it
Question 2
How can you iterate over the items of a list using a while loop?
 A
Use a for loop instead.
 B
Use the range function with the length of the list.
 C
Convert the list to a set and iterate over it.
 D
Use the enumerate function.
Discuss it
Question 3
In Python, can a while loop be used to iterate over a dictionary directly?
 A
Yes
 B
No
 C
Only if the dictionary keys are integers.
 D
Only if the dictionary has a single key.
Discuss it
Question 4
In Python, how can you emulate the behavior of a break statement inside a while loop
without using bre
 A
Use a return statement.
 B
Use a pass statement.
 C
Raise a custom exception.
 D
Use a goto statement.
Discuss it
Question 5
In Python, can a while loop have multiple else blocks?
 A
Yes
 B
No
 C
Only if the loop has multiple conditions.
 D
Only if the loop uses nested if statements.
Discuss it
Question 6
What is the purpose of the assert statement in a while loop?
 A
To terminate the loop.
 B
To check if a condition is true and raise an error if not.
 C
To skip the rest of the code in the loop.
 D
It is not a valid statement in a while loop.
Discuss it
Question 7
What is the purpose of the else clause in a while loop?
 A
It always runs after the loop completes.
 B
It is used to handle exceptions within the loop.
 C
It runs if the loop encounters an error.
 D
It runs if the loop completes without encountering a break statement.
Discuss it
Question 8
How does the while-else construct work in Python?
 A
It is not a valid construct in Python.
 B
The else block always runs after the loop.
 C
The else block runs if the loop encounters an error.
 D
The else block runs if the loop completes without encountering a break statement.
Discuss it
Question 9
What is the purpose of the continue statement in a while loop?
 A
Terminates the loop.
 B
Skips the remaining code in the loop and moves to the next iteration.
 C
Exits the loop prematurely.
 D
Breaks out of the loop entirely.
Discuss it
Question 10
What is the output of the following Python code?
num = 2
while num < 10:
print(num, end=" ")
num **= 2

 A
Prints powers of 2 from 2 to 8.
 B
Prints the square of numbers from 2 to 10.
 C
Prints numbers in the range [2, 10) with a step of 2.
 D
Raises a SyntaxError.
Discuss it
Question 11
What is the basic syntax of a while loop in Python?
 A
while (condition):
 B
for condition:
 C
while loop condition do:
 D
loop while condition:
Discuss it
Question 12
What does the following Python code do?
x=1
while x < 6:
print(x, end=" ")
x += 1
if x == 4:
continue

 A
Prints numbers in the range [1, 6) with a skip for 4.
 B
Prints numbers in the range [1, 6] without a skip.
 C
Raises a SyntaxError.
 D
Enters into an infinite loop.
Discuss it
Question 13
What does the following Python code do?
num = 10
while num > 0:
if num % 2 == 0:
print(num, end=" ")
num -= 1

 A
Prints even numbers in reverse order from 10 to 1.
 B
Prints odd numbers in the range [1, 10].
 C
Prints even numbers in the range [1, 10].
 D
Raises a SyntaxError.
Discuss it
Question 14
What is the output of the following Python code?
count = 0
while count < 3:
print("Hello")
count += 1
else:
print("Else block")

 A
Prints "Hello" three times and then prints "Else block."
 B
Prints "Hello" four times.
 C
Prints "Else block" three times.
 D
Raises a .SyntaxError
Discuss it
Question 15
What is the purpose of the locals() function in a while loop?
 A
To access local variables of the loop.
 B
To define new local variables.
 C
To exit the loop.
 D
It is not a valid function in a while loop.
Discuss it
Question 16
How can you write a loop in Python that executes its body at least once?

 A
Use a for loop.
 B
Use a while loop with the condition always True and a break to exit inside the
loop.

 C
Set the loop condition to False.
 D
Use a continue statement.
Discuss it
Question 17
Which of the following statements is used to increment a variable within a while loop?
 A
inc()
 B
++
 C
+=
 D
increment
Discuss it
Question 18
How can you avoid an infinite loop?
 A
By using a for loop instead.
 B
By setting the loop condition to True.
 C
By providing a valid exit condition.
 D
Infinite loops cannot be avoided.
Discuss it
Question 19
How many times will a while loop with the condition True run?
 A
Zero times
 B
Infinite times
 C
Once
 D
Until it encounters an error
Discuss it
Question 20
How does a while loop differ from a for loop?
 A
While loops can iterate over a sequence, for loops cannot.
 B
While loops always have an exit condition, for loops do not.
 C
While loops have entry-controlled flow, for loops have exit-controlled flow.
 D
There is no difference between them.
Discuss it

Python List Quiz


Last Updated : Jan 3, 2025
Discuss
Comments
Question 1
Find the output of the following program:
nameList = ['Harsh', 'Pratik', 'Bob', 'Dhruv']

pos = [Link]("GeeksforGeeks")

print (pos * 3)
 A
GeeksforGeeks GeeksforGeeks GeeksforGeeks
 B
Harsh
 C
Harsh Harsh Harsh
 D
ValueError: \'GeeksforGeeks\' is not in list
Discuss it
Question 2
Find the output of the following program:
li = ['a', 'b', 'c', 'd', 'e']
print(li[10:] )
 A
[\'a\', \'b\', \'c\', \'d\', \'e\']
 B
[ \'c\', \'d\', \'e\']
 C
[]
 D
[\'a\', \'b\']
Discuss it
Question 3
Find the output of the following program:
def REVERSE(a):
[Link]()
return(a)
def YKNJS(a):
b = []
[Link](REVERSE(a))
print(b)

a = [1, 3.1, 5.31, 7.531]


YKNJS(a)
 A
[1, 3.1, 5.31, 7.531]
 B
[7.531, 5.31, 3.1, 1]
 C
IndexError
 D
AttributeError: ‘NoneType’ object has no attribute ‘REVERSE’
Discuss it
Question 4
Find the output of the following program:
li = [1, 3, 5, 7, 9]
print([Link](-3), end = ' ')
 A
5
 B
9
 C
7
 D
3
Discuss it
Question 5
Find the output of the following program:
a = [1, 2, 3, 4]
b=a
c = [Link]()
d=a
a[0] = [5]
print(a, b, c, d)
 A
[5, 2, 3, 4] [5, 2, 3, 4] [1, 2, 3, 4] [1, 2, 3, 4]
 B
[[5], 2, 3, 4] [[5], 2, 3, 4] [[5], 2, 3, 4] [1, 2, 3, 4]
 C
[5, 2, 3, 4] [5, 2, 3, 4] [5, 2, 3, 4] [1, 2, 3, 4]
 D
[[5], 2, 3, 4] [[5], 2, 3, 4] [1, 2, 3, 4] [[5], 2, 3, 4]
Discuss it
Question 6
Find the output of the following program:
li = [1, 1.33, 'GFG', 0, 'NO', None, 'G', True]
val1, val2 = 0,''
for x in li:
if(type(x) == int or type(x) == float):
val1 += x
elif(type(x) == str):
val2 += x
else:
break
print(val1, val2)
 A
2 GFGNO
 B
2.33 GFGNOG
 C
2.33 GFGNONoneGTrue
 D
2.33 GFGNO
Discuss it
Question 7
Find the output of the following program:
a = []
[Link]([1, [2, 3], 4])
[Link]([7, 8, 9])
print(a[0][1][1] + a[2])
 A
Type Error
 B
12
 C
11
 D
38
Discuss it
Question 8
Find the output of the following program:
a = [x for x in (x for x in 'Geeks 22966 for Geeks' if [Link]()) if
(x in ([x for x in range(20)]))]
print(a)
 A
[2, 2, 9, 6, 6]
 B
[]
 C
Compilation error
 D
Runtime error
Discuss it
Question 9
Find the output of the following program:
a = 'Geeks 22536 for 445 Geeks'
b = [x for x in (int(x) for x in a if [Link]()) if x%2 == 0]
print(b)
 A
[2, 2, 6, 4, 4]
 B
Compilation error
 C
Runtime error
 D
[‘2’, ‘2’, ‘5’, ‘3’, ‘6’, ‘4’, ‘4’, ‘5’]
Discuss it
Question 10
Find the output of the following program:
a = ['Geeks', 'for', 'Geeks']
b = [i[0].upper() for i in a]
print(b)
 A
[‘G’, ‘F’, ‘G’]
 B
[‘GEEKS’, ‘FOR’, ‘GEEKS’]
 C
[‘GEEKS’]
 D
Compilation error
Discuss it
Question 11
Find the output of the following program:
a = [x for x in range(5)]
b = [x for x in range(7) if x in a and x%2==0]
print(b)
 A
[0, 2, 4, 6]
 B
[0, 2, 4]
 C
[0, 1, 2, 3, 4, 5]
 D
Runtime error
Discuss it
Question 12
Find the output of the following program:
li = [2, 3, 9]
li = [[x for x in[li]] for x in range(3)]
print (li)
 A
[[[2, 3, 9]], [[2, 3, 9]], [[2, 3, 9]]]
 B
[[2, 3, 9], [2, 3, 9], [2, 3, 9]]
 C
[[[2, 3, 9]], [[2, 3, 9]]]
 D
None of these
Discuss it
Question 13
Question 15: Find the output of the following program:
li = ['a', 'b', 'c'] * -3
print(li)
 A
[\'a\', \'b\', \'c\', \'a\', \'b\', \'c\', \'a\', \'b\', \'c\']
 B
[\'c\', \'b\', \'a\', \'c\', \'b\', \'a\', \'c\', \'b\', \'a\']
 C
[]
 D
[\'a\', \'b\', \'c\']
Discuss it
Question 14
Find the output of the following program:
li = ['Harsh', 'Pratik', 'Bob', 'Dhruv']
print (li[1][-1])
 A
r
 B
b
 C
D
 D
k
Discuss it
Question 15
Find the output of the following program:
a = [10, 20, 30, 40, 50]
b = [1, 2, 3, 4, 5]
subtracted = list()
for a, b in zip(a, b):
item = a -b
[Link](item)

print(subtracted)
 A
[10, 20, 30, 40, 50]
 B
[1, 2, 3, 4, 5]
 C
[10, 20, 30, 40, 50,-1, -2, -3, -4, -5]
 D
9, 18, 27, 36, 45
Discuss it
Question 16
Find the output of the following program:
a = ['python', 'learning', '@', 'Geeks', 'for', 'Geeks']
print(a[0:6:2])
 A
['python', '@', 'for']
 B
[\'Geeks\', \'Geeks\', \'learning\']
 C
[\'python\', \'learning\', \'@\', \'Geeks\', \'for\', \'Geeks\']
 D
[\'python\', \'Geeks\']
Discuss it
Question 17
Find the output of the following program:
a = [1, 2, 3, None, (1, 2, 3, 4, 5), ['Geeks', 'for', 'Geeks']]
print(len(a))
 A
12
 B
11
 C
6
 D
22
Discuss it
Question 18
Find the output of the following program:
a = ['physics', 'chemistry', 1997, 2000]
print (a[1][-1])
 A
p
 B
y
 C
7
 D
2
Discuss it
Question 19
Find the output of the following program:
a = [1998, 2002]
b = [2014, 2016]

print ((a + b)*2)


 A
[1998, 2002, 2014, 2016, 1998, 2002, 2014, 2016]
 B
[1998, 2002, 2014, 2016]
 C
[1998, 2002, 1998, 2002]
 D
[2014, 2016, 2014, 2016]
Discuss it
Question 20
Find the output of the following program:
a = [1, 2, 3, 4, 5]
b=a
b[0] = 0;

print(a)
 A
[1, 2, 3, 4, 5, 0]
 B
[0,1, 2, 3, 4, 5]
 C
[0, 2, 3, 4, 5]
 D
[1, 2, 3, 4, 0]
Discuss it
Question 21
Find the output of the following program:
# statement 1
li = range(100, 110)

# statement 2
print ([Link](105))
 A
105
 B
5
 C
106
 D
104
Discuss it
Question 22
Find the output of the following program:
def gfg(x,li=[]):
for i in range(x):
[Link](i*i)
print(li)

gfg(3,[3,2,1])
 A
[3, 2, 1, 0, 1, 4]
 B
[0, 1, 0, 1, 4]
 C
[0, 1]
 D
[]
Discuss it
Question 23
Find the output of the following program:
a = ['Learn', 'Quiz', 'Practice', 'Contribute']
b=a
c = a[:]

b[0] = 'Code'
c[1] = 'Mcq'

count = 0
for c in (a, b, c):
if c[0] == 'Code':
count += 1
if c[1] == 'Mcq':
count += 10

print (count)
 A
4
 B
5
 C
11
 D
12
Discuss it
Question 24
Find the output of the following program:
def addToList(a):
a += [10]
b = [10, 20, 30, 40]
addToList(b)
print (len(b))
 A
4
 B
5
 C
6
 D
10
Discuss it
Question 25
Find the output of the following program:
li = [1, 2, 3, 4]
[Link]([5,6,7,8])
print(li)
 A
[1,2,3,4,5,6,7,8]
 B
[1,2,3,4]
 C
[1,2,3,4,[5,6,7,8]]
 D
[1,2,3,4][5,6,7,8]
Discuss it

Python String Quiz


Last Updated : Jan 10, 2025
Discuss
Comments
Question 1
Which of the following is true about lists in Python?
 A
Lists are dynamic sized arrays
 B
Lists store references at items contiguous locations
 C
A list can contain elements of different types.
 D
All of the above
Discuss it
Question 2
What are strings in Python?

 A
Arrays of bytes representing Unicode characters
 B
Arrays of integers representing characters
 C
Single characters only
 D
Arrays of floats representing characters
Discuss it
Question 3
What does the string method .join() do in Python?

 A
Splits a string into a list
 B
Concatenates a list of strings into one string
 C
Reverses a string
 D
Returns the index of a substring in the string
Discuss it
Question 4
Which method can be used to handle strings with both single and double quotes
simultaneously in Python?

 A
Using triple quotes
 B
Using backslash ()
 C
Using parentheses
 D
Using single quotes only
Discuss it
Question 5
How can you print a string without resolving escape sequences in Python?

 A
By using the repr() function
 B
By using the eval() function
 C
By using the str() function
 D
By using the format() function
Discuss it
Question 6
What is the primary reason that updating or deleting characters from a string in Python
is not allowed?

 A
Strings are mutable data types
 B
Python strings are immutable data types
 C
Python doesn't support character-level operations on strings
 D
Python string operations are not efficient
Discuss it
Question 7
What is the purpose of the find() function in Python strings?

 A
It returns the position of the last occurrence of a substring within a string.
 B
It returns true if the string begins with a specified prefix.
 C
It returns the position of the first occurrence of a substring within a string.
 D
It returns true if all the letters in the string are lowercased.
Discuss it
Question 8
What does the startswith() function in Python do?

 A
It returns true if all the letters in the string are uppercased.
 B
It returns true if the string starts with a specified prefix.
 C
It returns true if the string ends with a specified suffix.
 D
It returns true if all the letters in the string are lowercased
Discuss it
Question 9
What does the title() method do in Python strings?

 A
It converts the first letter of every word to uppercase and others to lowercase.
 B
It swaps the cases of all letters in the string.
 C
It converts all letters to uppercase.
 D
It converts all letters to lowercase.
Discuss it
Question 10
What is the time complexity of the find() function in Python?

 A
O(log n)
 B
O(n^2)
 C
O(n)
 D
O(1)
Discuss it
Question 11
What does the count() function in Python do?

 A
It counts the total number of characters in a string.
 B
It counts the occurrences of a specified substring within a string.
 C
It returns true if all characters in the string are alphabets.
 D
It returns true if all characters in the string are numbers.
Discuss it
Question 12
What does the isalpha() function in Python return?

 A
True if all characters in the string are alphabets, else False.
 B
True if all characters in the string are numbers, else False.

 C
True if all characters in the string are alphanumeric, else False.
 D
True if all characters in the string are spaces, else False.
Discuss it
Question 13
What does the strip() method do in Python?

 A
Deletes all the leading characters mentioned in its argument.
 B
Deletes all the trailing characters mentioned in its argument.
 C
Deletes all the leading and trailing characters mentioned in its argument.
 D
Splits the string based on the characters mentioned in its argument.
Discuss it
Question 14
Which method is best suited to replace all tab characters with whitespace using the
given tab size?

 A
strip()
 B
expandtabs()
 C
replace()
 D
maketrans()
Discuss it
Question 15
Which method is used to create a Regex object in Python?
 A
[Link]()
 B
[Link]()
 C
[Link]()
 D
[Link]()
Discuss it
Question 16
What is the purpose of the translate() function in Python?

 A
It is used to map the contents of string 1 with string 2 with respective indices to be
translated later.
 B
It is used to swap the string elements mapped with the help of maketrans().
 C
It is used to replace the substring with a new substring in the string.
 D
It is used to replace all tab characters with whitespace using the given tab size.
Discuss it
Tags:
Python-Quizzes
Python Tuples Quiz
Last Updated : Aug 5, 2025
Discuss
Comments
Question 1
What is the output of the following program?
tup = (1, 2, 3, 4)
[Link]( (5, 6, 7) )
print(len(tup))
 A
1
 B
2
 C
5
 D
Error
Discuss it
Question 2
What is the output of the following program?
tup = {}
tup[(1,2,4)] = 8
tup[(4,2,1)] = 10
tup[(1,2)] = 12
sum1 = 0
for k in tup:
sum1 += tup[k]
print(len(tup) + sum1)
 A
30
 B
31
 C
32
 D
33
Discuss it
Question 3
What is the output of the following program?
tup1 = (1, 2, 4, 3)
tup2 = (1, 2, 3, 4)
print(tup1 < tup2)
 A
Error
 B
True
 C
False
 D
Unexpected
Discuss it
Question 4
What is the output of the following program?
tup = (1, 2, 3)
print(2 * tup)
 A
(1, 2, 3, 1, 2, 3)
 B
(1, 2, 3, 4, 5, 6)
 C
(3, 6, 9)
 D
Error
Discuss it
Question 5
What is the output of the following program?
tup=("Check")*3
print(tup)
 A
Unexpected
 B
3Check
 C
CheckCheckCheck
 D
Syntax Error
Discuss it
Question 6
What is the output of the following program?
s = 'geeks'
a, b, c, d, e = s
b = c = '*'
s = (a, b, c, d, e)
print(s)
 A
(‘g’, ‘*’, ‘*’, ‘k’, ‘s’)
 B
(‘g’, ‘e’, ‘e’, ‘k’, ‘s’)
 C
(‘geeks’, ‘*’, ‘*’)
 D
KeyError
Discuss it
Question 7
What is the output of the following program?
tup = (2e-04, True, False, 8, 1.001, True)
val = 0
for x in tup:
val += int(x)
print(val)
 A
12
 B
11
 C
11.001199999999999
 D
TypeError
Discuss it
Question 8
What is the output of the following program?
li = [3, 1, 2, 4]
tup = ('A', 'b', 'c', 'd')
[Link]()
counter = 0
for x in tup:
li[counter] += int(x)
counter += 1
break
print(li)
 A
[66, 97, 99, 101]
 B
[66, 68, 70, 72]
 C
[66, 67, 68, 69]
 D
ValueError
Discuss it
Question 9
What is the output of the following program?
li = [2e-04, 'a', False, 87]
tup = (6.22, 'boy', True, 554)
for i in range(len(li)):
if li[i]:
li[i] = li[i] + tup[i]
else:
tup[i] = li[i] + li[i]
break
 A
[6.222e-04, ‘aboy’, True, 641]
 B
[6.2202, ‘aboy’, 1, 641]
 C
TypeError
 D
[6.2202, ‘aboy’, False, 87]
Discuss it
Question 10
What is the output of the following program?
import sys
tup = tuple()
print([Link](tup), end = " ")
tup = (1, 2)
print([Link](tup), end = " ")
tup = (1, 3, (4, 5))
print([Link](tup), end = " ")
tup = (1, 2, 3, 4, 5, [3, 4], 'p', '8', 9.777, (1, 3))
print([Link](tup))
 A
0 2 3 10
 B
32 34 35 42
 C
48 64 72 128
 D
48 144 192 480
Discuss it
Question 11
What is the output of the following program?
tup1 = (1)
tup2 = (3, 4)
tup1 += 5
print(tup1)
 A
TypeError
 B
(1, 5, 3, 4)
 C
1 TypeError
 D
6
Discuss it

Python Dictionary Quiz


Last Updated : Jan 3, 2025
Discuss
Comments
Question 1
What will be the output of the following code?
s = "GeeksforGeeks"
print(s[0], s[-1])
 A
GG
 B
Gs
 C
Gk
 D
ek
Discuss it
Question 2
Find the output of the following program:
d = dict()
for x in enumerate(range(2)):
d[x[0]] = x[1]
d[x[1]+7] = x[0]
print(d)
 A
{0: 1, 7: 0, 1: 1, 8: 0}
 B
{1: 1, 7: 2, 0: 1, 8: 1}
 C
{0: 0, 7: 0, 1: 1, 8: 1}
 D
KeyError
Discuss it
Question 3
Find the output of the following program:
d1 = {'GFG' : 1,
'Google' : 2,
'GFG' : 3
}
print(d1['GFG']);
 A
Compilation error due to duplicate keys
 B
Runtime time error due to duplicate keys
 C
3
 D
1
Discuss it
Question 4
Find the output of the following program:
d = {}

def addTodict(country):
if country in d:
d[country] += 1
else:
d[country] = 1
addTodict('China')
addTodict('Japan')
addTodict('china')

print (len(d))
 A
0
 B
1
 C
2
 D
3
Discuss it
Question 5
Find the output of the following program:
d = {1:'1', 2:'2', 3:'3'}
del d[1]
d[1] = '10'
del d[2]
print (len(d) )
 A
1
 B
2
 C
3
 D
4
Discuss it
Question 6
Find the output of the following program:
a ={}
a['a']= 1
a['b']=[2, 3, 4]
print(a)
 A
{‘b’: [2], ‘a’: 1}
 B
{'a': 1, 'b': [2, 3, 4]}
 C
{‘b’: [2], ‘a’: [3]}
 D
Error
Discuss it
Question 7
Find the output of the following program:
d = {1:'A', 2:'B', 3:'C'}
del d[1]
d[1] = 'D'
del d[2]
print(len(d))
 A
Error
 B
0
 C
1
 D
2
Discuss it
Question 8
Find the output of the following program:
a = {}
a[1] = 1
a['1'] = 2
a[1]= a[1]+1
count = 0
for i in a:
count += a[i]
print(count)
 A
2
 B
4
 C
1
 D
Error
Discuss it
Question 9
Find the output of the following program:
d ={1:"geek", 2:"for", 3:"geeks"}
del d
 A
del deletes the entire dictionary
 B
del doesn’t exist for the dictionary
 C
del deletes the keys in the dictionary
 D
del deletes the values in the dictionary
Discuss it
Question 10
Find the output of the following program:
d = {"geek":10, "for":45, "geeks": 90}
print("geek" in d)
 A
10
 B
False
 C
True
 D
Error
Discuss it
Question 11
Find the output of the following program:
d1 = {"john":40, "peter":45}
d2 = {"john":466, "peter":45}
print (d1 > d2)
 A
True
 B
False
 C
Compilation Error
 D
TypeError
Discuss it
Question 12
Find the output of the following program:
d = {}
d[(1,2,4)] = 8
d[(4,2,1)] = 10
d[(1,2)] = 12

sum = 0
for k in d:
sum += d[k]

print (len(d) + sum)


 A
33
 B
12
 C
10
 D
8
Discuss it
Question 13
Find the output of the following program:
d = {'GFG' : 1,
'Facebook' : 2,
'Google' : 3
}
for (key, values) in [Link]():
print(key, values, end = " ")
 A
GFG 1 Facebook 2 Google 3
 B
Facebook 2 GFG 1 Google 3
 C
Facebook 2 Google 3 GFG 1
 D
Any of the above
Discuss it
Question 14
Find the output of the following program:
d = dict()
d['key1'] = {'key1' : 44, 'key2' : 566}
d['key2'] = [1, 2, 3, 4]
for (key, values) in [Link]():
print(values, end = "")
 A
Compilation error
 B
{'key1': 44, 'key2': 566}[1, 2, 3, 4]
 C
Runtime error
 D
None of the above
Discuss it
Question 15
Find the output of the following program:
d1 = {'Google' : 1,
'Facebook' : 2,
'Microsoft' : 3
}
d2 = {'GFG' : 1,
'Microsoft' : 2,
'Youtube' : 3
}
[Link](d2);
for key, values in [Link]():
print(key, values , end=" ")
 A
Google 1 Facebook 2 Microsoft 2 GFG 1 Youtube 3
 B
Runtime error
 C
Compilation error
 D
None of these
Discuss it
Question 16
Find the output of the following program:
d = {'GFG' : '[Link]',
'google' : '[Link]',
'facebook' : '[Link]'
}
del d['google'];
for key, values in [Link]():
print(key, end=" ")
[Link]();
for key, values in [Link]():
print(key)
del d;
for key, values in [Link]():
print(key)
 A
Both B and D
 B
GFG facebook
 C
facebook GFG
 D
NameError: name 'dictionary' is not defined
Discuss it
Question 17
Which of the following is FALSE about dictionary?
 A
The values of a dictionary can be accessed using keys
 B
The keys of a dictionary can be accessed using values
 C
Both of the above
 D
None of the above
Discuss it
Question 18
Find the output of the following program:
a = {'geeks' : 1, 'gfg' : 2}
b = {'geeks' : 2, 'gfg' : 1}
print (a == b)
 A
True
 B
False
 C
Error
 D
None
Discuss it
Question 19
Find the output of the following program:
dict ={}
print (all(dict))
 A
{}
 B
False
 C
True
 D
An exception is thrown
Discuss it
Question 20
Find the output of the following program:
a = {}
[Link](['a', 'b', 'c', 'd'], 98)
print (a)
 A
Syntax error
 B
{‘a’:98, ‘b’:98, ‘c’:98, ‘d’:98}
 C
{‘a’:None, ‘b’:None, ‘c’:None.’d’:None}
 D
{}
Discuss it
Question 21
Question 5:Find the output of the following program:
d = {1 : [1, 2, 3], 2: (4, 6, 8)}
d[1].append(4)
print(d[1], end = " ")
li = [d[2]]
[Link](10)
d[2] = tuple(L)
print(d[2])
 A
[1, 2, 3, 4] ((4, 6, 8), 10)
 B
[1, 2, 3, 4] (4, 6, 8, 10)
 C
[1, 2, 3, 4] TypeError: tuples are immutable
 D
[1, 2, 3, 4] [4, 6, 8, 10]
Discuss it
Question 22
Find the output of the following program:
d = dict()
for i in range (3):
for j in range(2):
d[i] = j
print(d)
 A
{0: 0, 1: 0, 2: 0}
 B
{0: 1, 1: 1, 2: 1}
 C
{0: 0, 1: 0, 2: 0, 0: 1, 1: 1, 2: 1}
 D
TypeError: Immutable object
Discuss it
Question 23
Find the output of the following program:
d = {1 : {'A' : {1 : "A"}, 2 : "B"}, 3 :"C", 'B' : "D", "D": 'E'}
print(d[d[d[1][2]]], end = " ")
print(d[d[1]["A"][2]])
 A
CB
 B
E Key Error
 C
BD
 D
DB
Discuss it
Question 24
Find the output of the following program:
d = {1 : 1, 2 : '2', '1' : 1, '2' : 3}
d['1'] = 2
print(d[d[d[str(d[1])]]])
 A
2
 B
3
 C
\'2\'
 D
KeyError
Discuss it

Python Sets Quiz


Last Updated : Jan 3, 2025
Discuss
Comments
Question 1
What is the output of the following program?
set1 = {1, 2, 3, 4, 4}
print(set1)
 A
{1, 2, 3}
 B
{1, 2, 3, 4}
 C
{1, 2, 3, 4, 4}
 D
Error
Discuss it
Question 2
What is the output of the following program?
set1 = {3, 4, 5}
[Link]([1, 2, 3])
print(set1)
 A
{1, 2, 3, 4, 5}
 B
{3, 4, 5, 1, 2, 3}
 C
{1, 2, 3, 3, 4, 5}
 D
Error
Discuss it
Question 3
What is the output of the following program?
set1 = {1, 2, 3}
set2 = [Link]()
[Link](4)
print(set1)
 A
{1, 2, 3, 4}
 B
{1, 2, 3}
 C
Invalid Syntax
 D
Error
Discuss it
Question 4
What is the output of the following program?
set1 = {1, 2, 3}
set2 = [Link](4)
print(set2)
 A
{1, 2, 3, 4}
 B
{1, 2, 3}
 C
Invalid Syntax
 D
None
Discuss it
Question 5
What is the output of the following program?
set1 = {1, 2, 3}
set2 = {4, 5, 6}
print(len(set1 + set2))
 A
3
 B
6
 C
Unexpected
 D
Error
Discuss it
Question 6
What is the output of the following program?
set1 = {0, 2, 4, 6, 8};
set2 = {1, 2, 3, 4, 5};

print(set1 | set2)
 A
{0, 1, 2, 3, 4, 5}
 B
{0, 1, 2, 3, 4, 5, 6, 8}
 C
{ 6, 8}
 D
None
Discuss it
Question 7
What is the output of the following program?
set1 = {0, 2, 4, 6, 8};
set2 = {1, 2, 3, 4, 5};

print(set1 & set2)


 A
{0, 1, 2, 3, 4, 5, 6, 8}
 B
{0, 1, 3, 5, 6, 8}
 C
{2, 4}
 D
{0, 8, 6}
Discuss it
Question 8
What is the output of the following program?
set1 = {0, 2, 4, 6, 8};
set2 = {1, 2, 3, 4, 5};

print(set1 - set2)
 A
{0, 1, 2, 3, 4, 5, 6, 8}
 B
{0, 8, 6}
 C
{2, 4}
 D
{0, 1, 3, 5, 6, 8}
Discuss it
Question 9
What is the output of the following program?
set1 = {0, 2, 4, 6, 8};
set2 = {1, 2, 3, 4, 5};

print(set1 ^ set2)
 A
{0, 1, 2, 3, 4, 5, 6, 8}
 B
{2, 4}
 C
{0, 8, 6}
 D
{0, 1, 3, 5, 6, 8}
Discuss it
Question 10
What is the output of the following program?
set1 = set([1, 2, 4, 4, 3, 3, 3, 6, 5])

print(set1)
 A
{1, 2, 4, 4, 3, 3, 3, 6, 5}
 B
{1, 2, 3, 4, 5, 6}
 C
[1, 2, 3, 4, 5, 6]
 D
[1, 2, 4, 4, 3, 3, 3, 6, 5]
Discuss it
Question 11
What is the output of the following program?
set1 = set([ 4, 5, (6, 7)])
[Link]([10, 11])

print(set1)
 A
{4, 5, 6, 7, 10, 11}
 B
{4, 5, 10, 11}
 C
{4, 5, (6, 7), 10, 11}
 D
None
Discuss it

Python Functions
Last Updated : Jan 3, 2025
Discuss
Comments
Question 1
What will be the output of the following code :
print(type(type(int)))

 A
type \'int\'
 B
type \'type\'
 C
Error
 D
0
Discuss it
Question 2
What is the output of the following code :
li = ['a', 'b', 'c', 'd']
print("".join(li))
 A
Error
 B
None
 C
abcd
 D
[‘a’,’b’,’c’,’d’]
Discuss it
Question 3
What is the output of the following segment :
print(chr(ord('A')))
 A
A
 B
B
 C
a
 D
Error
Discuss it
Question 4
What is the output of the following program :
y=8
z = lambda x : x * y
print(z(6))
 A
48
 B
14
 C
64
 D
None of the above
Discuss it
Question 5
What is called when a function is defined inside a class?
 A
Module
 B
Class
 C
Another Function
 D
Method
Discuss it
Question 6
Which of the following is the use of id() function in python?
 A
Id returns the identity of the object
 B
Every object doesn’t have a unique id
 C
All of the mentioned
 D
None of the mentioned
Discuss it
Question 7
What is the output of the following program :
def func(a, b=[]):
[Link](a)
return b

print(func(1))
print(func(2))
 A
[1]
[2]

 B
[1]
[1, 2]

 C
[1]
[1]

 D
None of the above
Discuss it
Question 8
Suppose li is [3, 4, 5, 20, 5, 25, 1, 3], what is li after [Link](1)?
 A
[3, 4, 5, 20, 5, 25, 1, 3]
 B
[1, 3, 3, 4, 5, 5, 20, 25]
 C
[3, 5, 20, 5, 25, 1, 3]
 D
[1, 3, 4, 5, 20, 5, 25]
Discuss it
Question 9
[Link]() returns ________
 A
The current time as a string formatted as "HH:MM:SS".
 B
The current time in milliseconds since January 1, 1970 UTC (Unix epoch).
 C
The current time in seconds (including fractions) since January 1, 1970 UTC
(Unix epoch).
 D
The system’s local time in seconds since midnight.

Discuss it
Question 10
What will be the output of the following code?
def outer():
x = 10
def inner():
nonlocal x
x += 5
return x
return inner

closure = outer()
print(closure())
print(closure())

 A
15
20

 B
15
15

 C
10
15

 D
5
5

Discuss it

Python Namespaces and Scope Quiz


Last Updated : Apr 2, 2024
Discuss
Comments
Question 1
What is the purpose of the __call__ method in Python?
 A
To call a function
 B
To make an instance callable
 C
To define class variables
 D
To create a callable object
Discuss it
Question 2
In Python, what is the purpose of the property() function?
 A
To define a class property
 B
To access global variables
 C
To create a new property
 D
To define a method as a property
Discuss it
Question 3
What is the purpose of the 'staticmethod' decorator in Python?
 A
To define a static method in a class
 B
To access global variables
 C
To create a static variable
 D
To declare a method as static
Discuss it
Question 4
How can you access a global variable from within a function in Python?
 A
Use the access keyword
 B
Use the global keyword
 C
Use the outer keyword
 D
Use the variable name directly
Discuss it
Question 5
What is the purpose of the dir() function in Python?
 A
Returns a list of all global variables
 B
Returns a list of all local variables
 C
Returns a list of names in the current namespace
 D
Returns a list of all functions in the current module
Discuss it
Question 6
What is the purpose of the threading module in Python?
 A
To create threads and implement multithreading
 B
To access global variables

 C
To define class variables
 D
To create thread-safe functions
Discuss it
Question 7
What is the purpose of the [Link] function in Python?
 A
To define a partial function
 B
To create a function with fixed arguments
 C
To access global variables
 D
To define a function with default arguments
Discuss it
Question 8
In Python, what is the purpose of the super() function?
 A
To call a method in the parent class
 B
To create a superclass
 C
To access global variables
 D
To declare a variable as super
Discuss it
Question 9
What is the purpose of the __all__ attribute in Python?
 A
To define all global variables
 B
To specify which names should be imported when using from module import *
 C
To list all local variables
 D
To declare all class attributes
Discuss it
Question 10
Which of the following is true regarding the __main__ block in Python?
 A
It is executed when the program is imported as a module
 B
It is executed when the program is run as the main program
 C
It is used to define main functions
 D
It is executed when a function is defined
Discuss it
Question 11
Which of the following is not a valid variable name in Python?
 A
my_variable
 B
1variable
 C
_variable
 D
variable_1
Discuss it
Question 12
What is the purpose of the __file__ attribute in Python?
 A
To get the name of the module
 B
To get the path of the module's source file
 C
To get the creation date of the module
 D
To get the size of the module
Discuss it
Question 13
What is the output of the following code?
x = 10
def func():
global x
x=5
print(x)
func()
print(x)

 A
10
 B
5
 C
15
 D
Error
Discuss it
Question 14
What is the primary purpose of namespaces in Python?
 A
To organize code into modules
 B
To avoid naming conflicts and collisions
 C
To define global variables
 D
To enhance code readability
Discuss it
Question 15
Which of the following is an immutable data type in Python?
 A
List
 B
Tuple
 C
Set
 D
Dictionary
Discuss it
Question 16
What is the purpose of the nonlocal keyword in Python?

 A
To declare a variable as non-local
 B
To access a variable from the global scope
 C
To declare a variable as local
 D
To access a variable from an enclosing (non-global) scope
Discuss it
Question 17
What does the locals() function return in Python?
 A
All global variables
 B
All local variables
 C
Both global and local variables
 D
None of the above
Discuss it
Question 18
What is the purpose of the __init__ method in Python classes?
 A
To initialize the class object
 B
To create a new instance of the class
 C
To define class variables
 D
To destroy the class object
Discuss it
Question 19
How can you access the value of a variable from an outer (non-global) scope in
Python?
 A
Using the outer keyword
 B
Using the enclosing keyword

 C
Using the nonlocal keyword
 D
It is not possible
Discuss it
Question 20
What is the output of the following code?
x = 10
def func():
x=5
print(x)
func()
 A
10
 B
5
 C
15
 D
Error
Discuss it
Python Exception Handling quiz
Last Updated : Apr 2, 2024
Discuss
Comments
Question 1
What is an exception in Python?
 A
A syntax error
 B
A runtime error
 C
A logical error
 D
A compile-time error
Discuss it
Question 2
How can you handle exceptions in Python?
 A
Using if-else statements
 B
Using try-except blocks
 C
Using switch-case statements
 D
Using for loops
Discuss it
Question 3
What is the purpose of the finally block in exception handling?
 A
To define a block of code that will be executed if an exception occurs
 B
To specify the code to be executed regardless of whether an exception occurs or
not

 C
To catch and handle specific exceptions

 D
To raise a custom exception

Discuss it
Question 4
Which of the following statements is used to raise a custom exception in Python?
 A
throw
 B
raise
 C
catch
 D
except
Discuss it
Question 5
What will be the output of the following code?
try:
result = 10 / 0
except ZeroDivisionError:
result = "Infinity"
print(result)

 A
10
 B
"Infinity"
 C
ZeroDivisionError
 D
None
Discuss it
Question 6
What is the purpose of the else block in exception handling?
 A
To handle exceptions
 B
To specify code that will be executed if no exceptions are raised
 C
To define custom exceptions
 D
To skip the execution of the block if an exception occurs
Discuss it
Question 7
How can you catch multiple exceptions in a single except block?
 A
Using a comma-separated list of exceptions
 B
Using nested try-except blocks
 C
By defining a custom exception
 D
Using the catch keyword
Discuss it
Question 8
What is the purpose of the assert statement in Python exception handling?
 A
To catch and handle exceptions
 B
To raise a custom exception
 C
To check if a given expression is true, otherwise raise an 'AssertionError'
 D
To ignore exceptions
Discuss it
Question 9
What does the finally block execute if an exception is raised and not caught?
 A
It doesn't execute
 B
It executes before the exception is raised
 C
It executes after try/except blocks
 D
It executes only if the exception is caught
Discuss it
Question 10
What is the purpose of the with statement in Python exception handling?
 A
To create a new exception
 B
To simplify resource management using context managers
 C
To catch and handle exceptions
 D
To define a custom exception
Discuss it
Question 11
How can you handle uncaught exceptions globally in Python?
 A
By defining a custom global exception handler function and assigning it to
[Link]
 B
Using the 'global_exception_handler()' function

 C
By using the 'global' keyword
 D
There is no way to handle exceptions globally
Discuss it
Question 12
In Python, what does the sys.exc_info() function return?
 A
The exception type
 B
The exception value
 C
A tuple containing the exception type, value, and traceback
 D
A dictionary containing exception information
Discuss it
Question 13
What is the purpose of the raise statement in Python?
 A
To raise an arbitrary exception
 B
To terminate the program
 C
To catch an exception
 D
To ignore an exception
Discuss it
Question 14
What will happen if an exception is raised but not caught in a Python program?
 A
The program will terminate abruptly
 B
The program will continue to execute without any impact
 C
The program will print an error message and continue
 D
The program will prompt the user to handle the exception
Discuss it
Question 15
How can you re-raise an exception in Python?
 A
Using the retry statement
 B
Using the throw statement
 C
Using the raise statement without any arguments
 D
Using the rethrow keyword
Discuss it
Question 16
Which of the following is the correct syntax to catch an exception and store its details
in a variable?
 A
except Exception e:
 B
except Exception, e:
 C
catch Exception as e:
 D
except Exception as e
Discuss it

Python File handling quiz


Last Updated : Apr 2, 2024
Discuss
Comments
Question 1
What is the output of the following code snippet?
with open("[Link]", "r") as file:
content = [Link]()
print(content)

 A
Prints the content of "[Link]"
 B
Raises a FileNotFoundError
 C
Prints "None"
 D
Raises a PermissionError
Discuss it
Question 2
What is the purpose of the 'a+U' mode in file opening?
 A
Append and Unicode support
 B
Access and Universal newline support
 C
Add and Update
 D
Append and Update

Discuss it
Question 3
Which method is used to return the current position of the file cursor?
 A
[Link]()
 B
get_cursor_position()
 C
[Link]()
 D
cursor_location()
Discuss it
Question 4
What does the following code snippet do?
import os
if [Link]("[Link]"):
[Link]("[Link]")

 A
Removes the file "[Link]"
 B
Checks if "[Link]" exists
 C
Creates a new file "[Link]"
 D
Renames "[Link]" to a different name
Discuss it
Question 5
How do you copy the content of one file to another in Python?
 A
copy_file()
 B
[Link]()
 C
[Link]()
 D
copy_to()
Discuss it
Question 6
What does the 'a+b' mode stand for in file opening?
 A
Append and Binary
 B
Access and Backup
 C
Append and Backup
 D
Access and Binary
Discuss it
Question 7
Which method is used to move the cursor to a specific position in a file?
 A
[Link]()
 B
move_cursor()
 C
cursor_position()
 D
set_position()
Discuss it
Question 8
How do you check if a file is writable in Python?
 A
[Link]()
 B
[Link]()
 C
[Link](file, os.W_OK)
 D
file.is_writable()
Discuss it
Question 9
Which of the following code snippets opens a file named "[Link]" in write mode
and writes "Hello, World!" to it?
 A
[Link]("Hello, World!")
 B
with open("[Link]", "w") as file: [Link]("Hello, World!")
 C
open("[Link]", "w").write("Hello, World!")
 D
open("[Link]", "r").write("Hello, World!")
Discuss it
Question 10
What does the following code snippet do?
with open("[Link]", "a") as file:
[Link]("New data")

 A
Reads the content of "[Link]"
 B
Appends "New data" to "[Link]"
 C
Creates a new file "[Link]"
 D
Replaces the content of "[Link]" with "New data"
Discuss it
Question 11
What is file handling in Python?
 A
Managing folders
 B
Reading and writing file
 C
Controlling system files
 D
Handling exceptions in files
Discuss it
Question 12
How can you write data to a file without overwriting its existing content in Python?
 A
Open the file with mode 'w' and call write()
 B
Open the file with mode 'a' and call write()
 C
Use file.write_append()
 D
Use [Link]('a')
Discuss it
Question 13
How do you read a file line by line in Python?
 A
read_all_lines()
 B
file.read_line()
 C
readlines()
 D
read_line(file)
Discuss it
Question 14
What is the purpose of the 'with' statement in file handling?
 A
It creates a new file
 B
It automatically closes the file
 C
It appends data to a file
 D
It reads the entire file at once
Discuss it
Question 15
How do you check if a file exists before opening it in Python?
 A
check_file_existence()
 B
file_exists()
 C
[Link]()
 D
verify_file()
Discuss it
Question 16
How can you read the first five characters of a file in Python?
 A
[Link](5)
 B
read(file, 5)
 C
read_first(file, 5)
 D
file.read_first(5)
Discuss it
Question 17
What is the purpose of the 'a' mode in file opening?
 A
Append
 B
Add
 C
Access
 D
Assign
Discuss it
Question 18
What is the purpose of the 'rb' mode in file opening?
 A
Read binary
 B
Replace binary
 C
Read and backup
 D
Rename binary
Discuss it
Question 19
Which method is used to read the entire content of a file as a string?
 A
read()
 B
read_all()
 C
read_full()
 D
readfile()
Discuss it
Question 20
Which function is used to open a file in Python?
 A
open_file()
 B
read_file()
 C
file_open()
 D
open()
Discuss it

Common questions

Powered by AI

The 'continue' statement in a Python for loop skips the remaining code inside the loop for the current iteration and moves to the next iteration. It does not terminate the loop but skips over any subsequent actions inside the loop block, effectively short-circuiting the iteration cycle to begin anew. For example, in the loop 'for i in range(5): if i == 3: continue print(i)', the number 3 will not be printed because 'continue' is triggered when 'i' equals 3, and thus, 'print(i)' is skipped for that iteration .

In Python, you can iterate over a dictionary's keys and values simultaneously by using the 'items()' method within a for loop. This method provides key-value pairs as tuples that can be unpacked directly in the loop statement. For example: 'for key, value in dictionary.items():'. This approach allows you to perform operations using both the key and value during each iteration of the loop .

To reverse a string using a for loop in Python, you can iterate over the string from its last character to the first, appending each character to a new string. Alternatively, you can utilize 'reversed()' to iterate in reverse order directly. Compared to using slicing (string[::-1]), a for loop explicitly constructs the reversed string, potentially using more memory due to the creation of intermediate variables. In contrast, slicing is often optimized and can be more memory-efficient, especially for large strings as it may involve less overhead in terms of operation execution .

Tuple assignment, also known as unpacking, allows multiple variables to be assigned values from a tuple (or an iterable) in a single statement, making it particularly useful in iteration contexts. Within a loop, this can be seen when iterating over items returned by functions like 'enumerate()' or 'items()', where the tuple returned can be unpacked directly into separate variables. Regular assignment in Python involves assigning a value to a single variable and does not inherently support multiple assignments in a single statement. Tuple unpacking provides the advantage of succinctly handling multiple values without the need for indexing or separate assignment statements .

The 'break' statement terminates the current loop prematurely, skipping any code that follows within that loop iteration, and transfers control to the statement following the terminated loop. When combined with an 'else' clause in a loop, the 'else' block executes only if the loop completes all its iterations without the 'break' statement being triggered. In essence, the 'else' block acts as a post-loop operation that only runs when the loop exits normally (without interruption from a 'break').

The 'else' clause in a Python for loop serves as a block of code that executes after the loop completes its iterations, provided the loop did not encounter a 'break' statement. Its primary role is to run additional code when the loop has not been exited prematurely. This construct allows seamless extension of loop functionality. For example, in a search loop, the 'else' can handle a scenario when no elements match the search criteria, thus concluding the operation with specific logic when all items have been checked .

List comprehension in Python is a concise way to create lists using a single line of code by defining the elements that should be included in the list. It consists of brackets containing an expression followed by a for clause, which can be followed by additional for or if clauses. This enables the transformation or filtering of iterables efficiently. Nested comprehensions allow for more complex transformations such as creating multidimensional lists or processing elements that require multiple levels of iteration. For example, 'matrix = [[i * j for j in range(5)] for i in range(5)]' generates a list of lists where each sub-list is created by multiplying a row number by column numbers .

A 'while' loop is preferable when the number of iterations is not known beforehand and is instead dependent on a specific condition being true. Unlike 'for' loops that are generally used when iterating over a sequence with a known length (such as a list or range), 'while' loops run based on a condition that must initially be true and continue until that condition becomes false. For instance, a 'while' loop is ideal for continuously prompting a user for input until they provide a valid response, as the loop may need to iterate an indeterminate number of times before receiving the appropriate input .

Exception handling in Python, done using the 'try-except' block, allows a programmer to catch and manage exceptions (errors) that occur during the execution of a program, preventing crashes and enabling the program to continue running. In contrast, normal code execution proceeds uninterrupted unless an uncaught exception arises, at which point it stops. The 'try' block contains code that might trigger an exception, while the 'except' block contains code that runs if that exception occurs, facilitating graceful error handling and recovery .

The 'append()' and 'extend()' methods in Python provide ways to expand list objects but differ in their operation. The 'append()' method adds its argument as a single element to the end of the list, potentially increasing the nesting level if the argument is a list. In contrast, 'extend()' iterates over its argument and adds each element to the list, thereby flattening any iterable provided. Consequently, 'extend()' is generally preferred when appending multiple elements or iterables, as it avoids creating nested lists .

You might also like