Python MCQs

Test your Python knowledge with these multiple-choice questions (MCQs). Explore a variety of topics including Python syntax, data types, control structures, functions, and more. Challenge yourself and enhance your Python skills by answering these thought-provoking questions.

1. What is the keyword for defining a function?
A. function
B. define
C. def
D. func

The answer is C:

Explanation: In Python, the keyword for defining a function is def. When creating a function, you use the def keyword followed by the function name, a pair of parentheses, and a colon. Here’s an example:
def my_function(): print("Hello from a function")

2. How do you comment a single line in Python?
A. hash
B. slash
C. double Slash
D. dot

The answer is A:

Explanation: In Python, you can create single-line comments to add explanatory notes or descriptions within your code. These comments are ignored by the interpreter and are meant for human readers. Here are a couple of ways to write single-line comments:

  1. Using the # Symbol:
    • The most common way to create a single-line comment is by using the # symbol.
    • Place the # symbol at the beginning of the line, followed by your comment text.
    • Example:Python# This is a single-line comment in Python x = 5 # Assigns the value 5 to x

3. Which operator is used for exponentiation?
A. Star
B. Carat
C. Double Star or Double asterisk
D. Exponent

The Answer is C:

Explanation: In Python, the operator used for exponentiation is the double asterisk (**). You can raise a number to a power using this operator.

For instance:

To calculate 2 raised to the power of 3, you would write 2 ** 3, which results in 812.
Remember that the ** operator has a higher precedence than most other operators in Python, so it’s essential to grasp operator precedence when working with exponents23. 🐍💡

4. What is the output of print(“Hello” + “World”)?
B. HelloWorld
C. Helloworld
D. Hello+World

The Answer is B:

Explanation: The output of print(“Hello” + “World”) in Python would be the concatenated string: “HelloWorld”.
When you use the + operator with two strings, Python combines them into a single string by joining them together. In this case, it combines the string “Hello” with the string “World” to form the complete word “HelloWorld.” 🐍🌎

5. What data type is used to store a sequence of characters?
A. str
B. chr
C. seqchar
D. character

The Answer is A:

Explanation: In Python, the data type used to store a sequence of characters is the string (or str) data type. Strings represent text and can contain letters, numbers, spaces, punctuation, and special characters. They are enclosed in either single or double quotes, and each character within the string contributes to the sequence45. Whether it’s a single character or an entire sentence, Python treats it as a string. 🐍📜

6. How do you define an empty list in Python?
A. Empty List
B. []
C. list()
D. Novalue

The Answer is B:


In Python, an empty list is represented by a pair of open and close square brackets, like this: []. You can also refer to an empty list as a null list. The key point to remember is that an empty list contains no elements. It serves as a container for data that you can add to later.

Here are two ways to declare an empty list in Python:

Using Square Brackets:
You can create an empty list by simply placing a sequence inside square brackets: [].

my_empty_list = []
print(“Values of my_empty_list:”, my_empty_list)
print(“Type of my_empty_list:”, type(my_empty_list))
print(“Size of my_empty_list:”, len(my_empty_list))

Values of my_empty_list: []
Type of my_empty_list:
Size of my_empty_list: 0

7. Which loop is used for iterating over a sequence (e.g., list, tuple)?
A. while
B. for
C. foreach
D. repeat

The Answer is B.


When iterating over a sequence such as a list or a tuple in Python, the most commonly used loop is the for loop. Let’s explore how the for loop works for different types of sequences:

For Loop with Lists:
A list is a mutable collection of items enclosed in square brackets. To iterate over a list, you can use the for loop with the in keyword:

my_list = [“Geeks”, “for”, “Geeks”]
for item in my_list:


8. What is the result of 5 % 2?
A. 1
B. 2
C. 0
D. 3

The Answer is A:

Explanation: The result of 5 % 2 is 1. In mathematical terms, this operation represents the remainder when dividing 5 by 2. 🧮💡

9. How do you check if a variable is of a certain type?
A. type()
B. instance()
C. is
D. check

The Answer is A.


  • The type() function returns the type of an object.
  • For example:Pythoni = 123 print(type(i)) # Output: <class 'int'> print(type(i) is int) # Output: True

10. Which built-in function is used to get the length of a list?
A. length
B. count
C. len
D. size

The Answer is C:

len() Function:

  • The len() function returns the number of elements in a list. It’s a straightforward and commonly used method.
  • Example:Python my_list = [10, 20, 30, 40] length = len(my_list) print(f"The length of the list is: {length}")

11. What is the purpose of the if statement in Python?
A. condition
B. loop
C. function
D. control

The Answer is A:

Conditional Execution:

  • The if statement allows you to execute a block of code only when a specific condition is true.
  • The basic syntax is as follows: if condition: # Code to execute if condition is true

12. How do you remove an item from a list in Python?
A. remove
B. delete
C. erase
D. extract

The Answer is A:

  • The remove() method allows you to remove an element from a list based on its value.
  • Syntax: my_list = ['apple', 'banana', 'cherry'] my_list.remove('banana') # Removes 'banana' from the list

13. Which of the following is a mutable data type in Python?
A. int
B. str
C. list
D. tuple

The Answer is C:

Lists: Lists are mutable. You can change their contents (add, remove, or modify elements) after creating them

14. How do you define a dictionary in Python?
A. {}
B. []
C. dict()
D. dict

The Answer is A.

  • The most common way to create a dictionary is by enclosing key-value pairs within curly braces.
  • Separate each pair with a comma.
  • The syntax is: dict_var = {key1: value1, key2: value2, ...}
  • Example: my_dict = {'name': 'Alice', 'age': 30, 'city': 'Wonderland'}

15. What is the result of 4 * 3?
A. 7
B. 12
C. 3
D. 6

The Answer is B:

The result of (4 \times 3) is 12. 🧮

16. What is the correct way to import a module in Python?
A. load
B. include
C. import
D. from

The Answer is C:

The most straightforward way is to use the import keyword followed by the module name.

17. Which method is used to add an element to a set in Python?
A. add
B. insert
C. append
D. push

The Answer is A:

add() Method:

  • The add() method allows you to append a single element to a set.
  • It accepts an element as an argument and adds it to the set if it’s not already present.

18. How do you round a floating-point number to the nearest integer in Python?
A. floor
B. ceil
C. round
D. int

The Answer is C:

The round() function rounds a floating-point number to the nearest integer.

19. What is the primary purpose of a docstring in Python?
A. test
B. comment
C. documentation
D. explain

The Answer is C:

In Python, a docstring (short for “documentation string”) serves as a formal way to document code. It provides essential information about modules, functions, classes, or methods.

20. Which operator is used to check if two values are equal in Python?
A. =
B. ==
C. ===
D. !=

The Answer is B:

In Python, the operator used to check if two values are equal is the equality operator, denoted by ==. When you use ==, it compares the values of the two objects and returns True if they are equivalent. 


x = 42
y = 42

if x == y:
    print("x and y are equal")
    print("x and y are not equal")

21. What is the output of print(“Python”[-1])?
A. p
B. n
C. o
D. h

The Answer is B:

Explanation: The output of print(“Python”[-1]) in Python is the last character of the string “Python,” which is the letter “n”. When you use negative indices in Python, it counts from the end of the string. So, [-1] refers to the last character, [-2] would be the second-to-last character, and so on.

22. How do you open a file for writing in Python?
A. open(“file.txt”, “r”)
B. open(“file.txt”, “w”)
C. open(“file.txt”, “a”)
D. open(“file.txt”, “x”)

The Answer is B:

Explanation: To open a file for writing in Python, you can use the open() function with the mode argument set to 'w'.

  • If the file already exists, opening it in write mode (‘w’) will overwrite any existing content.
  • Example: f = open('myfile.txt', 'w') # Write your content here f.close() # Remember to close the file

23. What does the continue statement do in a loop?
A. Breaks the loop
B. Skips the current iteration
C. Halts the program
D. Does nothing

The Answer is B:

Explanation: When encountered inside a loop, it skips the current iteration and immediately moves to the next iteration without executing the remaining statements within the loop for that particular iteration

24. Which method is used to find the maximum value in a list in Python?
A. max()
B. maximum()
C. find_max()
D. min()

The Answer is A:


To find the maximum value in a Python list, you can use the max() method. This method returns the largest element present in the list. Let’s explore how it works:

  1. Syntax: max_value = max(list_name)
  2. Parameters:
    • list_name: The name of the list from which you want to find the maximum value.
  3. Return Value:
    • It returns the maximum value present in the list.
  4. Examples:
    • Suppose we have a list of integers: numbers = [54, 67, 12, 33, 69, 32] print(max(numbers)) # Output: 69

25. What is the purpose of the __init__ method in a class?
A. Initialize the object
B. Define class methods
C. Terminate the object
D. Modify the object

The Answer is A:


The __init__ method in Python plays a crucial role when creating class instances. Let’s delve into its purpose:

  1. Initialization and Construction:
    • The __init__ method is akin to a constructor in languages like C++ and Java.
    • When you create an object (instance) of a class, the __init__ method is automatically called.
    • Its primary purpose is to initialize the object’s attributes (also known as data members) when the object is instantiated.
  2. Assigning Initial Values:
    • Within the __init__ method, you can accept arguments (such as self and other parameters) and use them to assign initial values to the object’s attributes.
    • These attributes represent the state of the object and can be accessed throughout the class.
  3. Example:
    • Let’s consider a simple class called Person: class Person: def __init__(self, name): = name def say_hi(self): print('Hello, my name is', p = Person('Nikhil') p.say_hi() # Output: Hello, my name is Nikhil
  • In this example:
    • We create a Person object named “Nikhil.”
    • The __init__ method initializes the name attribute with the provided argument.
    • The say_hi method prints a greeting using the name attribute.
  • Inheritance and __init__:
  • Inheritance allows one class to derive properties from another.
  • When using inheritance, the child class’s __init__ method can call the parent class’s __init__ method.
  • Example: class A: def __init__(self, something): print("A init called") self.something = something class B(A): def __init__(self, something): A.__init__(self, something) print("B init called") self.something = something obj = B("Something") # Output: A init called # B init called
    • The parent class constructor (A.__init__) is called first, followed by the child class constructor (B.__init__).

Remember, the __init__ method is essential for initializing object attributes and ensuring proper setup when creating instances of a class. Happy coding! 😊🐍

26. Which keyword is used to exit a loop prematurely in Python?
A. stop
B. exit
C. break
D. quit

The Answer is C:

In Python, the keyword used to exit a loop prematurely is break. When encountered inside a loop, the break statement immediately terminates the loop, and program control transfers to the next statement following the loop. It’s like finding the emergency exit in a maze of code! 🚪🔍

For example, consider the following loop structure:


for i in range(10):
    if i == 5:
        break  # Exit the loop when i equals 5

27. How do you create a copy of a list in Python without modifying the original list?
A. clone()
B. duplicate()
C. copy()
D. replicate()

The Answer is C:

  • The copy() method creates a shallow copy of the list (i.e., a new list containing references to the same objects).
  • Example: import copy original_list = [1, 2, [3, 5], 4] cloned_list = copy.copy(original_list) print(cloned_list)

28. What is the output of bool(“False”)?
A. True
B. False
C. Error
D. None

The Answer is A:

The output of bool("False") in Python is True.

Here’s why:

  • The bool() function converts a value to a Boolean value (either True or False) using the standard truth testing procedure.
  • When you pass the string "False" to bool(), it evaluates as True because it is a non-empty string. In Python, any non-empty value (except for specific cases like 0None, and empty sequences) is considered True.
  • So, even though the string contains the word “False,” it is not the same as the Boolean value False.

Remember, in Python, the bool() method follows specific rules for truthiness and falsiness, so be cautious when converting values! 🐍🔍

29. How do you define a tuple with a single element?
A. (1)
B. 1
C. (1,)
D. [1]

The Answer is C:

To define a tuple with a single element in Python, you can use the following approaches:

  1. Using a Comma:
    • The most straightforward way is to add a comma after the element. Even if there’s only one element, the trailing comma is essential to create a valid tuple.
    • Example: single_element_tuple = (42,) print(single_element_tuple) # Output: (42,) print(type(single_element_tuple)) # Output: <class 'tuple'>

30. Which operator is used for logical “or” in Python?
A. &
B. |
C. ||
D. or

The Answer is D:


In Python, the logical “or” operation is performed using the or operator. This operator evaluates to True if either of the operands is True. Let’s explore some examples:

  1. Using the or operator:
    • If at least one of the conditions is True, the entire expression evaluates to True.
    • Example: x = 5 y = 10 result = (x > 7) or (y < 15) print(result) # Output: True.

Remember, the or operator helps you make decisions based on multiple conditions! 🐍🔍

31. What is the result of 3 ** 2 in Python?
A. 9
B. 6
C. 12
D. 27

The Answer is A:


Python operators usually evaluate from left to right, except for the exponentiation operator. When you have multiple exponentiation operators in an expression, they group from right to left. So, the expression 3 ** 2 is equivalent to 3 ** (2 ** 1), which simplifies to 3 ** 2, resulting in 9

32. How do you check if a key exists in a dictionary in Python?
A. key()
B. exists()
C. in
D. has_key()

The Answer is C:


Using the in Operator: The most straightforward way is to use the in operator. You can check if a specific key exists in a dictionary like this: y_dict = {'apple': 5, 'banana': 3, 'cherry': 8} if 'banana' in my_dict: print("The key 'banana' exists in the dictionary.")

33. What is the purpose of the else statement in an if condition?
A. Execute a different block of code
B. Check another condition
C. Terminate the program
D. Always run the code

The Answer is B

34. Which method is used to remove the last element from a list in Python?
A. pop()
B. remove()
C. delete()
D. shift()

The Answer is A:


  • The pop() method is the most straightforward way to remove the last element from a list.
  • It accepts an optional index argument (which specifies the position to remove), but if no index is provided, it removes the last item by default.
  • Example:my_list = [10, 20, 30, 40, 50] my_list.pop() # Removes the last element (50) print(my_list) # Output: [10, 20, 30, 40]

35. How do you create a set in Python?
A. set()
B. {}
C. SET[]
D. set{}

The Answer is A:

36. What is the output of print(3/2)?
A. 1.5
B. 2
C. 1
D. 1.0

The Answer is A:


The expression 3 / 2 in Python evaluates to approximately 1.5. Let me explain why:

  1. Floating-Point Division:
    • When you divide two integers using the / operator, Python performs floating-point division.
    • In this case, 3 and 2 are both integers, so the result is a floating-point number.
    • The division result is the quotient of the numerator divided by the denominator.
    • Mathematically: (3 / 2 = 1.5).
  2. Output with print():
    • To display the result, you can use the print() function: print(3 / 2) # Output: 1.5 AI-generated code. Review and use carefully.

Remember that Python automatically handles the data type conversion when performing arithmetic operations! 🐍🔢

37. What is the correct syntax for a single-line comment in Python?
A. /* comment */
B. // comment
C. # comment
D. <!– comment –>

The Answer is C:


In Python, you can create single-line comments using the hash symbol (#). These comments provide brief explanations or notes within your code. Here’s how to use them:

  1. Basic Syntax:
    • To write a single-line comment, simply start a line with #, followed by your comment text.
    • The interpreter ignores everything after the # symbol on that line.
    • Example:# This is a single-line comment in Python print("Hello, World!")

38. Which keyword is used to define a function in Python?
A. function
B. define
C. def
D. func

The Anser is C:

Explanation: In Python, the keyword used to define a function is def. When creating a function, you start with the def keyword, followed by the function name of your choosing, a set of parentheses (which can be empty or contain parameters), and finally, a colon. 

Here’s a simple example of defining a function:


def greet(name):
    """Prints a friendly greeting."""
    print(f"Hello, {name}!")

# Calling the function

In this example:

  • We define a function named greet using def.
  • The function takes one parameter (name).
  • The indented block below the def line contains the code to greet the specified name.
  • When we call greet("Alice"), it prints “Hello, Alice!”.

Remember, the def keyword is essential for creating reusable and modular code in Python! 🐍📝

39. How do you remove all elements from a list in Python?
A. empty()
B. clear()
C. remove_all()
D. erase()

The Answer is B:


  • The clear() method is the most straightforward way to empty a list.
  • When invoked on a list, it removes all the elements, leaving an empty list.
  • Example: my_list = [1, 2, 3, 4, 5] my_list.clear() print(my_list) # Output: []

40. What is the purpose of the finally block in a try-except statement?
A. Handle exceptions
B. Execute code regardless of exceptions
C. Ignore exceptions
D. Exit the program

The Answer is B:


The finally block in a Python try-except statement serves a crucial purpose. Let’s explore its role:

  1. Ensuring Cleanup and Resource Release:
    • The finally block ensures that a specific piece of code executes regardless of whether an exception occurs within the associated try block.
    • It is particularly useful for activities such as:
      • Releasing resources: For example, closing files, database connections, or network sockets.
      • Performing cleanup tasks: Ensuring that temporary files are deleted or other necessary cleanup actions are taken.

41. What is the result of 5 / 2 in Python?
A. 2.5
B. 2
C. 2.0
D. 2.2

The Answer is A


In Python, the expression 5 / 2 results in 2.5. This is because the “/” operator performs floating point division, which yields a decimal result. If you were to use the “//” operator instead, it would perform floor division (also known as integer division), resulting in 2.

To summarize:

  • 5 / 2 → 2.5 (floating point division)
  • 5 // 2 → 2 (floor division)

Remember, the choice between “/” and “//” depends on whether you want a decimal or an integer result! 🐍🔢

42. How do you convert a string to lowercase in Python?
A. str.lower()
B. toLower()
C. str.lowercase()
D. lower.str()

The Answer is A

43. Which operator is used for membership testing in Python?
A. in
B. exists
C. contains
D. has

The Answer is A:


In Python, the membership operators are used to test whether a sequence is present in an object. There are two membership operators:

  1. in: This operator returns True if a specified value is found in the sequence, and False otherwise. For example: x = [1, 2, 3] y = 2 result = y in x # Returns True
  2. not in: This operator returns True if a specified value is not found in the sequence, and False otherwise. For example: x = [1, 2, 3] y = 4 result = y not in x # Returns True

44. What is the purpose of the pass statement in Python?
A. Print a message
B. Terminate the program
C. Do nothing
D. Execute a function

The Answer is C:

45. How do you remove leading and trailing whitespace from a string in Python?
A. trim()
B. strip()
C. remove_whitespace()
D. clean()

The Answer is B:


  • The strip() method removes spaces, tabs, and newline characters from the beginning and end of a string.
  • If you don’t provide any argument to strip(), it will default to removing all whitespace characters.
  • Example: s = "\tHi, how are you?\n " new_s = s.strip() print(new_s) # Output: "Hi, how are you?"
Scroll to Top