Top Python Fundamentals MCQs & Answers for Beginners

1 min read

Python is a dynamically typed, high-level programming language created by Guido van Rossum in 1991. Renowned for its clear syntax and clean code structure enforced by mandatory block indentation, Python is widely utilized in web development, data science, automation, and artificial intelligence. Mastering basic concepts such as built-in data types (lists, tuples, dictionaries, sets), control structures, functions, and scope is essential for writing efficient code and passing technical assessments. This practice quiz covers fundamental syntax, core data structures, and arithmetic operations. Evaluating these questions will help solidify your foundational knowledge and pinpoint areas for improvement.

1. Who created the Python programming language?

a) Guido van Rossum
b) James Gosling
c) Dennis Ritchie
d) Bjarne Stroustrup
Correct Answer: a) Guido van Rossum
Explanation:
Guido van Rossum created Python in the late 1980s, and it was officially released in 1991.

2. Which of the following is the standard file extension for Python source files?

a) .python
b) .py
c) .pyt
d) .pt
Correct Answer: b) .py
Explanation:
Standard Python code files use the .py extension.

3. Which keyword is used to define a function in Python?

a) func
b) function
c) def
d) define
Correct Answer: c) def
Explanation:
The 'def' keyword introduces a function definition in Python.

4. How are code blocks defined in Python instead of curly braces?

a) Parentheses
b) Indentation
c) Semicolons
d) Square brackets
Correct Answer: b) Indentation
Explanation:
Python uses consistent indentation (whitespace) to delineate blocks of code.

5. Which built-in function prints output to the console?

a) display()
b) echo()
c) write()
d) print()
Correct Answer: d) print()
Explanation:
The print() function sends formatted text or values to standard output.

6. How is a single-line comment written in Python?

a) // This is a comment
b) # This is a comment
c) /* This is a comment */
d)
Correct Answer: b) # This is a comment
Explanation:
Single-line comments start with a hash symbol (#).

7. Which of the following data types is immutable in Python?

a) List
b) Dictionary
c) Tuple
d) Set
Correct Answer: c) Tuple
Explanation:
Tuples are immutable sequences; their values cannot be modified after creation.

8. What is the output of type([]) in Python?

a)
b)
c)
d)
Correct Answer: c)
Explanation:
Square brackets [] denote a list data type.

9. Which operator is used for exponentiation (power) in Python?

a) ^
b) **
c) ^^
d) pwr
Correct Answer: b) **
Explanation:
The double asterisk (**) operator computes power (e.g., 2 ** 3 = 8).

10. What is the output of 7 // 2 in Python?

a) 3.5
b) 3
c) 4
d) 3.0
Correct Answer: b) 3
Explanation:
The // operator performs floor division, truncating fractional parts into an integer.

11. Which function returns the number of items in a sequence or collection?

a) length()
b) count()
c) len()
d) size()
Correct Answer: c) len()
Explanation:
len() returns the total count of elements inside containers like strings, lists, or tuples.

12. Which list method removes and returns the last element by default?

a) remove()
b) pop()
c) delete()
d) discard()
Correct Answer: b) pop()
Explanation:
pop() without arguments removes and returns the end element of a list.

13. What does bool('') evaluate to?

a) True
b) False
c) None
d) Error
Correct Answer: b) False
Explanation:
An empty string is considered falsy in Python boolean context.

14. Which loop structure iterates from 0 through 4?

a) for (i = 0; i < 5; i++)
b) for i in range(5):
c) for i in 5:
d) foreach i in range(0, 5):
Correct Answer: b) for i in range(5):
Explanation:
range(5) generates sequence values from 0 up to, but not including, 5.

15. Which keyword catches exceptions in Python try blocks?

a) catch
b) except
c) trap
d) error
Correct Answer: b) except
Explanation:
Python uses try/except handling constructs to catch exceptions.

16. Which function converts a compatible string into an integer?

a) str()
b) float()
c) int()
d) parse()
Correct Answer: c) int()
Explanation:
int() casts valid numerical inputs or strings to integer data types.

17. Which data structure maps key-value pairs?

a) List
b) Set
c) Dictionary
d) Tuple
Correct Answer: c) Dictionary
Explanation:
Dictionaries store key-value mapping elements within curly braces.

18. Which statement terminates loop execution prematurely?

a) stop
b) exit
c) break
d) return
Correct Answer: c) break
Explanation:
The break keyword exits the current loop execution completely.

19. Which statement skips remaining current loop code and advances to the next iteration?

a) continue
b) skip
c) pass
d) next
Correct Answer: a) continue
Explanation:
continue jumps directly to evaluating the next loop iteration.

20. What is the output of 3 * 'A' in Python?

a) AAA
b) Error
c) 979797
d) 3A
Correct Answer: a) AAA
Explanation:
Multiplying strings by positive integers repeats the text sequence.

21. What does a function return by default if no explicit return statement exists?

a) 0
b) False
c) None
d) Null
Correct Answer: c) None
Explanation:
Python functions implicitly return None if no explicit return value is returned.

22. Which built-in module generates pseudo-random numbers?

a) math
b) random
c) rand
d) numbers
Correct Answer: b) random
Explanation:
The random module supplies functions to generate pseudo-random numbers.

23. Which operator checks if two variables point to the same memory location?

a) ==
b) is
c) equals
d) in
Correct Answer: b) is
Explanation:
The 'is' operator checks identity (whether two references point to identical memory addresses).

24. Which operator tests whether values of two objects are equal?

a) is
b) ==
c) =
d) eq
Correct Answer: b) ==
Explanation:
The '==' operator checks value equality.

25. Which keyword executes logical conjunction in Python?

a) &&
b) &
c) and
d) AND
Correct Answer: c) and
Explanation:
Python uses the English word 'and' for logical operations.

26. How do you construct an empty set in Python?

a) {}
b) set()
c) []
d) ()
Correct Answer: b) set()
Explanation:
Empty curly braces {} build a dictionary; set() constructs an empty set.

27. Which method appends an element at the end of a list?

a) add()
b) insert()
c) append()
d) extend()
Correct Answer: c) append()
Explanation:
append() inserts a single value at the end of an existing list.

28. Which statement acts as a syntactic placeholder doing nothing?

a) skip
b) void
c) pass
d) continue
Correct Answer: c) pass
Explanation:
pass is a null operation; it fulfills structural requirements without running code.

29. What is the output of float(5)?

a) 5
b) 5.0
c) '5.0'
d) Error
Correct Answer: b) 5.0
Explanation:
float() converts integers into floating-point numbers with decimal representation.

30. Which negative index accesses the final item in a Python sequence?

a) 0
b) last
c) -1
d) len()-1
Correct Answer: c) -1
Explanation:
Negative index -1 points to the last item.

31. Which slice expression reverses a string 's'?

a) s[0:-1]
b) s[::-1]
c) s[reverse]
d) s[-1:0]
Correct Answer: b) s[::-1]
Explanation:
A negative step value of -1 traverses a sequence in reverse direction.

32. Which method returns a lowercase version of a string?

a) toLower()
b) lowercase()
c) lower()
d) casefold_all()
Correct Answer: c) lower()
Explanation:
lower() converts upper characters in strings into lower case.

33. Which function lists attributes and methods available on an object?

a) help()
b) dir()
c) info()
d) reflect()
Correct Answer: b) dir()
Explanation:
dir() inspects objects and returns valid attributes.

34. Which block ensures automatic file closure after executing code operations?

a) using open('file.txt') as f:
b) with open('file.txt') as f:
c) open('file.txt').auto_close()
d) file f = open('file.txt')
Correct Answer: b) with open('file.txt') as f:
Explanation:
The with statement uses context managers to automatically release file handles.

35. Which standard library module handles regular expressions?

a) regex
b) re
c) string
d) parse
Correct Answer: b) re
Explanation:
The re module implements regular expression matching operations.

36. Which keyword imports modules into Python scripts?

a) include
b) require
c) import
d) using
Correct Answer: c) import
Explanation:
The import keyword loads modules and namespaces.

37. What is the function of __init__() in Python classes?

a) To initialize module dependencies
b) To initialize object instance attributes upon instantiation
c) To delete instance memory
d) To return string representations
Correct Answer: b) To initialize object instance attributes upon instantiation
Explanation:
__init__() works as a constructor method initializer when instantiating object instances.

38. Which parameter must explicitly be the first argument in standard instance methods?

a) this
b) self
c) cls
d) super
Correct Answer: b) self
Explanation:
self represents the reference of the current object instance inside class methods.

39. Which of these expressions creates a float variable equal to 10?

a) x = float(10)
b) x = 10.0
c) Both a and b
d) x = 10f
Correct Answer: c) Both a and b
Explanation:
10.0 and float(10) both initialize float objects with value 10.0.

40. What is the output of print(10 % 3)?

a) 3
b) 1
c) 0
d) 3.33
Correct Answer: b) 1
Explanation:
The modulo operator (%) yields remainder values (10 divided by 3 has remainder 1).

41. Which exception arises when dividing numbers by 0?

a) NullPointerError
b) ZeroDivisionError
c) ArithmeticError
d) ValueException
Correct Answer: b) ZeroDivisionError
Explanation:
ZeroDivisionError triggers when division or modulo operations use 0 as divisor.

42. Which string formatting styles utilize curly brace {} placeholders?

a) % formatting
b) format() method
c) f-strings
d) Both b and c
Correct Answer: d) Both b and c
Explanation:
str.format() and f-strings both use curly braces for variable interpolation.

43. What does print('Hello' + 'World') produce?

a) Hello World
b) HelloWorld
c) Hello+World
d) TypeError
Correct Answer: b) HelloWorld
Explanation:
String concatenation concatenates text without automatically injecting spaces.

44. How do you create a single-element tuple containing 5?

a) (5)
b) (5,)
c) tuple(5)
d) [5]
Correct Answer: b) (5,)
Explanation:
A trailing comma differentiates single-element tuples from integer groupings.

45. Which string method combines list elements into a unified string using delimiters?

a) join()
b) concat()
c) merge()
d) split()
Correct Answer: a) join()
Explanation:
delimiter.join(iterable) concatenates string sequences into single strings.

46. Which method empties all items out of a dictionary?

a) delete()
b) clear()
c) reset()
d) popall()
Correct Answer: b) clear()
Explanation:
clear() removes every key-value pair from dictionaries.

47. What is the output of print(2 ** 3 ** 2)?

a) 64
b) 512
c) 36
d) 256
Correct Answer: b) 512
Explanation:
Exponentiation resolves right-to-left: 3 ** 2 = 9, then 2 ** 9 = 512.

48. Which expression checks key membership inside dictionary 'd'?

a) if 'a' in d:
b) if d.contains('a'):
c) if 'a' exists d:
d) if d.has_key('a'):
Correct Answer: a) if 'a' in d:
Explanation:
The 'in' operator tests whether specified keys exist in dictionaries.

49. What list is generated by list(range(1, 5))?

a) [1, 2, 3, 4, 5]
b) [1, 2, 3, 4]
c) [0, 1, 2, 3, 4]
d) [2, 3, 4, 5]
Correct Answer: b) [1, 2, 3, 4]
Explanation:
range(start, stop) excludes the stop value parameter.

50. Which keyword manually triggers exceptions in code?

a) throw
b) raise
c) fire
d) error
Correct Answer: b) raise
Explanation:
The raise keyword raises errors and custom exceptions.

51. Which function generates index and item pairs from iterables?

a) zip()
b) enumerate()
c) map()
d) filter()
Correct Answer: b) enumerate()
Explanation:
enumerate() returns iterators yielding index-value tuples.

52. What action does map() perform?

a) Generates coordinate plots
b) Applies specified functions to every item in iterables
c) Filters elements based on conditional checks
d) Maps dictionary keys
Correct Answer: b) Applies specified functions to every item in iterables
Explanation:
map(function, iterable) executes function calls against all input items.

53. Which function extracts elements from iterables based on conditional truth checks?

a) filter()
b) map()
c) reduce()
d) select()
Correct Answer: a) filter()
Explanation:
filter(function, iterable) constructs iterators keeping items where functions evaluate True.

54. What are single-expression anonymous functions called in Python?

a) Def functions
b) Lambda functions
c) Inline functions
d) Macros
Correct Answer: b) Lambda functions
Explanation:
Lambda expressions create inline anonymous function objects.

55. What data type is returned by input() in Python 3?

a) int
b) str
c) float
d) Dynamic based on entry
Correct Answer: b) str
Explanation:
input() continuously reads console inputs as string data objects.

56. Which path handling module works across operating systems?

a) sys
b) os.path
c) file
d) pathlib
Correct Answer: b) os.path
Explanation:
os.path offers portable operations on path strings.

57. Which function parses JSON strings into Python objects?

a) json.dumps()
b) json.loads()
c) json.parse()
d) json.decode()
Correct Answer: b) json.loads()
Explanation:
json.loads() (load string) deserializes JSON string data.

58. Which function converts Python structures into JSON formatted text?

a) json.dumps()
b) json.loads()
c) json.stringify()
d) json.encode()
Correct Answer: a) json.dumps()
Explanation:
json.dumps() (dump string) converts Python objects to JSON string structures.

59. What is the output of 'abc'.upper()?

a) Abc
b) ABC
c) abc
d) Error
Correct Answer: b) ABC
Explanation:
upper() returns uppercase formatted strings.

60. Which method removes whitespace from string start and end locations?

a) clean()
b) strip()
c) trim()
d) remove()
Correct Answer: b) strip()
Explanation:
strip() removes both leading and trailing whitespaces.

61. What is the boolean valuation of empty dict {}?

a) True
b) False
c) None
d) Undefined
Correct Answer: b) False
Explanation:
Empty dictionary objects evaluate as False in boolean contexts.

62. What is the default opening mode for open()?

a) 'w'
b) 'r'
c) 'a'
d) 'rb'
Correct Answer: b) 'r'
Explanation:
Files open in text read mode ('r') when mode parameters are unspecified.

63. Which keyword creates user-defined classes?

a) struct
b) object
c) class
d) interface
Correct Answer: c) class
Explanation:
The class keyword constructs new object types.

64. How do you derive Child class from Parent class?

a) class Child extends Parent:
b) class Child(Parent):
c) class Child implements Parent:
d) class Child : Parent
Correct Answer: b) class Child(Parent):
Explanation:
Parent classes pass inside header parentheses during child class definitions.

65. Which built-in provides access to base class methods?

a) parent()
b) super()
c) base()
d) this()
Correct Answer: b) super()
Explanation:
super() returns proxy objects delegating method calls to parent classes.

66. What does *args receive in function signatures?

a) Keyword arguments as dictionary
b) Positional arguments as a tuple
c) Multiplied numerical arguments
d) Type bounds
Correct Answer: b) Positional arguments as a tuple
Explanation:
*args collects variable numbers of positional arguments inside tuples.

67. What does **kwargs capture inside function signatures?

a) Keyword arguments as a dictionary
b) Positional parameter values
c) Exponent variables
d) Immutability rules
Correct Answer: a) Keyword arguments as a dictionary
Explanation:
**kwargs stores arbitrary keyword arguments inside dictionaries.

68. Which module exposes system arguments sys.argv?

a) os
b) sys
c) env
d) cli
Correct Answer: b) sys
Explanation:
The sys module captures system environment configurations and arguments.

69. How are command-line arguments accessed in scripts?

a) os.args
b) sys.argv
c) cmd.args
d) input.args
Correct Answer: b) sys.argv
Explanation:
sys.argv holds lists containing command-line inputs.

70. What value resides inside sys.argv[0]?

a) First option argument
b) Script file path or name
c) Python interpreter path
d) OS name
Correct Answer: b) Script file path or name
Explanation:
sys.argv[0] records the script path invoked in command lines.

71. Which collection structure maintains unordered unique items?

a) List
b) Tuple
c) Set
d) Dictionary
Correct Answer: c) Set
Explanation:
Sets are collections storing distinct unordered values.

72. What happens when duplicate items add to sets?

a) Raises ValueError
b) Duplicates are silently ignored
c) Overwrites existing set
d) Adds items to set end
Correct Answer: b) Duplicates are silently ignored
Explanation:
Set structures inherently ignore duplicate additions.

73. Which operator executes set union?

a) &
b) |
c) ^
d) -
Correct Answer: b) |
Explanation:
The pipe operator | calculates set union.

74. Which operator executes set intersection?

a) &
b) |
c) ^
d) -
Correct Answer: a) &
Explanation:
The ampersand operator & returns set intersections.

75. How do you construct dictionaries from key-value tuple pairs?

a) to_dict()
b) dict()
c) map_dict()
d) struct()
Correct Answer: b) dict()
Explanation:
dict() builds dictionaries when provided paired iterable items.

76. Which block runs code unconditionally in exception handling?

a) always
b) finally
c) ensure
d) complete
Correct Answer: b) finally
Explanation:
The finally block runs cleanup routines regardless of exception states.

77. What class is returned by 1/2 in Python 3?

a)
b)
c)
d)
Correct Answer: b)
Explanation:
Standard division / produces floats in Python 3.

78. Which string method replaces occurrences of specified substrings?

a) swap()
b) replace()
c) sub()
d) change()
Correct Answer: b) replace()
Explanation:
replace() substitutes substring occurrences with designated replacement text.

79. Which string method splits text into list items via delimiters?

a) split()
b) partition()
c) divide()
d) break()
Correct Answer: a) split()
Explanation:
split() divides strings by specified separator strings into lists.

80. Which variable identifier follows valid Python naming rules?

a) 2myvar
b) my-var
c) _my_var
d) my var
Correct Answer: c) _my_var
Explanation:
Identifiers can contain underscores and letters, but cannot start with numbers or use spaces/hyphens.

81. Which keyword checks key presence in dictionaries or collections?

a) has
b) in
c) with
d) exist
Correct Answer: b) in
Explanation:
The 'in' operator tests value or key membership.

82. What range of elements does list slice lst[1:4] grab?

a) Indices 1 through 4
b) Indices 1 through 3
c) Indices 0 through 4
d) First 4 elements
Correct Answer: b) Indices 1 through 3
Explanation:
Slicing includes starting index 1, stopping before ending bound index 4.

83. What is the primary function of zip()?

a) Compresses data archives
b) Pairs elements across multiple iterables
c) Accelerates execution
d) Merges text files
Correct Answer: b) Pairs elements across multiple iterables
Explanation:
zip() iterates across input sequences, aggregating corresponding elements into tuples.

84. Which error is raised when accessing missing dictionary keys directly?

a) IndexError
b) KeyError
c) ValueError
d) LookupError
Correct Answer: b) KeyError
Explanation:
Direct bracket access on non-existent dictionary keys raises KeyError exceptions.

85. Which dictionary method safely retrieves key values without raising errors if missing?

a) find()
b) get()
c) fetch()
d) search()
Correct Answer: b) get()
Explanation:
get() returns default values (None unless overridden) when requested keys are absent.

86. Which list comprehension squares numbers x inside range(3)?

a) [x^2 for x in range(3)]
b) [x**2 for x in range(3)]
c) (x**2 for x in range(3))
d) {x**2 for x in range(3)}
Correct Answer: b) [x**2 for x in range(3)]
Explanation:
List comprehensions utilize square brackets [] with valid mathematical operators like **.

87. Which brackets generate lazy generator expressions instead of lists?

a) Square brackets []
b) Parentheses ()
c) Curly braces {}
d) Angle brackets
Correct Answer: b) Parentheses ()
Explanation:
Parentheses enclose comprehension statements to construct generator objects.

88. Which keyword turns function code into generator iterators?

a) return
b) yield
c) generate
d) emit
Correct Answer: b) yield
Explanation:
The yield keyword returns values and pauses execution state in generator functions.

89. What does isinstance(obj, Class) check?

a) Instantiates Class objects
b) Verifies if obj belongs to Class or its subclasses
c) Deletes obj objects
d) Casts obj to Class type
Correct Answer: b) Verifies if obj belongs to Class or its subclasses
Explanation:
isinstance() checks if target objects match specific types or subclasses.

90. Which function returns unique integer object identity memory values?

a) address()
b) id()
c) ref()
d) loc()
Correct Answer: b) id()
Explanation:
id() returns memory address identity integers.

91. What integer value is returned by str.find() if substrings are missing?

a) False
b) -1
c) None
d) ValueError
Correct Answer: b) -1
Explanation:
find() returns -1 when target search values are missing in strings.

92. How do you perform shallow copies of list 'a' using slicing?

a) b = a
b) b = a[:]
c) b = a.copy_all()
d) b = a[0]
Correct Answer: b) b = a[:]
Explanation:
a[:] selects all elements into new copy array references.

93. Which function finds maximum values inside iterables?

a) maximum()
b) max()
c) greatest()
d) top()
Correct Answer: b) max()
Explanation:
max() returns largest inputs or items inside iterables.

94. Which decorator constructs static methods inside classes?

a) @classmethod
b) @staticmethod
c) @static
d) @property
Correct Answer: b) @staticmethod
Explanation:
@staticmethod defines class methods without mandatory self or cls parameters.

95. Which decorator turns method calls into managed property getters?

a) @attribute
b) @property
c) @getter
d) @variable
Correct Answer: b) @property
Explanation:
@property turns instance methods into accessible read-only attributes.

96. Which expression builds a dictionary mapping keys 'a' and 'b' to value 0?

a) dict.fromkeys(['a', 'b'], 0)
b) dict.create(['a', 'b'], 0)
c) {'a', 'b' : 0}
d) dict(['a', 'b'] = 0)
Correct Answer: a) dict.fromkeys(['a', 'b'], 0)
Explanation:
dict.fromkeys() creates dictionaries populated with specified key sequences and uniform initial values.

97. What is returned by the sorted() function?

a) Sorts lists in-place, returning None
b) Returns a new sorted list from input iterables
c) Reverses array sequences
d) Sorts numeric values exclusively
Correct Answer: b) Returns a new sorted list from input iterables
Explanation:
sorted() returns brand new sorted lists while maintaining original source order.

98. Which method sorts lists directly in-place?

a) list.sort()
b) list.sorted()
c) list.order()
d) list.arrange()
Correct Answer: a) list.sort()
Explanation:
The sort() method reorders original list items directly in place.

99. What exception occurs when passing invalid numeric string values like int('abc')?

a) TypeError
b) ValueError
c) ConversionError
d) AttributeError
Correct Answer: b) ValueError
Explanation:
ValueError triggers when operations receive arguments of right data types but invalid values.

100. Which function sums numeric items inside iterables?

a) add()
b) sum()
c) total()
d) accumulate()
Correct Answer: b) sum()
Explanation:
sum() totals numerical elements inside iterables.

101. Which operator executes bitwise XOR operations?

a) &
b) |
c) ^
d) ~
Correct Answer: c) ^
Explanation:
The caret ^ calculates bitwise exclusive OR (XOR).

102. Which operator performs bitwise NOT (complement) operations?

a) !
b) ~
c) not
d) ^
Correct Answer: b) ~
Explanation:
The tilde ~ executes bitwise complement operations.
← Previous: Python Variables & Data Types MCQs
Newpython variables & datatypes MCQs

Python Variables & Data Types MCQs

Variables in Python act as dynamic references reserved in memory to store objects, operating without explicit data type declarations due…

By MCQs Generator
NewLatest Python Operators MCQs

Latest Python Operators MCQs

Operators in Python are special symbols and keywords used to manipulate data, perform mathematical computations, make boolean comparisons, and control…

By MCQs Generator
NewPython OOP MCQs

Python OOP MCQs

Object-Oriented Programming (OOP) in Python is a programming paradigm that uses classes and objects to model real world entities, promoting…

By MCQs Generator