Python Online Test - 100 MCQ Questions

This Python Online Test simulates a real online certification exam. You will be presented with 100 Multiple-Choice Questions (MCQs) based on Python fundamental and advanced concepts, and you will be given four options. You will select the correct answer for each question and finally submit the test. Once you submit the Test, you will receive your score, correct answer, and more.

1. What does the len() function return when applied to a dictionary?

a) The number of keys
b) The number of values
c) The number of items (key-value pairs)
d) None of the above

2. Which of the following data types is immutable?

a) List
b) Set
c) Tuple
d) Dictionary

3. What is slicing in Python?

a) Changing the data type of a variable
b) A method to cut objects into half
c) Creating a new list from a current list
d) A way to access parts of sequential data types like lists or strings

4. What is the output of 1 == “1”?

a) True
b) False
c) Error
d) None

5. How do you add an element to a set in Python?

a) .append()
b) .add()
c) .insert()
d) .extend()

6. Which function in Python can generate a sequence of numbers?

a) range()
b) sequence()
c) list()
d) num()

7. What does the continue keyword do in a loop?

a) Pauses the loop
b) Exits the loop
c) Skips the rest of the code inside the loop for the current iteration
d) None of the above

8. How do you catch exceptions in Python?

a) try...except
b) try...catch
c) error...except
d) error...handle

9. What is the output of the following code snippet: print(2 ** 3)?

a) 6
b) 8
c) 9
d) 5

10. Which of the following is correct to create a list?

a) [1, 2, 3]
b) {1, 2, 3}
c) (1, 2, 3)
d) "123"

11. What is the correct way to import a module named time?

a) import "time"
b) import time
c) #import time
d) @import time

12. What does the split() method do to a string?

a) Divides the string at each white space
b) Splits the string into characters
c) Joins two strings together
d) None of the above

13. Which keyword is used to create a function in Python?

a) func
b) def
c) function
d) method

14. What is the result of list("hello")?

a) ['h', 'e', 'l', 'l', 'o']
b) ['hello']
c) 'h', 'e', 'l', 'l', 'o'
d) (‘h’, ‘e’, ‘l’, ‘l’, ‘o’)

15. Which method is used to add an element at the end of a list?

a) append()
b) extend()
c) insert()
d) add()

16. What does the pass statement do in Python?

a) It passes execution rights to another user
b) It fails silently without doing anything
c) It is a null statement that does nothing
d) It passes the loop to start over

17. What keyword is used to define a variable that can hold multiple values?

a) var
b) val
c) list
d) tuple

18. How can you generate random numbers in Python?

a) random()
b) import random
c) random.random()
d) import random and then random.random()

19. What does the strip() method do?

a) Reverses a string
b) Removes specific characters from the beginning and the end of the string
c) Splits the string into a list of strings
d) Concatenates strings

20. How do you open a file in read mode in Python?

a) open("file.txt", "r")
b) open("file.txt", "read")
c) open.file("file.txt", "r")
d) file.open("file.txt", "r")

21. What is the output of this code snippet: print("Hello, world!".upper())?

a) hello, world!
b) HELLO, WORLD!
c) Hello, World!
d) None of the above

22. Which data type would you use to store a numeric value that does not change?

a) Variable
b) Constant
c) int
d) float

23. Which of these collections is ordered and changeable, and allows duplicate members?

a) Tuple
b) Set
c) Dictionary
d) List

24. What error is caused by trying to access a non-existent dictionary key?

a) KeyError
b) ValueError
c) SyntaxError
d) TypeError

25. What type of data is returned by input() function?

a) int
b) bool
c) str
d) list

26. What is the output of print("Python"[1:4])?

a) P
b) Pyt
c) yth
d) Python

27. What is the correct way to create a dictionary?

a) {1:"apple", 2:"banana"}
b) [1:"apple", 2:"banana"]
c) (1:"apple", 2:"banana")
d) {"1":"apple", "2":"banana"}

28. How do you check the type of an object in Python?

a) type()
b) typeof()
c) getType()
d) checkType()

29. What is the output of the following code: print(10 // 3)?

a) 3.333
b) 3
c) 4
d) 0

30. Which module allows you to create regular expressions in Python?

a) regex
b) re
c) regular
d) regexp

31. How do you convert a list to a tuple?

a) tuple()
b) convert()
c) to_tuple()
d) list()

32. What is the term for code isolation in Python?

a) Encapsulation
b) Polymorphism
c) Inheritance
d) Namespace

33. Which Python built-in function returns the highest value in a list?

a) high()
b) max()
c) up()
d) top()

34. What is a correct way to declare a function that returns its argument multiplied by two?

a) def double(x): return 2 * x
b) double = lambda x: 2 * x
c) def double(x): return x * 2
d) All of the above

35. How do you create a set in Python?

a) set = {1, 2, 3}
b) set = [1, 2, 3]
c) set = (1, 2, 3)
d) set = {1: "one", 2: "two"}

36. What is the output of bool(None)?

a) True
b) False
c) None
d) Error

37. Which operator is used in Python to import modules from packages?

a) import
b) from
c) get
d) as

38. What is the output of the following code: 'Hello World'.replace('World', 'Python')?

a) Hello Python
b) Hello World
c) Hello
d) Error

39. How do you handle exceptions that might occur in a program without crashing it?

a) try and except
b) try and handle
c) check and except
d) check and handle

40. What is the use of the else clause in a Python loop?

a) Runs if the loop completes normally
b) Runs if the loop does not complete
c) Runs regardless of how the loop terminates
d) There is no else clause in Python loops

41. What does the following list comprehension do: [x for x in range(5) if x%2 == 0]?

a) Creates a list of all numbers from 0 to 4
b) Creates a list of even numbers from 0 to 4
c) Creates a list of odd numbers from 0 to 4
d) Creates a list of all numbers from 0 to 5

42. What will be the output of the following Python code snippet: print(8 % 3)?

a) 2
b) 2.67
c) 3
d) 0

43. Which operator is used to check if an object is an instance of a particular class or type?

a) ==
b) ===
c) is
d) isinstance()

44. How can you reverse a string in Python?

a) reverse("hello")
b) "hello"[::-1]
c) reversed("hello")
d) flip("hello")

45. What is the output of the following code snippet: type({})?

a) <class 'set'>
b) <class 'dict'>
c) <class 'list'>
d) <class 'tuple'>

46. Which method can be used to convert a JSON string into a Python dictionary?

a) json.loads()
b) json.dumps()
c) json.parse()
d) json.get()

47. How do you convert a string to lowercase in Python?

a) "HELLO".lower()
b) "HELLO".LOWERCASE()
c) lower("HELLO")
d) "HELLO".lowerCase()

48. What is the correct syntax to declare a class named Vehicle in Python?

a) class Vehicle()
b) class Vehicle:
c) create class Vehicle:
d) new class Vehicle:

49. What is the output of the following code: print(bool(""))?

a) True
b) False
c) Error
d) None

50. How do you calculate the number of characters in a string using Python?

a) len("characters")
b) "characters".length()
c) count("characters")
d) size("characters")

51. How do you round a number to two decimal places in Python?

a) round(3.14159, 2)
b) float(3.14159, 2)
c) 3.14159.round(2)
d) math.round(3.14159, 2)

52. What does the * operator do when used with a list in Python?

a) Multiplies the elements
b) Repeats the list
c) Sums the elements
d) Divides the elements

53. What will be the output of the following code: [1, 2, 3] + [4, 5, 6]?

a) [1, 2, 3, 4, 5, 6]
b) [5, 7, 9]
c) [1, 2, 3, 1, 2, 3, 4, 5, 6]
d) Error

54. How do you copy a list in Python to avoid modifying the original?

a) list.copy()
b) copy(list)
c) list()
d) new_list = old_list

55. What is the result of bool(0)?

a) True
b) False
c) 0
d) None

56. How do you find the maximum value in a list of numbers in Python?

a) max([1, 2, 3])
b) [1, 2, 3].max()
c) maximum([1, 2, 3])
d) max(1, 2, 3)

57. What method would you use to find an element in a list?

a) .locate()
b) .index()
c) .find()
d) .search()

58. What is the result of set([1, 2, 2, 3])?

a) [1, 2, 2, 3]
b) {1, 2, 3}
c) {1, 2, 2, 3}
d) Error

59. What does list(set([1, 2, 2, 3])) do?

a) Converts a list to a set and back to list, removing duplicates
b) Sorts the list
c) Counts unique items in the list
d) None of the above

60. How do you check if a key exists in a dictionary?

a) "key" in dict
b) dict.has_key("key")
c) dict.contains("key")
d) "key" exists dict

61. What does the break keyword do in a loop?

a) Pauses the loop
b) Terminates the loop immediately
c) Continues to the next iteration
d) None of the above

62. How is memory management handled in Python?

a) Manually by the programmer
b) Using pointers
c) It is handled by Python's garbage collector
d) Using manual garbage collection

63. What is the purpose of the __init__ method in Python?

a) To initialize memory space for a new object
b) To initialize a new object's attributes
c) To start the interpreter
d) To import libraries

64. What is the output of 9 ** 0.5?

a) 3.0
b) 4.5
c) 9
d) Error

65. How do you express a hexadecimal number 10 in Python?

a) 0x10
b) 10h
c) 0xA
d) #A

66. What is a lambda function in Python?

a) A high-order function that manipulates other functions
b) A small anonymous function defined with the lambda keyword
c) A type of inheritance in Python
d) A function that cannot return values

67. Which module in Python provides tools for handling paths?

a) os.path
b) sys.path
c) pathlib
d) path

68. How can you make a Python script executable on Unix?

a) Add a shebang line at the top of the script, e.g., #!/usr/bin/env python3
b) Compile it using a Python compiler
c) Change the extension to .pyc
d) It is not possible

69. What will be the output of 8/4 in Python 3.x?

a) 2
b) 2.0
c) 4
d) 0

70. What is the difference between deepcopy and copy in Python?

a) deepcopy copies only the reference pointers, while copy creates a new copied object.
b) copy creates a shallow copy of an object, whereas deepcopy creates a deep copy of an object.
c) There is no difference; both functions do the same thing.
d) deepcopy is used for immutable objects, while copy is used for mutable objects.

71. How do you remove all elements from a list in Python?

a) list.empty()
b) list.delete()
c) list.clear()
d) del list[:]

72. What is the correct way to create a complex number in Python?

a) 1 + 2i
b) 1 + 2j
c) complex(1, 2)
d) b and c

73. How do you convert an integer to a string in Python?

a) str(10)
b) string(10)
c) "10"
d) int('10', str)

74. Which function is used to serialize an object to a byte stream in Python?

a) pickle.dump()
b) pickle.load()
c) pickle.dumps()
d) pickle.loads()

75. What is the purpose of decorators in Python?

a) To simplify the syntax of the code
b) To add functionality to an existing function or class
c) To decorate the output in the console
d) To comment out sections of code

76. How do you ensure thread safety when modifying a shared resource?

a) Use the thread module
b) Use the mutex library
c) Use the locking mechanism
d) Use the synchronize keyword

77. Which module provides tools for creating temporary files and directories?

a) tempfile
b) os.temp
c) sys.temp
d) shutil

78. What does the @staticmethod decorator do?

a) Converts a method into a static method, which does not receive the instance as the first parameter
b) Makes a method accessible outside the class without instantiation
c) Synchronizes a method in a multithreaded environment
d) None of the above

79. What is a context manager in Python?

a) A tool used to manage memory context
b) A feature that manages the context in which a script runs
c) A construct that enables resource management, used with the with statement
d) A module that loads and unloads contexts

80. How do you compile a Python script into bytecode, which can be executed more quickly than the source code?

a) Use the py_compile module
b) Use the compile() function
c) Save the script with a .pyc extension
d) Use the cython package

81. Which of the following is the correct way to create a generator in Python?

a) Using square brackets []
b) Using parentheses ()
c) Using the yield keyword in a function
d) Using the generate keyword

82. What does the global keyword do in Python?

a) It declares a variable as global inside a function
b) It imports global variables from different modules
c) It makes a function globally accessible
d) It declares that all variables in the module are global

83. Which module would you use to measure the execution time of small code snippets?

a) timeit
b) timing
c) stopwatch
d) timer

84. What is the difference between @classmethod and @staticmethod in Python?

a) @classmethod can modify class state that applies across all instances of the class, while @staticmethod cannot
b) @staticmethod can access and modify class state, @classmethod cannot
c) There is no difference, they serve the same purpose
d) @staticmethod is used to define a static variable within a method

85. How do you create a named tuple in Python?

a) Use the namedtuple function from the collections module
b) Use the tuple() constructor and specify names
c) Assign names directly in a regular tuple
d) Use the dict() constructor

86. What is monkey patching in Python?

a) Patching the Python interpreter
b) Making changes to a module or class while the program is running
c) A bug fixing process in Python
d) A term used for Python applications that crash unexpectedly

87. Which Python library is used for scientific computing and contains various features including linear algebra, random number generation, and Fourier transforms?

a) NumPy
b) SciPy
c) Math
d) Pandas

88. How do you test that a certain part of the code raises an exception in unit tests?

a) Use assertRaises
b) Use try and except blocks
c) Use with self.assertRaises()
d) Use expectException

89. What is the purpose of the __name__ variable in Python?

a) Shows the name of the current module
b) Stores the main function
c) Indicates whether the module is run as a script or imported
d) None of the above

90. How can you make an HTTP request in Python?

a) Use the requests module
b) Use the http module
c) Use the socket module
d) Use the urllib module

91. What is the output of the expression all([0, 1, 2, 3])?

a) True
b) False
c) None
d) Error

92. What does the @property decorator do in Python?

a) Marks a method as a getter for a property
b) Sets a property that cannot be inherited
c) Sets a property to be static
d) Creates a new property dynamically

93. What are metaclasses in Python?

a) Classes that create other classes
b) A class of methods that are not bound to class instances
c) Python's way of adding metadata to classes
d) Special classes that contain only static methods

94. What is the with statement best described as in Python?

a) A simpler way to handle exceptions
b) A method for modifying Python syntax
c) A syntax for defining anonymous functions
d) A context manager that simplifies exception handling and cleanup

95. How do you create a simple coroutine in Python?

a) Using the async and await keywords
b) Using the yield and send() methods
c) Using the asyncio module
d) All of the above

96. What is type hinting in Python?

a) A way to specify the type of a variable
b) A debugging tool that hints at variable types
c) A style convention
d) A way to force a particular datatype

97. How is a static method defined within a class in Python?

a) def staticmethod(self):
b) static def method():
c) @staticmethod\ndef method():
d) def method(static):

98. What is the GIL in Python?

a) Global Interpreter Lock
b) General Internal Loop
c) Global Initialization Load
d) Generic Input Logger

99. How do you ensure that an object can be garbage collected?

a) Set all references to the object to None
b) Delete the object using del
c) Remove all references to the object
d) Both a and c

100. What is the difference between __str__ and __repr__ in Python?

a) __str__ is used for creating output for end user while __repr__ is mainly used for debugging and development
b) __repr__ is used for creating output for end user while __str__ is mainly used for debugging and development
c) There is no difference; both are used interchangeably
d) __str__ cannot be overridden, while __repr__ can be

Comments