Python Quiz: Test Your Python Knowledge
Pick how many questions you want, choose a difficulty and go. You'll see why each answer is right or wrong, then you can retry to beat your score.
Which command checks which version of Python is installed?
- python -check
- print(version)
- python install
- python --version
What file extension do Python script files use?
- .pt
- .pyt
- .py
- .python
What does
print(10 / 4)show?- 2.5
- 2
- 2.0
- 2 remainder 2
What happens if a line starts with an unexpected space?
- Python ignores the space
- Python raises an IndentationError
- The line becomes a comment
- The line runs twice
Which file extension do Python programs use?
- .pt
- .pyt
- .python
- .py
What defines a Python statement block?
- Curly braces
- Consistent indentation
- Python ignores the distinction
Which statement correctly describes continuation?
- Parentheses allow long expressions to continue across physical lines.
- Only the example output matters, not the rule
- Every operation has the same behavior
What does # inside quoted text represent?
- A comment marker
- A character in the string
- Python ignores the distinction
Which statement correctly describes docstrings?
- The opening string in a function, class or module documents its public purpose.
- Only the example output matters, not the rule
- Every operation has the same behavior
Which keyword changes the text between printed arguments?
- end
- sep
- Python ignores the distinction
Which statement correctly describes line endings?
- end sets the text following the final argument.
- Only the example output matters, not the rule
- Every operation has the same behavior
What type is the value
3.0?- int
- str
- float
- bool
Which variable name follows Python's usual style?
- total_price
- TotalPrice
- totalprice!
- total-price
What does
input()always return?- An int
- Whatever type the user typed
- A boolean
- A string
What does
print(f"{7 / 2:.1f}")show?- 3.5
- 3
- 3.50
- 7 / 2
What does
type(int("7") + 0.5)give?- <class 'int'>
- <class 'float'>
- <class 'str'>
- An error
What does a = b = [] create?
- Two independent lists
- Two references to one list
- Python ignores the distinction
Which statement correctly describes swapping?
- The right side is evaluated before its values are assigned to targets.
- Only the example output matters, not the rule
- Every operation has the same behavior
What does
2 ** 3equal?- 8
- 6
- 5
- 9
What type is the result of
10 / 5?- int
- str
- bool
- float
What does
round(3.14159, 2)return?- 3.14
- 3.1
- 3.142
- 3
Why does
0.1 + 0.2print0.30000000000000004?- Python has a bug
- The numbers are strings
- Some decimals can't be stored exactly in binary
- round() was missing
What does
-7 // 2give?- -3
- -3.5
- 3
- -4
What does int(-3.8) produce?
- -4
- -3
- Python ignores the distinction
Which statement correctly describes truncation?
- int applied to a finite float discards the fractional part toward zero.
- Only the example output matters, not the rule
- Every operation has the same behavior
Which test specifically checks for None?
- not value
- value is None
- Python ignores the distinction
Which statement correctly describes implicit results?
- Functions with no explicit returned value produce None.
- Only the example output matters, not the rule
- Every operation has the same behavior
What is the index of the first character in a Python string?
- 1
- -1
- It depends on the string
- 0
Which method removes spaces from both ends of a string?
- trim()
- clean()
- strip()
- cut()
What does
"hello"[::-1]return?- "hello"
- "olleh"
- "h"
- An error
Why does
s.upper()on its own not changes?- upper() only works inside print()
- Strings are immutable, so upper() returns a new string
- You must call it twice
- upper() only changes the first letter
What does
"a,b,,c".split(",")return?- ['a', 'b', 'c']
- ['a,b,,c']
- ['a', 'b', '', 'c']
- ['a', 'b', ',', 'c']
What does
f"{7:03d}"produce?- 7
- 700
- 007
- 3d7
Which alignment character centres text?
- <
- >
- =
- ^
What does
"{:>6.1f}".format(3.14159)produce?- "3.1 "
- " 3.1" (right-aligned in 6 characters)
- "3.14159"
- " 3.14"
How do you print a literal
{inside an f-string?- {{
- \{
- '{'
- It isn't possible
Why is it better to format values at the moment you print them?
- Formatting is slow
- f-strings can only be used in print()
- Formatted values are strings, so calculating with them gives wrong results or errors
- Python forgets formatting after one line
Which type does input return?
- int
- str
- Python ignores the distinction
Which statement correctly describes validation?
- Conversion checks the representation, and range checks enforce the application rule.
- Only the example output matters, not the rule
- Every operation has the same behavior
What is bool("0")?
- False
- True
- Python ignores the distinction
Which statement correctly describes truthiness?
- Zero, empty collections and None are false in conditions.
- Only the example output matters, not the rule
- Every operation has the same behavior
What does 2 + 3 * 4 evaluate to?
- 20
- 14
- Python ignores the distinction
Which statement correctly describes membership and bits?
- in checks containment while bitwise operators combine integer bit patterns.
- Only the example output matters, not the rule
- Every operation has the same behavior
What does
==do in Python?- Stores a value
- Checks whether two values are equal
- Checks whether two values are different
- Joins two strings
What must come at the end of an
ifline?- A semicolon
- Curly braces
- Nothing
- A colon
How many branches of an if/elif/else chain can run at once?
- All the true ones
- Exactly two
- At most one
- It depends on the indentation
What is the value of
not (5 > 3 and 2 > 4)?- True
- False
- None
- An error
What does
not (5 > 3)evaluate to?- False
- True
- 5
- An error
What does a bare name normally do in a match pattern?
- Look up an existing constant
- Capture a value
- Python ignores the distinction
Which statement correctly describes guards?
- A case guard checks an additional condition after its pattern succeeds.
- Only the example output matters, not the rule
- Every operation has the same behavior
Does pass skip the rest of a loop iteration?
- Yes
- No
- Python ignores the distinction
Which statement correctly describes loop behavior?
- pass does not skip later work in a loop iteration.
- Only the example output matters, not the rule
- Every operation has the same behavior
Which numbers does
range(4)produce?- 1, 2, 3, 4
- 0, 1, 2, 3, 4
- 0, 1, 2, 3
- 4
Which loop is best when you don't know how many repeats you need?
- for
- range
- if
- while
What does
breakdo inside a loop?- Exits the loop immediately
- Pauses the loop for a moment
- Skips one pass
- Restarts the loop
How many times does
printrun here:for i in range(10, 0, -2): print(i)?- 4
- 5
- 6
- 10
What does
continuedo inside a loop?- Ends the loop completely
- Restarts the loop from the beginning
- Skips the rest of this pass and moves on to the next one
- Pauses the program
What is the index of the first item in a Python list?
- 1
- 0
- -1
- It depends on the list
What does
len(["x", "y", "z"])return?- 2
- "xyz"
- 0
- 3
What's the difference between
my_list.sort()andsorted(my_list)?- There is no difference
- sorted() changes the list itself; sort() returns a new list
- sort() changes the list itself; sorted() returns a new sorted list
- sort() only works on numbers
What is
["a", "b", "c", "d", "e"][-2:]?- ['d', 'e']
- ['d']
- ['c', 'd']
- ['e']
What's the difference between
appendandextend?- There's none
- extend adds to the front
- append sorts the list
- append adds one item; extend adds every item from another list
Which brackets create a dictionary?
- { }
- [ ]
- ( )
- < >
What happens when you read a missing key with square brackets?
- It returns None
- Python raises a KeyError
- It returns 0
- It adds the key
What does
d.get("age", 18)return if "age" isn't in d?- None
- 18
- "age"
- A KeyError
Which of these can be a dictionary key?
- A list such as [1, 2]
- Another dictionary
- A set
- A tuple such as (1, 2)
In what order does a loop over a Python 3.7+ dictionary visit the keys?
- Alphabetical order
- Random order
- The order the keys were added
- Sorted by value
What makes a tuple different from a list?
- Tuples can only hold numbers
- Tuples are unordered
- Tuples can't be changed after they're created
- Tuples use square brackets
What happens if you add a value that's already in a set?
- An error
- It's added twice
- The old value is replaced
- Nothing, sets keep only unique values
What does
a, b = b, ado?- Swaps the values of a and b
- Raises an error
- Makes both variables equal to a
- Creates a list
Which operator gives the items found in both sets?
- |
- &
- -
- +
Why is
("red")not a tuple?- It's the comma that makes a tuple; this is just a string in brackets
- Tuples can't contain strings
- Tuples need at least three items
- It needs square brackets
Which boundary is excluded by range?
- The start
- The stop
- Python ignores the distinction
Which statement correctly describes compact storage?
- A range stores its defining parameters rather than a list of every generated integer.
- Only the example output matters, not the rule
- Every operation has the same behavior
What restricts values in array.array?
- Nothing
- Its selected type code
- Python ignores the distinction
Which statement correctly describes sequence operations?
- Typed arrays support indexing, slices and compatible append operations.
- Only the example output matters, not the rule
- Every operation has the same behavior
Which operation finds shared set members?
- Union
- Intersection
- Python ignores the distinction
Which statement correctly describes set algebra?
- Union, intersection, difference and symmetric difference answer different membership questions.
- Only the example output matters, not the rule
- Every operation has the same behavior
What stays shared after a shallow copy?
- The new outer container
- Nested objects
- Python ignores the distinction
Which statement correctly describes deep copies?
- deepcopy recursively copies supported structures and tracks previously copied objects.
- Only the example output matters, not the rule
- Every operation has the same behavior
Which keyword defines a function in Python?
- function
- def
- func
- define
What does a function return if it has no return statement?
- 0
- An empty string
- None
- An error
In
def area(w, h):andarea(3, 4), what are 3 and 4?- Parameters
- Return values
- Defaults
- Arguments
What does this print?
def f(x): return x * 2thenprint(f(f(3)))- 12
- 6
- 9
- 36
Which call uses a keyword argument?
- greet("Ada")
- greet(name="Ada")
- greet["Ada"]
- greet.name("Ada")
What type is
argsinsidedef f(*args):?- list
- dict
- set
- tuple
What type is
kwargsinsidedef f(**kwargs):?- list
- tuple
- str
- dict
What does
print(*[1, 2, 3])print?- [1, 2, 3]
- 1 2 3
- 123
- (1, 2, 3)
What happens to a local variable when its function finishes?
- It disappears
- It becomes global
- It's saved for the next call
- It's printed
What's the safe default for a parameter that should start as an empty list?
- basket=[]
- basket=list
- basket=None, then create a list inside the function
- basket=()
What terminates recursive descent?
- A print statement
- A reachable base case
- Python ignores the distinction
Which statement correctly describes call stack?
- Active calls keep separate local state until deeper calls return.
- Only the example output matters, not the rule
- Every operation has the same behavior
What does a list comprehension return?
- The original list, changed
- A new list
- A string
- None
In
[x for x in items if x > 0], what does theifdo?- Keeps only items where the condition is true
- Changes every item
- Stops the loop
- Sorts the items
What is a lambda?
- A loop
- A small, unnamed function written as one expression
- A kind of list
- A module
What does
key=do insorted(items, key=...)?- Encrypts the items
- Removes duplicates
- Tells sorted() which value to compare for each item
- Sorts in reverse
What does
{w.lower() for w in ["A", "a", "B"]}produce?- ['a', 'a', 'b']
- {'A': 'a', 'B': 'b'}
- An error
- {'a', 'b'}
Where should you start reading a traceback?
- At the top
- In the middle
- It doesn't matter
- At the bottom, which names the error type and message
Which exception does
int("hello")raise?- TypeError
- NameError
- ValueError
- KeyError
When does a
finallyblock run?- Only when there's an error
- Always
- Only when there's no error
- Never inside functions
What does
raise ValueError("Too big")do?- Stops normal execution with a ValueError carrying that message
- Prints "Too big" and continues
- Fixes the value
- Creates a variable
When does the
elseblock of a try statement run?- When an exception is caught
- Before the try block
- Only if there's also a finally
- When the try block finished without any exception
What does
with open(...)guarantee?- The file exists
- The file is empty
- The file is closed when the block ends
- The file is read-only
What happens if you open an existing file with mode "w"?
- The file is emptied before writing
- An error is raised
- New text is added to the end
- Nothing changes
Why add
encoding="utf-8"when opening text files?- It makes files smaller
- It's required for CSV files only
- It encrypts the file
- So characters such as é or ñ are read and written consistently on every system
What type are the values in a row from
csv.DictReader?- Strings
- Numbers where possible
- Lists
- Booleans
What does the mode "a" do in
open("log.txt", "a")?- Opens the file read-only
- Deletes the file first
- Adds new text to the end, creating the file if needed
- Opens it as binary
What is a Python module?
- A type of loop
- A built-in data type
- A .py file containing code you can import
- An error message
What does
import pandas as pddo?- Imports pandas and lets you refer to it as pd
- Renames the pandas package on disk
- Installs pandas
- Imports only the pd function
What file is commonly used to list a project's packages?
- packages.py
- requirements.txt
- pip.json
- modules.cfg
Why should you avoid
from module import *?- It's slower to type
- It doesn't work in Python 3
- It only imports classes
- It imports every name, making it unclear where names come from and risking clashes
What is a virtual environment for?
- Running Python in the browser
- Making code run faster
- Keeping each project's installed packages separate
- Hiding your code
What does
date.today().yeargive?- The current month
- The date as text
- The current year as a number
- The day of the week
What does
timedelta(days=7)represent?- A specific date
- A length of time: one week
- The seventh day of the month
- Seven o'clock
What does
%Bshow?- The short month name
- The month number
- The full month name, such as March
- The weekday
What does
strptimeraise if the text doesn't match the format?- ValueError
- TypeError
- KeyError
- Nothing, it returns None
What does
date(2025, 3, 5).weekday()return, given that 5 March 2025 is a Wednesday?- 3
- 4
- "Wednesday"
- 2
How do you create an object from a class called
Car?- new Car()
- create Car
- Car.new()
- Car()
When does
__init__run?- Each time a new object is created
- When the program starts
- When the object is printed
- Only once per class
What is a class attribute?
- An attribute created inside __init__
- A private attribute
- An attribute defined in the class body, shared by all instances
- A method
What does a leading underscore in
_balancemean?- It's a syntax error
- By convention, it's internal and should be changed through methods
- Python makes it read-only
- It's a class attribute
Why is
items = []in a class body risky for per-object data?- Lists can't be attributes
- It slows the class down
- The same list is shared by every object of the class
- It deletes the list each time
What does a subclass inherit from its parent?
- Nothing
- Only its __init__
- Its attributes and methods
- Only methods named with underscores
What is method overriding?
- Deleting a parent method
- Defining a method in the child with the same name as one in the parent
- Calling a method twice
- Making a method private
What does
super().__init__(name)do inside a child's__init__?- Creates a second object
- Deletes the parent's attributes
- Calls the child's __init__ again
- Runs the parent class's __init__ for this object
What is polymorphism?
- Different classes responding to the same method call in their own way
- A class with many attributes
- A class that inherits from many parents
- Changing an object's type
When is composition usually better than inheritance?
- When the relationship is "is a"
- When there are no methods
- Never
- When the relationship is "has a"
Which method is intended for diagnostic representation?
- __str__ only
- __repr__
- Python ignores the distinction
Which statement correctly describes diagnostic text?
- __repr__ helps developers inspect the important state of an object.
- Only the example output matters, not the rule
- Every operation has the same behavior
Why store _capacity in the property setter?
- To enforce secrecy
- To avoid recursive setter calls
- Python ignores the distinction
Which statement correctly describes static methods?
- A staticmethod has no automatic self or cls argument.
- Only the example output matters, not the rule
- Every operation has the same behavior
Does a nested class automatically receive an outer instance?
- Yes
- No
- Python ignores the distinction
Which statement correctly describes composition?
- An object can contain a collaborator instead of inheriting its behavior.
- Only the example output matters, not the rule
- Every operation has the same behavior
Does Python stop the program if an argument doesn't match its type hint?
- No, hints are checked by tools like editors and mypy, not at run time
- Yes, always
- Only for ints
- Only in classes
Which methods does
@dataclassgenerate by default?- Only __init__
- __str__ and __len__
- All comparison operators
- __init__, __repr__ and __eq__
How do you give a dataclass field an empty list as its default?
- items: list = []
- items: list[str] = list
- items: list[str] = field(default_factory=list)
- items: list[str] = None()
What does
-> Noneon a function mean?- It returns zero
- It can't be called
- It returns an empty string
- It doesn't return a value
With
@dataclass(order=True)and fieldsmajor, minor, how are objects compared?- Field by field, starting with major, then minor if major is equal
- By the order they were created
- By memory address
- Alphabetically by class name
Which keyword turns a function into a generator?
- return
- yield
- async
- gen
What does
next()raise when an iterator has no more items?- IndexError
- ValueError
- StopIteration
- None
What does lazy evaluation mean?
- Code runs slowly
- Errors are ignored
- Values are produced only when they're needed
- Functions run in the background
What does
list(islice(count(5), 3))give?- [0, 1, 2]
- [5, 5, 5]
- [3, 4, 5]
- [5, 6, 7]
What happens to a generator's local variables between
next()calls?- They're reset
- They're kept, because the function is paused, not finished
- They become global
- They're deleted
What happens to an exhausted iterator in a for loop?
- It restarts
- The loop finishes
- Python ignores the distinction
Which statement correctly describes exhaustion?
- StopIteration signals that no next value remains.
- Only the example output matters, not the rule
- Every operation has the same behavior
Where should essential contextmanager cleanup go?
- Only before yield
- In finally around yield
- Python ignores the distinction
Which statement correctly describes bound value?
- The result of __enter__ is assigned to the name after as.
- Only the example output matters, not the rule
- Every operation has the same behavior
What is a decorator?
- A function that takes a function and returns a modified version of it
- A comment that styles code
- A type of class
- A loop
What is a closure?
- A function with no return
- An inner function that remembers variables from the function it was defined in
- The end of a file
- A closed file object
What does
@lru_cachedo?- Stores results so repeated calls with the same arguments return instantly
- Deletes old functions
- Logs every call
- Limits recursion
How many nested functions does a decorator with arguments normally have?
- One
- Two
- Three
- Four
When does a decorator run?
- Every time the program starts a loop
- Once, when the decorated function is defined; the wrapper runs on each call
- Only when an error happens
- Never, it's just a label
Which module provides regular expressions in Python?
- regex
- re
- string
- pattern
What does
?mean after a character in a pattern?- One or more
- Zero or more
- Optional: zero or one
- Exactly one
What does
re.searchreturn when nothing matches?- An empty string
- False
- None
- An error
What does
\smatch?- A whitespace character
- The letter s
- Any symbol
- The start of the text
In
re.sub(r"(\w+) (\w+)", r"\2 \1", "Ada Lovelace"), what's the result?- Ada Lovelace
- \2 \1
- AdaLovelace
- Lovelace Ada
What does an automated test do?
- Runs code with known inputs and checks the result automatically
- Speeds up the program
- Formats code
- Installs packages
In pytest output, what does
Fmean?- Finished
- A fixture ran
- A test failed
- A file was skipped
What is a fixture?
- A broken test
- A type of assert
- A test file
- A function that prepares data or resources that tests receive as parameters
How do you compare floats safely in a pytest assert?
- pytest.approx(expected)
- round both sides to 0 decimals
- str(a) == str(b)
- You can't
You've found a bug. What's a good first step?
- Delete the related tests
- Write a test that reproduces the bug, then fix the code until it passes
- Rewrite the whole module
- Ignore it if other tests pass
What format do most web APIs use for their responses?
- CSV
- HTML only
- JSON
Which HTTP method is normally used to create something new?
- POST
- GET
- HEAD
- OPTIONS
What does status code 429 tell you?
- Success
- The server crashed
- You're sending too many requests
- The page moved
Why always pass
timeout=?- It makes requests faster
- Without it, a request to a slow server can wait for ever
- Some APIs require it
- It retries failed requests
Which exception catches all errors raised by requests, including connection problems?
- ValueError
- requests.RequestException
- HTTPError only
- KeyError
Which mode refuses to overwrite an existing file?
- w
- x
- Python ignores the distinction
Which statement correctly describes context lifetime?
- with closes the file when its block ends.
- Only the example output matters, not the rule
- Every operation has the same behavior
Which function decodes JSON from a string?
- json.load
- json.loads
- Python ignores the distinction
Which statement correctly describes formatting?
- indent improves readability and ensure_ascii=False preserves readable Unicode characters.
- Only the example output matters, not the rule
- Every operation has the same behavior
What type is a numeric field returned by DictReader?
- int
- str
- Python ignores the distinction
Which statement correctly describes writing?
- DictWriter writes named fields using an explicit field order.
- Only the example output matters, not the rule
- Every operation has the same behavior
Does creating a Path object create a filesystem entry?
- Yes
- No
- Python ignores the distinction
Which statement correctly describes traversal?
- iterdir lists immediate children while glob can select matching names.
- Only the example output matters, not the rule
- Every operation has the same behavior
What does ordinary zip do with unequal iterable lengths?
- Fill missing values automatically
- Stop at the shortest
- Python ignores the distinction
Which statement correctly describes transformation?
- sorted, reversed, enumerate and zip provide useful traversal transformations.
- Only the example output matters, not the rule
- Every operation has the same behavior
Which method changes a list in place?
- sorted
- list.sort
- Python ignores the distinction
Which statement correctly describes mappings?
- keys, values and items expose dictionary views and get reads with a fallback.
- Only the example output matters, not the rule
- Every operation has the same behavior
Which exception normally describes invalid integer text?
- KeyError
- ValueError
- Python ignores the distinction
Which statement correctly describes filesystem errors?
- FileNotFoundError, PermissionError and other OSError subclasses describe external resource failures.
- Only the example output matters, not the rule
- Every operation has the same behavior
Is print normally a reserved Python keyword?
- Yes
- No
- Python ignores the distinction
Which statement correctly describes core vocabulary?
- An argument is a supplied value, a parameter is a declared input and a return value is a produced result.
- Only the example output matters, not the rule
- Every operation has the same behavior
Which standard library type counts repeated values?
- Path
- Counter
- Python ignores the distinction
Which statement correctly describes collections?
- Counter counts values, defaultdict supplies missing defaults and deque supports efficient end operations.
- Only the example output matters, not the rule
- Every operation has the same behavior
What type does os.getenv return when it finds a value?
- int
- str
- Python ignores the distinction
Which statement correctly describes required configuration?
- Missing required configuration should produce an actionable startup error.
- Only the example output matters, not the rule
- Every operation has the same behavior
Which form selects pip for a chosen Python interpreter?
- An unrelated pip executable
- python -m pip
- Python ignores the distinction
Which statement correctly describes installation records?
- A requirements file records dependency specifications for a reproducible setup.
- Only the example output matters, not the rule
- Every operation has the same behavior
What makes a useful debugging hypothesis?
- A random code change
- A prediction you can test
- Python ignores the distinction
Which statement correctly describes breakpoints?
- breakpoint enters the configured debugger so execution state can be inspected.
- Only the example output matters, not the rule
- Every operation has the same behavior
Where does logger.exception normally capture exception context?
- Before any exception occurs
- Inside an exception handler
- Python ignores the distinction
Which statement correctly describes deferred formatting?
- Passing a format string and arguments defers message interpolation until needed.
- Only the example output matters, not the rule
- Every operation has the same behavior
Why test an exact capacity boundary?
- To guarantee every possible input
- To detect off by one mistakes
- Python ignores the distinction
Which statement correctly describes parameterization?
- Parametrized cases check several boundary inputs using one declared test contract.
- Only the example output matters, not the rule
- Every operation has the same behavior
Where should a dependency usually be patched?
- Only in its original module
- Where the tested code looks it up
- Python ignores the distinction
Which statement correctly describes patching locations?
- Patch the name used by the code under test rather than guessing its original definition location.
- Only the example output matters, not the rule
- Every operation has the same behavior
Which style commonly names Python functions?
- CapWords
- snake_case
- Python ignores the distinction
Which statement correctly describes imports and layout?
- Imports are normally organized near the top and separated into sensible groups.
- Only the example output matters, not the rule
- Every operation has the same behavior
Do annotations alone enforce parameter types at runtime?
- Yes
- No
- Python ignores the distinction
Which statement correctly describes collection types?
- Generic annotations describe the element or key and value types inside collections.
- Only the example output matters, not the rule
- Every operation has the same behavior
What does a loose version constraint guarantee?
- One exact resolved environment
- A permitted version range
- Python ignores the distinction
Which statement correctly describes reproducibility?
- Record the interpreter, dependency inputs and installation instructions.
- Only the example output matters, not the rule
- Every operation has the same behavior
Should a project normally commit its .venv directory?
- Yes
- No
- Python ignores the distinction
Which statement correctly describes commits?
- Focused commits describe one coherent behavior change with a useful message.
- Only the example output matters, not the rule
- Every operation has the same behavior
Why did editing second also change first?
- Every list is globally shared
- Both names reference the same list
- Python ignores the distinction
Which statement correctly describes problem discussion?
- Clarify inputs, constraints and expected results before coding.
- Only the example output matters, not the rule
- Every operation has the same behavior
Does with sqlite3.connect(...) by itself close the connection?
- Yes
- No
- Python ignores the distinction
Which statement correctly describes transactions and closure?
- Resource closure and transaction handling are related but distinct responsibilities.
- Only the example output matters, not the rule
- Every operation has the same behavior
Which clause limits rows affected by a simple UPDATE?
- ORDER BY alone
- WHERE
- Python ignores the distinction
Which statement correctly describes value binding?
- The placeholder syntax belongs to the selected database driver.
- Only the example output matters, not the rule
- Every operation has the same behavior
How should a member identifier enter a SQL query?
- By concatenating user text
- As a bound parameter
- Python ignores the distinction
Which statement correctly describes parameters?
- Connector/Python uses parameter placeholders to bind values separately from SQL.
- Only the example output matters, not the rule
- Every operation has the same behavior
Which update operator changes selected MongoDB fields?
- Replacing every field manually
- $set
- Python ignores the distinction
Which statement correctly describes filters and updates?
- Query filters select documents while update operators describe requested changes.
- Only the example output matters, not the rule
- Every operation has the same behavior
Why set a request timeout?
- To guarantee the server returns valid JSON
- To bound a wait for network activity
- Python ignores the distinction
Which statement correctly describes response handling?
- Status checks and decoding are separate steps.
- Only the example output matters, not the rule
- Every operation has the same behavior
Can a valid token still lack permission for an operation?
- No
- Yes
- Python ignores the distinction
Which statement correctly describes failure categories?
- Network failures, error statuses and invalid response data need separate diagnoses.
- Only the example output matters, not the rule
- Every operation has the same behavior
What type is written to the response body stream?
- A Python dictionary
- bytes
- Python ignores the distinction
Which statement correctly describes encoding?
- JSON text must be encoded into bytes for a binary response stream.
- Only the example output matters, not the rule
- Every operation has the same behavior
Should the Flask development debugger be exposed in production?
- Yes
- No
- Python ignores the distinction
Which statement correctly describes request data?
- JSON and form data arrive through request interfaces and require validation.
- Only the example output matters, not the rule
- Every operation has the same behavior
What does axis=1 sum in a two dimensional array?
- Every column into one row
- Values within each row
- Python ignores the distinction
Which statement correctly describes axes?
- Axis arguments select the dimensions along which reductions operate.
- Only the example output matters, not the rule
- Every operation has the same behavior
Which selector uses integer positions?
- loc
- iloc
- Python ignores the distinction
Which statement correctly describes aggregation?
- groupby partitions rows into groups before aggregation.
- Only the example output matters, not the rule
- Every operation has the same behavior
Which object represents an individual plotting area?
- The filename
- Axes
- Python ignores the distinction
Which statement correctly describes labels and scales?
- Titles, axis labels and appropriate scales help a reader interpret the measurements.
- Only the example output matters, not the rule
- Every operation has the same behavior
Why retain rejected row information?
- To increase the reported total
- To explain cleaning decisions
- Python ignores the distinction
Which statement correctly describes conversion and provenance?
- Convert values explicitly and preserve enough information to explain rejected rows.
- Only the example output matters, not the rule
- Every operation has the same behavior
Which statistic is generally less affected by one extreme duration?
- Mean
- Median
- Python ignores the distinction
Which statement correctly describes sampling?
- A collected sample may differ from the full process being studied.
- Only the example output matters, not the rule
- Every operation has the same behavior
Which chart shows the distribution of one numeric variable?
- Category bar chart
- Histogram
- Python ignores the distinction
Which statement correctly describes scatter plots?
- A scatter plot shows paired numeric observations.
- Only the example output matters, not the rule
- Every operation has the same behavior
What is the worst case growth of a full list scan?
- O(1)
- O(n)
- Python ignores the distinction
Which statement correctly describes worst and average cases?
- Different inputs can require different amounts of work.
- Only the example output matters, not the rule
- Every operation has the same behavior
What prerequisite does binary search require?
- A random input order
- A suitably sorted search space
- Python ignores the distinction
Which statement correctly describes interval invariant?
- Maintain a search interval that still contains every possible matching position.
- Only the example output matters, not the rule
- Every operation has the same behavior
What does a stable sort preserve for equal keys?
- Reverse order
- Their original relative order
- Python ignores the distinction
Which statement correctly describes algorithm tradeoffs?
- Insertion sort illustrates local shifts while merge sort illustrates dividing and combining.
- Only the example output matters, not the rule
- Every operation has the same behavior
Which order describes a queue?
- Last in, first out
- First in, first out
- Python ignores the distinction
Which statement correctly describes empty structures?
- Removal from an empty stack or deque needs an explicit policy.
- Only the example output matters, not the rule
- Every operation has the same behavior
How does a singly linked list reach the next value?
- By constant time arbitrary indexing
- By following a next reference
- Python ignores the distinction
Which statement correctly describes insertion?
- Insertion can relink a known predecessor without moving a whole array of elements.
- Only the example output matters, not the rule
- Every operation has the same behavior
Can different dictionary keys have the same hash?
- No
- Yes
- Python ignores the distinction
Which statement correctly describes hashable keys?
- A key needs a stable hash and a compatible equality contract while stored.
- Only the example output matters, not the rule
- Every operation has the same behavior
What determines search cost in a simple BST?
- Only the root value
- The tree height
- Python ignores the distinction
Which statement correctly describes traversal?
- Inorder, preorder and postorder visit the same structure in different sequences.
- Only the example output matters, not the rule
- Every operation has the same behavior
Which traversal finds shortest hop counts in an unweighted graph?
- Any depth first traversal
- Breadth first search
- Python ignores the distinction
Which statement correctly describes breadth first search?
- BFS explores by distance in edge count using a queue.
- Only the example output matters, not the rule
- Every operation has the same behavior
What must mutable backtracking restore?
- Every global variable
- The state changed for the current choice
- Python ignores the distinction
Which statement correctly describes memoization?
- Caching results can avoid solving an identical subproblem repeatedly.
- Only the example output matters, not the rule
- Every operation has the same behavior
Why compare a learned model with a baseline?
- To avoid all evaluation
- To check whether complexity improves useful performance
- Python ignores the distinction
Which statement correctly describes baselines?
- A simple baseline gives a model result a useful comparison.
- Only the example output matters, not the rule
- Every operation has the same behavior
What does multimode help represent?
- Only the arithmetic average
- Ties among most frequent values
- Python ignores the distinction
Which statement correctly describes standard deviation?
- Standard deviation expresses spread in the original measurement units.
- Only the example output matters, not the rule
- Every operation has the same behavior
Why can percentile calculations differ between tools?
- Percentiles are unrelated to ordering
- They can use different interpolation conventions
- Python ignores the distinction
Which statement correctly describes outlier meaning?
- An unusual observation may be an error or an important real event.
- Only the example output matters, not the rule
- Every operation has the same behavior
What kind of target does ordinary linear regression predict?
- Only a category label
- A numeric value
- Python ignores the distinction
Which statement correctly describes fitting and residuals?
- Fitting selects coefficients according to an objective, and residuals compare observed with predicted outcomes.
- Only the example output matters, not the rule
- Every operation has the same behavior
What does predict_proba provide?
- Guaranteed outcomes
- Estimated class probabilities
- Python ignores the distinction
Which statement correctly describes decision thresholds?
- A threshold turns a probability into a decision and should reflect the task tradeoffs.
- Only the example output matters, not the rule
- Every operation has the same behavior
Why scale mixed KNN features?
- To guarantee perfect accuracy
- Because distance depends on their magnitudes
- Python ignores the distinction
Which statement correctly describes hyperparameters?
- Tree depth and neighbor count are choices selected using training side validation.
- Only the example output matters, not the rule
- Every operation has the same behavior
Which observations should fit a preprocessing transformation?
- The full dataset including test observations
- Training observations
- Python ignores the distinction
Which statement correctly describes preprocessing?
- Learn transformations on training observations and apply the learned transformation to held out data.
- Only the example output matters, not the rule
- Every operation has the same behavior
Why include preprocessing inside the cross validation pipeline?
- To inspect the final test target
- To fit it separately on each training fold
- Python ignores the distinction
Which statement correctly describes metrics?
- A metric should match the outcome and operational consequences.
- Only the example output matters, not the rule
- Every operation has the same behavior
Do K-means cluster labels have inherent category meanings?
- Yes
- No
- Python ignores the distinction
Which statement correctly describes scaling and choices?
- Feature scale, cluster count and initialization affect the result.
- Only the example output matters, not the rule
- Every operation has the same behavior
What should you identify before adapting an example?
- Only its line count
- Its inputs, outputs and assumptions
- Python ignores the distinction
Which statement correctly describes variation?
- Changing one meaningful assumption tests whether the underlying idea is understood.
- Only the example output matters, not the rule
- Every operation has the same behavior
What should a challenge include besides an ordinary example?
- Only a time limit
- Boundary and adversarial cases
- Python ignores the distinction
Which statement correctly describes incremental solutions?
- A clear working approach can be improved after its behavior is verified.
- Only the example output matters, not the rule
- Every operation has the same behavior
Why attempt a problem before reading its solution?
- To guarantee a perfect first answer
- To expose your current reasoning and gaps
- Python ignores the distinction
Which statement correctly describes delayed solutions?
- Attempt the task and record a prediction before comparing a worked solution.
- Only the example output matters, not the rule
- Every operation has the same behavior
What makes an advanced exercise valuable?
- Only a larger line count
- Design and tradeoff decisions with evidence
- Python ignores the distinction
Which statement correctly describes advanced exercises?
- Advanced tasks ask for design, testing and performance decisions rather than merely longer syntax.
- Only the example output matters, not the rule
- Every operation has the same behavior
How should a missed quiz question guide study?
- Memorize the option position
- Review its explanation and apply the concept again
- Python ignores the distinction
Which statement correctly describes error analysis?
- A wrong answer is useful when its explanation identifies the mistaken rule.
- Only the example output matters, not the rule
- Every operation has the same behavior
What should the first project milestone provide?
- Every planned feature at once
- One small working behavior
- Python ignores the distinction
Which statement correctly describes milestones?
- Deliver one working behavior at a time with observable examples.
- Only the example output matters, not the rule
- Every operation has the same behavior
Which responsibility should be separated from stock arithmetic?
- The meaning of subtraction
- External file parsing
- Python ignores the distinction
Which statement correctly describes testing collaborators?
- Test pure logic directly and control external file dependencies with temporary data.
- Only the example output matters, not the rule
- Every operation has the same behavior
Do adjacent half open booking intervals overlap?
- Yes
- No
- Python ignores the distinction
Which statement correctly describes performance evidence?
- Measure a representative workload before choosing an optimization.
- Only the example output matters, not the rule
- Every operation has the same behavior
When should the separate machine learning track be approached?
- Before variables and collections
- After the core and relevant data science prerequisites
- Python ignores the distinction
Which statement correctly describes optional tracks?
- Database and web, data science, DSA and machine learning are goal dependent branches.
- Only the example output matters, not the rule
- Every operation has the same behavior
About the Python quiz
This Python quiz checks the ideas from every lesson in the course, from print() and variables to decorators, regular expressions and testing. Most questions show a few lines of code and ask what they print, because reading code and predicting its output is the single most useful skill when you're learning to program. Others check vocabulary such as "parameter", "immutable" or "exception", which you'll need when reading documentation and error messages.
If you're still in the beginner stage, choose Easy and pick a topic you've just finished, such as strings or loops. Once you've worked through the intermediate lessons, try Mixed with 10 questions: you'll meet lists, dictionaries and functions side by side, just as they appear in real programs. Save Exam mode for when you've finished the course; it hides the answers until the end, so it's an honest check of what you remember.
When you get a question wrong, read the explanation, then open the lesson linked in your results and look at its examples again. Mistakes in Python often come from small details: an index that starts at 0, a method that returns a new string instead of changing the old one, or an indent in the wrong place. Spotting those details in a quiz is exactly what makes them easy to avoid in your own code.
The question bank holds 289 questions drawn from 107 Python lessons: 119 easy, 144 medium and 26 hard. Every time you start, the quiz picks a fresh random selection that matches your settings, so retaking it is a good way to practise. After each answer, or at the end in exam mode, you'll see why the right answer is right, and every question you miss links back to the lesson that teaches it.
What the Python quiz covers
Beginner
- 1Python Introduction
- 2Python Syntax and Statements
- 3Python Comments
- 4Python The print() Function
- 5Python Variables and Data Types
- 6Python Naming and Multiple Assignment
- 7Python Numbers and Math
- 8Python Type Casting
- 9Python The None Value
- 10Python Strings
- 11Python String Formatting
- 12Python User Input with input()
- 13Python Boolean Values and Expressions
- 14Python Operators and Precedence
- 15Python if, elif and else
- 16Python The match Statement
- 17Python The pass Statement
- 18Python Loops
- 19Python Lists
Intermediate
- 20Python Dictionaries
- 21Python Tuples and Sets
- 22Python range() in Depth
- 23Python Arrays in Python
- 24Python Advanced Collection Methods
- 25Python Copying and Joining Collections
- 26Python Functions
- 27Python Function Arguments and Scope
- 28Python Recursion
- 29Python List Comprehensions
- 30Python Error Handling
- 31Python File Handling
- 32Python Modules and Packages
- 33Python Dates and Times
Advanced
- 34Python Classes and Objects
- 35Python Inheritance
- 36Python Magic Methods
- 37Python Class Methods and Properties
- 38Python Polymorphism and Inner Classes
- 39Python Type Hints and Dataclasses
- 40Python Iterators and Generators
- 41Python Iterators vs. Iterables
- 42Python Context Managers
- 43Python Decorators
- 44Python Regular Expressions
- 45Testing Python Code
- 46Working with Web APIs in Python
Files and Standard Library
- 47Python Read, Write, Create and Delete Files
- 48Python JSON Handling
- 49Python CSV Handling in Depth
- 50Python File and Directory Operations
- 51Python Built-in Functions Reference
- 52Python String and Collection Methods Reference
- 53Python Exception Types Reference
- 54Python Keywords and Glossary
- 55Python Standard Library Essentials
- 56Python Environment Variables and Configuration
- 57Python pip and Virtual Environments
Professional Development
- 58Python Debugging Python Programs
- 59Python Logging
- 60Python Unit Testing and pytest
- 61Python Mocking and Test Fixtures
- 62Python Code Style and PEP 8
- 63Python Type Checking and Type Hinting
- 64Python Virtual Environments and Dependencies
- 65Python Git and Python Projects
- 66Python Interview Questions and Answers
Database and Web Track
Data Science Track
DSA Track
Machine Learning Track
- 90Python Introduction to Machine Learning
- 91Python Mean, Median, Mode and Deviation
- 92Python Data Distribution and Percentiles
- 93Python Linear and Multiple Regression
- 94Python Logistic Regression
- 95Python Decision Trees and K-Nearest Neighbors
- 96Python Training and Testing Datasets
- 97Python Cross-Validation and Evaluation
- 98Python Clustering and K-Means