Python Exercises with Answers
Practise Python with 289 interactive exercises: multiple choice, fill-in-the-blank, output prediction and debugging. Every exercise gives instant feedback, a hint and the full solution.
Topic All topics Introduction Syntax and Statements Comments The print() Function Variables & Data Types Naming and Multiple Assignment Numbers & Math Type Casting The None Value Strings String Formatting User Input with input() Boolean Values and Expressions Operators and Precedence if / elif / else The match Statement The pass Statement Loops (for & while) Lists Dictionaries Tuples & Sets range() in Depth Arrays in Python Advanced Collection Methods Copying and Joining Collections Functions Arguments & Scope Recursion Comprehensions & Lambda Errors & Exceptions Files (Text, CSV, JSON) Modules, pip & venv Dates & Times Classes & Objects Inheritance Python Magic Methods Class Methods and Properties Polymorphism and Inner Classes Type Hints & Dataclasses Iterators & Generators Iterators vs. Iterables Context Managers Decorators Regular Expressions Testing Web APIs & requests Read, Write, Create and Delete Files JSON Handling CSV Handling in Depth File and Directory Operations Built-in Functions Reference String and Collection Methods Reference Exception Types Reference Python Keywords and Glossary Standard Library Essentials Environment Variables and Configuration pip and Virtual Environments Debugging Python Programs Logging Unit Testing and pytest Mocking and Test Fixtures Code Style and PEP 8 Type Checking and Type Hinting Virtual Environments and Dependencies Git and Python Projects Interview Questions and Answers Database Connections and Queries SQL CRUD with Python Python MySQL Tutorial Python MongoDB Tutorial HTTP Requests and REST APIs API Authentication and Errors A Simple Python Web Server Introduction to Flask NumPy Tutorial Pandas Tutorial Matplotlib Tutorial Data Cleaning and Analysis Statistics with Python Line, Bar, Scatter and Histogram Charts Time and Space Complexity Linear and Binary Search Sorting Algorithms Stacks and Queues Linked Lists Hash Tables Trees and Binary Search Trees Graphs and Graph Traversal Recursive Problem Solving Introduction to Machine Learning Mean, Median, Mode and Deviation Data Distribution and Percentiles Linear and Multiple Regression Logistic Regression Decision Trees and K-Nearest Neighbors Training and Testing Datasets Cross-Validation and Evaluation Clustering and K-Means Python Examples Library Python Coding Challenges Python Practice Problems Python Exercises by Difficulty Python Quizzes by Chapter Beginner Python Projects Intermediate Python Projects Advanced Python Projects Study Plan and Learning Roadmap
All types Fill in the blanks Predict the output Multiple choice
Any level Easy Medium Hard
Score 0 / 289
Complete the line so it shows the text Python is fun on screen.
( "Python is fun" )
print() displays whatever is inside its brackets.
Check answer Show solution
What does this program print?
print ( "Score:" , 4 * 5 )
A Score: 4 * 5 B Score:20 C 20 D Score: 20
The calculation runs first, then print() joins the two values with a space.
Show answer
Which line is a comment in Python?
A // total price B # total price C <!-- total price --> D /* total price */
Python comments start with #. The others are comments in JavaScript, HTML and CSS.
Show answer
print ( 17 // 5 , 17 % 5 )
A 3.4 2 B 3 3 C 3 2 D 2 3
17 // 5 is 3 (whole times 5 fits), and 17 % 5 is the remainder, 2.
Show answer
print ( "Total:" , 2 + 3 )
A Total: 5 B Total: 2 + 3 C Total:5 D "Total:" 5
print() works out 2 + 3 first, and puts a space between its arguments.
Show answer
What defines a Python statement block?
A Consistent indentation B Curly braces C The answer depends only on the displayed label
The indented statements belong to the same suite.
Hint: Review expressions and the relevant contract.
Which review concern is valid for syntax and statements?
A A syntax error can originate before the highlighted line. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
Python checks the source grammar before running ordinary statements.
Show answer
Which keyword changes the text between printed arguments?
A sep B end C The answer depends only on the displayed label
sep separates arguments and end follows the last one.
Hint: Review arguments and the relevant contract.
Which review concern is valid for the print() function?
A Assigning the result of print does not capture the displayed text. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
file selects a writable text stream, while print itself returns None.
Show answer
x = 5
x = x * 2
x += 1
print ( x)
A 11 B 5 C 10 D 12
x becomes 10, then 11.
Show answer
A 42 B "42" C 4.2 D True
The quotes make "42" text, even though it looks like a number.
Show answer
The user types 7. What does this print?
n = input ( "Number: " )
print ( n * 3 )
A 21 B 7 7 7 C 777 D TypeError
n is the string "7", and multiplying a string by 3 repeats it three times.
Show answer
Which variable name is valid in Python?
A 2nd_place B first_name C first-name D class
Names can't start with a digit, can't contain hyphens and can't be keywords like class.
Show answer
What does a = b = [] create?
A Two references to one list B Two independent lists C The answer depends only on the displayed label
There is only one list object on the right side.
Hint: Review names and the relevant contract.
Which review concern is valid for naming and multiple assignment?
A a = b = [] does not create two lists. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
Chained assignment gives several names the same object.
Show answer
Complete the code so it prints the remainder when 17 is divided by 5.
print ( 17 5 )
% is the remainder operator, and 17 % 5 is 2.
Check answer Show solution
print ( 9 / 3 , 9 // 2 )
A 3 4 B 3.0 4.5 C 3.0 4 D 3 4.5
/ always gives a float, and // gives the whole part of 4.5.
Show answer
x = 4
x += 2
x *= 3
print ( x)
A 14 B 12 C 24 D 18
x becomes 6, then 6 times 3 is 18.
Show answer
Which expression equals 20?
A 2 + 3 * 4 B 2 ** 3 + 4 C (2 + 3) * 4 D 20 // 3
Brackets are calculated first: 5 times 4.
Show answer
You need enough buses for 130 people, 50 per bus. Which gives the right answer?
A 130 // 50 B math.ceil(130 / 50) C round(130 / 50) D int(130 / 50)
2.6 buses must be rounded up to 3; the others give 2 or 3 only by luck.
Show answer
What does int(-3.8) produce?
A -3 B -4 C The answer depends only on the displayed label
The conversion truncates toward zero.
Hint: Review conversion functions and the relevant contract.
Which review concern is valid for type casting?
A A nonempty false string is still truthy. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
bool follows truth value rules rather than parsing words.
Show answer
Which test specifically checks for None?
A value is None B not value C The answer depends only on the displayed label
Identity distinguishes None from zero or an empty value.
Hint: Review absent values and the relevant contract.
Which review concern is valid for the none value?
A A mutable default list would be shared. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
None can mark an omitted argument so a fresh collection is created inside the function.
Show answer
Complete the code so it prints HELLO.
word = "hello"
print ( word. ( ) )
upper() returns a copy of the string in capital letters.
Check answer Show solution
s = "Python"
print ( s[ 1 : 4 ] )
A Pyt B yth C ytho D tho
The slice starts at index 1 ("y") and stops before index 4.
Show answer
tags = "html, css, js"
print ( [ t. strip ( ) for t in tags. split ( "," ) ] )
A ['html', 'css', 'js'] B ['html', ' css', ' js'] C ['html, css, js'] D html css js
split(",") cuts at each comma, then strip() removes the leftover spaces from each part.
Show answer
What does "banana".find("x") return?
A 0 B None C -1 D An error
find() returns -1 when there's no match. index() would raise an error instead.
Show answer
A True B False C The answer depends only on the displayed label
The string is nonempty.
Hint: Review literals and the relevant contract.
Which review concern is valid for boolean values and expressions?
A These operators do not always return boolean objects. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
and and or evaluate only the operands they need and can return an operand.
Show answer
What does 2 + 3 * 4 evaluate to?
A 14 B 20 C The answer depends only on the displayed label
Multiplication has higher precedence than addition.
Hint: Review arithmetic types and the relevant contract.
Which review concern is valid for operators and precedence?
A Powers associate to the right and interact with unary minus. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
Higher precedence operators group first, and parentheses make the intended grouping clear.
Show answer
x = 10
if x > 5 :
print ( "big" )
elif x > 8 :
print ( "bigger" )
else :
print ( "small" )
A bigger B big then bigger C small D big
Python stops at the first true branch, so the elif is never checked.
Show answer
Which condition is True when age is between 13 and 19, inclusive?
A 13 < age < 19 B age >= 13 or age <= 19 C age == 13 to 19 D 13 <= age <= 19
<= includes both ends. The "or" version is true for every age.
Show answer
logged_in = False
is_admin = True
if logged_in and is_admin:
print ( "Admin panel" )
elif not logged_in:
print ( "Please log in" )
else :
print ( "Welcome" )
A Please log in B Admin panel C Welcome D Nothing
logged_in is False, so the "and" test fails, and "not logged_in" is True.
Show answer
age = 15
if age >= 18 :
print ( "adult" )
elif age >= 13 :
print ( "teen" )
elif age >= 5 :
print ( "child" )
A adult B teen and child C teen D child
Only the first true branch runs; later elif checks are skipped.
Show answer
What does a bare name normally do in a match pattern?
A Capture a value B Look up an existing constant C The answer depends only on the displayed label
A capture pattern binds a value to its name.
Hint: Review availability and the relevant contract.
Which review concern is valid for the match statement?
A A bare name does not normally compare against an existing variable. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
A bare name captures the subject while underscore ignores it.
Show answer
Does pass skip the rest of a loop iteration?
A No B Yes C The answer depends only on the displayed label
pass does nothing and execution continues.
Hint: Review empty blocks and the relevant contract.
Which review concern is valid for the pass statement?
A Silently passing inside broad exception handling hides failures. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
NotImplementedError can expose a required behavior that has not been implemented.
Show answer
What numbers does this print?
for i in range ( 2 , 9 , 3 ) :
print ( i)
A 2 3 4 5 6 7 8 B 2 5 8 C 2 5 8 11 D 3 6 9
Start at 2 and add 3 each time, stopping before 9.
Show answer
n = 1
while n < 20 :
n = n * 3
print ( n)
A 9 B 20 C 81 D 27
n goes 1, 3, 9, 27. At 27 the condition is false, so the loop stops.
Show answer
Which keyword skips the rest of the current pass and moves to the next one?
A break B continue C pass D skip
continue jumps to the next pass; break leaves the loop completely.
Show answer
total = 0
for n in range ( 1 , 5 ) :
total += n
print ( total)
A 10 B 15 C 4 D 5
range(1, 5) gives 1, 2, 3 and 4, which add up to 10.
Show answer
Fill in the blankseasy Lists Complete the code so "pear" is added to the end of the list.
fruit = [ "apple" , "plum" ]
fruit. ( "pear" )
print ( fruit)
append() adds one item to the end of a list.
Check answer Show solution
Predict the outputeasy Lists
letters = [ "a" , "b" , "c" , "d" ]
print ( letters[ 1 ] , letters[ - 1 ] )
A b d B a d C b c D a c
Index 1 is the second item; -1 is the last.
Show answer
Predict the outputmedium Lists
nums = [ 10 , 20 , 30 , 40 , 50 ]
print ( nums[ 1 : 4 ] )
A [10, 20, 30, 40] B [20, 30, 40, 50] C [20, 30, 40] D [10, 20, 30]
The slice starts at index 1 and stops before index 4.
Show answer
Multiple choicemedium Lists Which line removes and returns the last item of a list called stack?
A stack.remove() B stack.delete(-1) C stack[-1] = None D stack.pop()
pop() with no argument removes the last item and gives it back.
Show answer
Predict the outputmedium Lists
nums = [ 4 , 8 , 15 , 16 , 23 ]
print ( nums[ 1 : 3 ] , nums[ - 1 ] )
A [4, 8, 15] 4 B [8, 15] 23 C [8, 15, 16] 23 D [4, 8] 16
A slice stops before index 3, and -1 is the last item.
Show answer
Complete the code so it prints Lisbon.
capitals = { "Portugal" : "Lisbon" , "Spain" : "Madrid" }
print ( capitals[ " "])
Read a value by putting its key in square brackets.
Check answer Show solution
d = { "a" : 1 , "b" : 2 }
d[ "a" ] = 10
d[ "c" ] = 3
print ( len ( d) , d[ "a" ] )
A 3 10 B 2 1 C 3 1 D 4 10
"a" is updated, "c" is added, so there are 3 keys and a is 10.
Show answer
stock = { "pens" : 12 }
print ( stock. get ( "pencils" , 0 ) + stock. get ( "pens" , 0 ) )
A An error B 12 C 0 D None
get() returns 0 for the missing key, so the result is 0 + 12.
Show answer
Which loop gives you both the key and the value?
A for k in d: B for v in d.values(): C for k, v in d.items(): D for k, v in d:
items() produces key-value pairs.
Show answer
d = { "x" : 1 , "x" : 2 }
print ( d)
A {'x': 1} B {'x': 2} C {'x': 1, 'x': 2} D An error
Keys are unique; the later value replaces the earlier one.
Show answer
Complete the code so it unpacks the tuple into two variables.
size = ( 1920 , 1080 )
, height = size
The variables on the left receive the tuple's items in order.
Check answer Show solution
nums = { 4 , 2 , 4 , 2 , 4 }
print ( len ( nums) )
A 5 B 3 C 1 D 2
A set keeps only the unique values: 2 and 4.
Show answer
a = { 1 , 2 , 3 , 4 }
b = { 3 , 4 , 5 }
print ( sorted ( a - b) , sorted ( a & b) )
A [1, 2] [3, 4] B [5] [3, 4] C [1, 2, 5] [3, 4] D [1, 2] [1, 2, 3, 4, 5]
a - b keeps 1 and 2; a & b keeps the shared 3 and 4.
Show answer
Which line creates an empty set?
A s = {} B s = set() C s = [] D s = ()
{} creates an empty dictionary.
Show answer
Which collection best stores a GPS position that must never be edited?
A A list B A set C A tuple D A dictionary with no keys
Tuples are ordered and immutable, ideal for fixed pairs like coordinates.
Show answer
Which boundary is excluded by range?
A The stop B The start C The answer depends only on the displayed label
range uses a half open interval.
Hint: Review boundaries and the relevant contract.
Which review concern is valid for range() in depth?
A range is not the right tool for every collection loop. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
Ranges support indexing, slicing, length and integer membership.
Show answer
What restricts values in array.array?
A Its selected type code B Nothing C The answer depends only on the displayed label
The type code selects the supported basic representation.
Hint: Review representations and the relevant contract.
Which review concern is valid for arrays in python?
A List multiplication repeats elements rather than scaling them. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
NumPy supplies multidimensional arrays and vectorized calculations as a separate package.
Show answer
Which operation finds shared set members?
A Intersection B Union C The answer depends only on the displayed label
Intersection retains the values present in both sets.
Hint: Review list mutation and the relevant contract.
Which review concern is valid for advanced collection methods?
A get does not insert its default into the mapping. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
get reads with a default while update merges and setdefault can insert.
Show answer
What stays shared after a shallow copy?
A Nested objects B The new outer container C The answer depends only on the displayed label
Only the outer container is independently copied.
Hint: Review aliasing and the relevant contract.
Which review concern is valid for copying and joining collections?
A Conflicting keys require a deliberate resolution policy. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
List concatenation creates a new sequence, extend mutates, and later dictionary keys replace earlier duplicates.
Show answer
def add ( a, b= 10 ) :
return a + b
print ( add ( 5 ) , add ( 5 , 1 ) )
A 15 15 B 5 6 C 15 6 D 6 15
Without a second argument, b uses its default of 10.
Show answer
def shout ( word) :
print ( word. upper ( ) )
result = shout ( "hey" )
print ( result)
A HEY then HEY B HEY then None C None then HEY D hey then HEY
shout prints but returns nothing, so result is None.
Show answer
Which definition is valid?
A def order(size="large", drink): B def order(drink, size="large") C function order(drink, size="large"): D def order(drink, size="large"):
Parameters with defaults must come last, and the line needs def and a colon.
Show answer
What does this function return when called as check(-2)?
def check ( n) :
if n > 0 :
return "positive"
A "negative" B 0 C None D An error
No return statement runs for -2, so the function returns None.
Show answer
Complete the definition so the function accepts any number of names.
def greet_all ( names) :
for name in names:
print ( "Hi" , name)
A single star collects positional arguments into a tuple.
Check answer Show solution
def count ( * things) :
return len ( things)
print ( count ( "a" , "b" , "c" ) )
A 1 B 0 C 3 D ('a', 'b', 'c')
things is a tuple of three items.
Show answer
def show ( ** info) :
print ( sorted ( info) )
show ( b= 2 , a= 1 )
A {'b': 2, 'a': 1} B [1, 2] C ['a', 'b'] D TypeError
info is a dictionary, and sorting a dictionary gives its sorted keys.
Show answer
Given def book(room, *, nights):, which call works?
A book(5, nights=2) B book(5, 2) C book(room=5, 2) D book(nights=2)
nights is keyword-only, and room is required.
Show answer
def f ( x, items= [ ] ) :
items. append ( x)
return len ( items)
f ( 1 )
print ( f ( 2 ) )
A 1 B 2 C 0 D An error
The default list is shared, so it already holds 1 when 2 is added.
Show answer
What terminates recursive descent?
A A reachable base case B A print statement C The answer depends only on the displayed label
A base case completes without making another recursive call.
Hint: Review recursive step and the relevant contract.
Which review concern is valid for recursion?
A Forgetting return loses the computed result. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
The current step combines its contribution with the smaller result.
Show answer
print ( [ len ( w) for w in [ "hi" , "hello" , "hey" ] ] )
A ['hi', 'hello', 'hey'] B 10 C [5] D [2, 5, 3]
len() is applied to each word.
Show answer
print ( [ n for n in range ( 1 , 11 ) if n % 3 == 0 ] )
A [0, 3, 6, 9] B [3, 6, 9] C [3, 6, 9, 12] D [1, 4, 7, 10]
Only the multiples of 3 between 1 and 10 are kept.
Show answer
words = [ "bb" , "a" , "ccc" ]
print ( sorted ( words, key= lambda w: len ( w) ) )
A ['a', 'bb', 'ccc'] B ['ccc', 'a', 'bb'] C ['ccc', 'bb', 'a'] D ['bb', 'a', 'ccc']
The words are compared by their length, shortest first.
Show answer
Which line builds the dictionary {'a': 'A', 'b': 'B'}?
A [c: c.upper() for c in "ab"] B {c.upper() for c in "ab"} C {c: c.upper() for c in "ab"} D dict(c.upper() for c in "ab")
Curly braces with key: value make a dictionary comprehension.
Show answer
try :
print ( 10 / 0 )
except ZeroDivisionError :
print ( "Oops" )
A 0 B Oops C inf D A traceback
Dividing by zero raises ZeroDivisionError, which is caught.
Show answer
try :
x = int ( "7" )
except ValueError :
print ( "A" )
else :
print ( "B" )
finally :
print ( "C" )
A B then C B A then C C A, B then C D C only
No error happened, so else runs, then finally.
Show answer
Which exception does {"a": 1}["b"] raise?
A IndexError B ValueError C KeyError D NameError
The dictionary has no key "b".
Show answer
Why is except: with no exception type usually a bad idea?
A It's a syntax error B It runs twice C It only works in loops D It also catches unexpected errors, including bugs, and hides them
Catch the specific errors you expect instead.
Show answer
Which mode adds text to the end of a file without deleting what's there?
A "r" B "w" C "a" D "x"
"a" means append.
Show answer
A file contains the two lines hi and there. What does this print?
with open ( "f.txt" , encoding= "utf-8" ) as f:
print ( f. readlines ( ) )
A ['hi', 'there'] B ['hi\n', 'there\n'] C hi there D 2
readlines() keeps the newline at the end of each line.
Show answer
Which function saves a Python dictionary to a file as JSON?
A json.dump() B json.save() C json.write() D json.loads()
dump writes to a file; load reads from one.
Show answer
Why is csv.DictReader handy?
A It converts every value to a number B It gives each row as a dictionary keyed by the column names C It sorts the rows D It only reads the first row
You can write row["price"] instead of remembering column positions.
Show answer
Which command installs a package from PyPI?
A python install requests B import requests --install C py get requests D pip install requests
pip is Python's package installer.
Show answer
import math
print ( math. ceil ( 4.1 ) , math. floor ( 4.9 ) )
A 4 4 B 5 4 C 4 5 D 5 5
ceil rounds up and floor rounds down.
Show answer
What does if __name__ == "__main__": do?
A Runs the block when the file is imported B Makes the file a package C Defines the main function D Runs the block only when the file is executed directly
When imported, __name__ is the module's name, not "__main__".
Show answer
Why use a virtual environment for each project?
A It makes Python run faster B Each project gets its own packages and versions, without conflicts C It's required to use the standard library D It hides your code from others
Different projects often need different versions of the same package.
Show answer
Complete the code so it prints today's date.
from datetime import date
print ( date. ( ) )
date.today() returns the current date.
Check answer Show solution
from datetime import date
d = date ( 2025 , 7 , 4 )
print ( d. strftime ( "%d/%m/%Y" ) )
A 04/07/2025 B 7/4/2025 C 2025-07-04 D 4 July 2025
%d and %m are padded to two digits.
Show answer
from datetime import date
print ( ( date ( 2025 , 3 , 10 ) - date ( 2025 , 2 , 28 ) ) . days )
A 9 B 11 C 12 D 10
2025 isn't a leap year, so 1 March is the day after 28 February and the gap is 10 days.
Show answer
Which call reads "31-01-2025" into a datetime?
A datetime.strftime("31-01-2025", "%d-%m-%Y") B datetime.strptime("31-01-2025", "%d-%m-%Y") C date("31-01-2025") D datetime.parse("31-01-2025")
strptime parses text; strftime formats a date.
Show answer
A It's the same everywhere and isn't affected by daylight saving, so times can be converted to any zone B UTC is faster to calculate C Local time can't be printed D Python requires it
Convert to local time only for display.
Show answer
class Cat :
def __init__ ( self , name) :
self . name = name
a = Cat ( "Tom" )
b = Cat ( "Kit" )
print ( b. name )
A Tom B Kit C Cat D An error
Each object has its own name attribute.
Show answer
class Counter :
def __init__ ( self ) :
self . count = 0
def click ( self ) :
self . count += 1
return self
c = Counter ( )
c. click ( ) . click ( ) . click ( )
print ( c. count )
A 1 B 0 C An error D 3
click() returns the object itself, so the calls can be chained three times.
Show answer
What is self in a method?
A The object the method was called on B The class itself C A copy of the object D A keyword that must be the last parameter
rex.bark() passes rex as self.
Show answer
Which method controls what print(obj) shows?
A __init__ B __print__ C __str__ D display
print() calls str(), which calls __str__.
Show answer
Complete the line so Truck inherits from Vehicle.
class Truck ( ) :
pass
Put the parent class in brackets after the child's name.
Check answer Show solution
Complete the constructor so the parent sets up the name first.
class Student ( Person ) :
def __init__ ( self , name, school) :
( ) . __init__ ( name)
self . school = school
super() gives access to the parent class's methods.
Check answer Show solution
class A:
def hello ( self ) :
return "A"
class B ( A) :
def hello ( self ) :
return "B" + super ( ) . hello ( )
print ( B ( ) . hello ( ) )
A A B BA C B D AB
B's version runs, then adds the result of A's version.
Show answer
class Shape : pass
class Square ( Shape ) : pass
print ( isinstance ( Square ( ) , Shape ) , isinstance ( Shape ( ) , Square ) )
A True False B True True C False True D False False
A Square is a Shape, but a plain Shape isn't a Square.
Show answer
A Library contains many Book objects. How should you model it?
A class Library(Book) B class Book(Library) C Copy Book's methods into Library D Give Library an attribute holding a list of Book objects
A library has books, so use composition.
Show answer
Which method is intended for diagnostic representation?
A __repr__ B __str__ only C The answer depends only on the displayed label
repr uses __repr__ to describe an object for inspection.
Hint: Review special protocols and the relevant contract.
Which review concern is valid for Python magic methods?
A Changing equality can affect instance hashability. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
__eq__ and ordering methods define comparisons for supported types.
Show answer
Why store _capacity in the property setter?
A To avoid recursive setter calls B To enforce secrecy C The answer depends only on the displayed label
The underscore storage name avoids invoking the capacity property again.
Hint: Review instance methods and the relevant contract.
Which review concern is valid for class methods and properties?
A Assigning capacity within its own setter recursively calls the setter. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
Properties combine attribute access with validation through getters and setters.
Show answer
Does a nested class automatically receive an outer instance?
A No B Yes C The answer depends only on the displayed label
Nesting supplies a namespace rather than an automatic outer reference.
Hint: Review shared interface and the relevant contract.
Which review concern is valid for polymorphism and inner classes?
A Its instances do not automatically receive an outer instance. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
A nested class belongs to the outer class namespace.
Show answer
Complete the hint so the function is marked as returning a string.
def initials ( name: str ) str :
return name[ 0 ]
-> introduces the return type.
Check answer Show solution
What does the hint list[int] mean?
A A list containing exactly one int B A list whose items are ints C An int called list D A list of any type
The type in brackets describes the items.
Show answer
from dataclasses import dataclass
@dataclass
class Point :
x: int
y: int = 0
print ( Point ( 3 ) )
A Point(x=3, y=0) B Point(3) C <Point object> D TypeError
The generated __repr__ shows every field, including the default.
Show answer
Which hint means "a string or nothing"?
A str + None B str & None C str | None D maybe[str]
The | symbol creates a union of types.
Show answer
Why does @dataclass(frozen=True) let objects be used as dictionary keys?
A Frozen objects are smaller B They can't change, so Python can safely give them a fixed hash C Dictionary keys must be dataclasses D It converts them to strings
Keys must stay the same for as long as they're in the dictionary.
Show answer
Complete the generator so it produces the numbers 1, 2 and 3.
def one_two_three ( ) :
for n in [ 1 , 2 , 3 ] :
n
yield hands out a value and pauses the function.
Check answer Show solution
it = iter ( "hi" )
print ( next ( it) , next ( it) )
A hi hi B h i C h h D StopIteration
Each next() returns the next character.
Show answer
def gen ( ) :
yield 1
yield 2
g = gen ( )
print ( list ( g) , list ( g) )
A [1, 2] [1, 2] B [1] [2] C [1, 2] [] D An error
The first list() uses up the generator.
Show answer
Which creates a generator expression?
A [x * 2 for x in data] B {x * 2 for x in data} C <x * 2 for x in data> D (x * 2 for x in data)
Round brackets make a generator; square brackets a list; curly brackets a set.
Show answer
Why is a generator good for a 20 GB log file?
A It processes one line at a time, so memory use stays tiny B It reads the file faster from disk C It compresses the file D It sorts the lines automatically
Lazy evaluation avoids loading everything at once.
Show answer
What happens to an exhausted iterator in a for loop?
A The loop finishes B It restarts C The answer depends only on the displayed label
for handles the exhaustion signal and stops.
Hint: Review iterable contract and the relevant contract.
Which review concern is valid for iterators vs. iterables?
A Collecting an unbounded stream in a list cannot finish. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
Containers often create fresh independent iterators while a generator object is normally one iterator.
Show answer
Where should essential contextmanager cleanup go?
A In finally around yield B Only before yield C The answer depends only on the displayed label
finally performs cleanup when the managed block exits.
Hint: Review resource lifetime and the relevant contract.
Which review concern is valid for context managers?
A The generator must yield exactly once. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
contextmanager divides setup and cleanup around one yield.
Show answer
Complete the line that applies the timed decorator to the function.
timed
def build_report ( ) :
. . .
The @ symbol applies a decorator.
Check answer Show solution
What is @shout above def hello(): shorthand for?
A hello = shout B shout = hello(shout) C hello = shout(hello) D hello(shout)
The decorator receives the function and its result replaces the name.
Show answer
def twice ( func) :
def wrapper ( ) :
func ( )
func ( )
return wrapper
@twice
def hi ( ) :
print ( "hi" )
hi ( )
A hi, then hi again on a new line B hi C Nothing D An error
wrapper calls the original function two times.
Show answer
Why does a wrapper use *args, **kwargs?
A To make it faster B To create global variables C Decorators require it D So it can accept and pass on any arguments the decorated function needs
The decorator can then be used on any function.
Show answer
What does @functools.wraps(func) do?
A Caches results B Runs func twice C Copies the original function's name and docstring to the wrapper D Makes func private
Error messages and help() then show the real name.
Show answer
Complete the pattern so it finds all whole numbers in the text.
re. findall ( r"\d ", " 3 cats and 12 dogs")
\d+ matches one or more digits in a row.
Check answer Show solution
import re
print ( re. findall ( r"[aeiou]" , "regex" ) )
A ['regex'] B ['r', 'g', 'x'] C 2 D ['e', 'e']
findall returns each vowel found.
Show answer
import re
print ( re. sub ( r"\d" , "#" , "PIN 4821" ) )
A PIN # B #### 4821 C PIN #### D PIN 4821
Each single digit is replaced separately.
Show answer
Which pattern matches exactly a UK-style time like 09:45?
A \d{2}:\d{2} B \d:\d C \w+:\w+ D .{5}
Two digits, a colon and two digits. The others match too much or too little.
Show answer
Why use re.fullmatch for validation instead of re.search?
A It's faster B search can't use groups C fullmatch ignores capital letters D search succeeds if any part of the text matches, so invalid input can pass
fullmatch requires the whole text to match the pattern.
Show answer
Complete the test so it checks that add(2, 3) returns 5.
def test_add ( ) :
add ( 2 , 3 ) == 5
assert raises an error if the condition is False, which fails the test.
Check answer Show solution
Which file name will pytest discover automatically?
A grades.py B test_grades.py C tests_for_grades.txt D grades_check.py
pytest looks for files named test_*.py (or *_test.py).
Show answer
How do you test that a function raises ValueError?
A assert func() == ValueError B with pytest.raises(ValueError): func() C try: func() except: pass D @pytest.raises(ValueError)
The with block passes only if that exception is raised inside it.
Show answer
A parametrized test has 4 sets of values. How many results does pytest report for it?
A 1 B 8 C It depends on the names D 4
Each set of values runs as a separate test.
Show answer
Where do bugs most often hide, and so where should test cases focus?
A Only on typical values B On random values C At boundaries, such as 0, empty lists and the exact limits of each range D Only on invalid input
Off-by-one mistakes appear at the edges.
Show answer
Complete the line so the JSON response is converted into Python objects.
data = response. ( )
.json() parses the response body.
Check answer Show solution
Which status code means "not found"?
A 200 B 201 C 500 D 404
404 means the address doesn't exist.
Show answer
What does params={"q": "cats"} do in requests.get?
A Sends a JSON body B Adds ?q=cats to the address C Sets a header D Saves to a file
params builds the query string safely.
Show answer
r.status_code is 500 and you call r.raise_for_status(). What happens?
A Nothing B It returns False C An HTTPError is raised D It retries automatically
Any 400 or 500 code raises HTTPError.
Show answer
Where should an API key live?
A In an environment variable or a .env file excluded from Git B In the Python file, as a constant C In the README D In the URL of every request, shared publicly
Keys in code end up shared with anyone who sees the file.
Show answer
Which mode refuses to overwrite an existing file?
A x B w C The answer depends only on the displayed label
Exclusive creation fails if the path already exists.
Hint: Review modes and the relevant contract.
Which review concern is valid for read, write, create and delete files?
A Deletion is irreversible without another retained copy. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
Path.unlink removes a file while directory removal uses different operations.
Show answer
Which function decodes JSON from a string?
A json.loads B json.load C The answer depends only on the displayed label
loads takes JSON text while load reads a file object.
Hint: Review data mapping and the relevant contract.
Which review concern is valid for json handling?
A Untrusted JSON can be valid yet unsuitable for the application. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
Parsing checks JSON syntax but application rules still need validation.
Show answer
What type is a numeric field returned by DictReader?
A str B int C The answer depends only on the displayed label
CSV does not normally infer numeric types.
Hint: Review csv structure and the relevant contract.
Which review concern is valid for csv handling in depth?
A Encoding and dialect must match the actual export. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
Opening CSV files with newline empty lets the CSV module manage line endings.
Show answer
Does creating a Path object create a filesystem entry?
A No B Yes C The answer depends only on the displayed label
A Path represents a location; filesystem methods perform actual operations.
Hint: Review path objects and the relevant contract.
Which review concern is valid for file and directory operations?
A Recursive removal requires careful verification of the intended target. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
rename moves a path while unlink removes files and rmdir removes empty directories.
Show answer
What does ordinary zip do with unequal iterable lengths?
A Stop at the shortest B Fill missing values automatically C The answer depends only on the displayed label
Default zip stops when an input is exhausted.
Hint: Review inspection and the relevant contract.
Which review concern is valid for built-in functions reference?
A Construction can consume an iterator and allocate memory. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
list, tuple, set and dict construct collections while int, float and str construct common scalar values.
Show answer
Which method changes a list in place?
A list.sort B sorted C The answer depends only on the displayed label
sort mutates the list while sorted returns a new list.
Hint: Review strings and the relevant contract.
Which review concern is valid for string and collection methods reference?
A Sets require hashable members and do not retain duplicates. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
Tuples provide count and index while sets provide membership operations and update methods.
Show answer
Which exception normally describes invalid integer text?
A ValueError B KeyError C The answer depends only on the displayed label
The argument type is acceptable text, but its value cannot represent an integer.
Hint: Review value and type errors and the relevant contract.
Which review concern is valid for exception types reference?
A BaseException also covers signals such as KeyboardInterrupt that applications should usually not swallow. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
Catch the specific expected exception close to the operation that can raise it.
Show answer
Is print normally a reserved Python keyword?
A No B Yes C The answer depends only on the displayed label
print is a built-in name and can be rebound, though doing so is usually confusing.
Hint: Review reserved keywords and the relevant contract.
Which review concern is valid for Python keywords and glossary?
A A name is a binding to an object rather than a box with a permanently fixed type. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
Mutable objects can change state, iterables supply traversal and exceptions signal failures.
Show answer
Which standard library type counts repeated values?
A Counter B Path C The answer depends only on the displayed label
Counter maps values to occurrence counts.
Hint: Review os and sys and the relevant contract.
Which review concern is valid for standard library essentials?
A Sample and population standard deviation use different denominators. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
mean, median and standard deviation summarize numeric observations.
Show answer
What type does os.getenv return when it finds a value?
A str B int C The answer depends only on the displayed label
Environment values arrive as text and need explicit parsing.
Hint: Review environment values and the relevant contract.
Which review concern is valid for environment variables and configuration?
A A .env file is not automatically loaded by Python or safe to commit. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
Credentials belong outside published source and should not appear in ordinary log messages.
Show answer
Which form selects pip for a chosen Python interpreter?
A python -m pip B An unrelated pip executable C The answer depends only on the displayed label
Running pip as a module ties it to the selected interpreter.
Hint: Review environment isolation and the relevant contract.
Which review concern is valid for pip and virtual environments?
A Environment directories should usually stay out of version control. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
Activation adjusts shell command lookup, and environments can also be used through their executable paths.
Show answer
What makes a useful debugging hypothesis?
A A prediction you can test B A random code change C The answer depends only on the displayed label
A testable prediction directs the next observation.
Hint: Review reproduction and the relevant contract.
Which review concern is valid for debugging python programs?
A Random edits can conceal the underlying problem. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
A focused hypothesis predicts what evidence would confirm or reject a cause.
Show answer
Where does logger.exception normally capture exception context?
A Inside an exception handler B Before any exception occurs C The answer depends only on the displayed label
It includes the current handled exception information.
Hint: Review log levels and the relevant contract.
Which review concern is valid for logging?
A Credentials and personal records should not appear in routine logs. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
logger.exception records exception context inside an exception handler.
Show answer
Why test an exact capacity boundary?
A To detect off by one mistakes B To guarantee every possible input C The answer depends only on the displayed label
Boundary cases distinguish neighboring behaviors.
Hint: Review test contracts and the relevant contract.
Which review concern is valid for unit testing and pytest?
A A broad except inside the test can hide the wrong exception. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
pytest.raises verifies that a specific invalid operation raises the intended exception.
Show answer
Where should a dependency usually be patched?
A Where the tested code looks it up B Only in its original module C The answer depends only on the displayed label
The lookup namespace determines which object the code actually uses.
Hint: Review fixtures and the relevant contract.
Which review concern is valid for mocking and test fixtures?
A A mock that always succeeds can hide error handling defects. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
A fake or mock should reproduce the part of a dependency contract the test relies on.
Show answer
Which style commonly names Python functions?
A snake_case B CapWords C The answer depends only on the displayed label
PEP 8 conventionally uses lowercase words separated by underscores for functions.
Hint: Review readable naming and the relevant contract.
Which review concern is valid for code style and pep 8?
A PEP 8 allows local consistency and compatibility considerations. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
A project can adopt formatter and lint rules that make its chosen conventions consistent.
Show answer
Do annotations alone enforce parameter types at runtime?
A No B Yes C The answer depends only on the displayed label
Annotations normally support documentation and static analysis rather than automatic runtime validation.
Hint: Review static intent and the relevant contract.
Which review concern is valid for type checking and type hinting?
A Static compatibility still depends on the declared method contract. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
Protocols can describe supported operations without requiring one concrete inheritance chain.
Show answer
What does a loose version constraint guarantee?
A A permitted version range B One exact resolved environment C The answer depends only on the displayed label
A constraint limits acceptable versions without fixing the entire resolution.
Hint: Review project metadata and the relevant contract.
Which review concern is valid for virtual environments and dependencies?
A The grouping syntax depends on the selected packaging workflow. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
Test and analysis tools can be separated from application runtime requirements.
Show answer
Should a project normally commit its .venv directory?
A No B Yes C The answer depends only on the displayed label
The environment should be recreated from documented dependency inputs.
Hint: Review repository boundaries and the relevant contract.
Which review concern is valid for git and python projects?
A A successful merge does not prove the program is correct. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
Branches and review help integrate work, while tests check the resulting combined behavior.
Show answer
Why did editing second also change first?
A Both names reference the same list B Every list is globally shared C The answer depends only on the displayed label
Assignment did not create an independent list.
Hint: Review reasoned explanations and the relevant contract.
Which review concern is valid for interview questions and answers?
A An optimization needs a reason grounded in the workload. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
Discuss complexity, error handling, tests and readability in relation to the given task.
Show answer
Does with sqlite3.connect(...) by itself close the connection?
A No B Yes C The answer depends only on the displayed label
Its context manager handles transactions; explicit closing handles the connection lifetime.
Hint: Review connection and cursor and the relevant contract.
Which review concern is valid for database connections and queries?
A Retrying nonidempotent writes blindly can duplicate work. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
Connection failures, query errors and invalid application data require different handling.
Show answer
Which clause limits rows affected by a simple UPDATE?
A WHERE B ORDER BY alone C The answer depends only on the displayed label
WHERE identifies the matching rows to change.
Hint: Review create and read and the relevant contract.
Which review concern is valid for sql crud with python?
A Partial commits can leave inconsistent application state. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
Related changes should succeed or fail together inside a suitable transaction.
Show answer
How should a member identifier enter a SQL query?
A As a bound parameter B By concatenating user text C The answer depends only on the displayed label
The driver handles a separately bound value without treating it as SQL syntax.
Hint: Review driver setup and the relevant contract.
Which review concern is valid for python mysql tutorial?
A Autocommit settings change transaction behavior. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
commit saves pending changes and rollback abandons them when the transaction fails.
Show answer
Which update operator changes selected MongoDB fields?
A $set B Replacing every field manually C The answer depends only on the displayed label
The $set operator updates specified fields while retaining other document data.
Hint: Review documents and the relevant contract.
Which review concern is valid for python mongodb tutorial?
A An identifier string is not automatically an ObjectId instance. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
Inserted documents receive identifiers and indexes can support frequent queries.
Show answer
Why set a request timeout?
A To bound a wait for network activity B To guarantee the server returns valid JSON C The answer depends only on the displayed label
A timeout limits waiting behavior without validating response content.
Hint: Review http methods and the relevant contract.
Which review concern is valid for http requests and rest apis?
A Assuming the first page contains every record loses data. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
Many APIs return only one page and provide a next token or link.
Show answer
Can a valid token still lack permission for an operation?
A Yes B No C The answer depends only on the displayed label
Authentication and authorization answer different questions.
Hint: Review authentication and the relevant contract.
Which review concern is valid for api authentication and errors?
A Retries can repeat a completed operation when a response was lost. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
Retry only selected temporary failures with limits and respect service rate guidance.
Show answer
What type is written to the response body stream?
A bytes B A Python dictionary C The answer depends only on the displayed label
The HTTP body is transmitted as bytes after serialization and encoding.
Hint: Review request handlers and the relevant contract.
Which review concern is valid for a simple python web server?
A A tutorial server is not a complete production hosting design. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
http.server is useful for controlled learning and local development.
Show answer
Should the Flask development debugger be exposed in production?
A No B Yes C The answer depends only on the displayed label
Flask documents the development server and debugger for development use.
Hint: Review application object and the relevant contract.
Which review concern is valid for introduction to flask?
A Production requires a suitable server and deployment configuration. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
The development server and debugger are intended for development rather than production.
Show answer
What does axis=1 sum in a two dimensional array?
A Values within each row B Every column into one row C The answer depends only on the displayed label
Axis one is the column dimension, so reducing it produces row totals.
Hint: Review array shape and the relevant contract.
Which review concern is valid for numpy tutorial?
A Fancy indexing and reshaping have different sharing behavior. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
Basic slicing often returns a view sharing storage, while copy makes independent array data.
Show answer
Which selector uses integer positions?
A iloc B loc C The answer depends only on the displayed label
iloc uses position while loc uses labels.
Hint: Review table model and the relevant contract.
Which review concern is valid for pandas tutorial?
A A missing amount is not necessarily zero. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
Missing data needs a deliberate interpretation before dropping or filling it.
Show answer
Which object represents an individual plotting area?
A Axes B The filename C The answer depends only on the displayed label
Axes contains plotted data, labels and scales.
Hint: Review figure and axes and the relevant contract.
Which review concern is valid for matplotlib tutorial?
A A plotting script can work without opening a desktop window. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
savefig exports a graphic that can be shared independently of an interactive window.
Show answer
Why retain rejected row information?
A To explain cleaning decisions B To increase the reported total C The answer depends only on the displayed label
An audit trail makes transformations inspectable and source defects repairable.
Hint: Review data contracts and the relevant contract.
Which review concern is valid for data cleaning and analysis?
A A visually convincing chart cannot repair an incorrect cleaning policy. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
Reconcile row counts and totals before presenting a summary.
Show answer
Which statistic is generally less affected by one extreme duration?
A Median B Mean C The answer depends only on the displayed label
The median depends on ordered position rather than adding every magnitude.
Hint: Review location summaries and the relevant contract.
Which review concern is valid for statistics with python?
A Correlation alone does not establish a causal mechanism. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
A numerical summary needs units, context and an explanation of its limitations.
Show answer
Which chart shows the distribution of one numeric variable?
A Histogram B Category bar chart C The answer depends only on the displayed label
Histogram bins represent numeric intervals.
Hint: Review line charts and the relevant contract.
Which review concern is valid for line, bar, scatter and histogram charts?
A Bins strongly affect the apparent shape. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
A histogram groups one numeric variable into intervals to show its distribution.
Show answer
What is the worst case growth of a full list scan?
A O(n) B O(1) C The answer depends only on the displayed label
A scan may inspect each of n items.
Hint: Review input size and the relevant contract.
Which review concern is valid for time and space complexity?
A Recursive call stacks also consume working memory. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
Count additional working storage separately from input and required output when useful.
Show answer
What prerequisite does binary search require?
A A suitably sorted search space B A random input order C The answer depends only on the displayed label
Ordering supports discarding part of the candidate interval.
Hint: Review linear search and the relevant contract.
Which review concern is valid for linear and binary search?
A An insertion position alone does not prove the value exists. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
bisect_left returns where a value could be inserted while preserving order.
Show answer
What does a stable sort preserve for equal keys?
A Their original relative order B Reverse order C The answer depends only on the displayed label
Equal key elements retain their relative order.
Hint: Review ordering keys and the relevant contract.
Which review concern is valid for sorting algorithms?
A Reimplementing a production sort is rarely needed for ordinary application code. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
sorted returns a new list while list.sort mutates the list, and Python sorting is stable.
Show answer
Which order describes a queue?
A First in, first out B Last in, first out C The answer depends only on the displayed label
The earliest queued item is served first.
Hint: Review stack order and the relevant contract.
Which review concern is valid for stacks and queues?
A A collection choice alone does not define complete concurrent behavior. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
queue.Queue provides coordination features for threaded producers and consumers.
Show answer
How does a singly linked list reach the next value?
A By following a next reference B By constant time arbitrary indexing C The answer depends only on the displayed label
Each node points to the next node in the chain.
Hint: Review nodes and the relevant contract.
Which review concern is valid for linked lists?
A Linked lists do not provide constant time arbitrary indexed access. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
Deletion changes references and must handle the head and empty cases.
Show answer
Can different dictionary keys have the same hash?
A Yes B No C The answer depends only on the displayed label
Hash tables resolve collisions and use key equality to distinguish entries.
Hint: Review hashing and the relevant contract.
Which review concern is valid for hash tables?
A Worst case performance and resize work need separate consideration. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
Dictionary operations are usually average constant time under suitable assumptions.
Show answer
What determines search cost in a simple BST?
A The tree height B Only the root value C The answer depends only on the displayed label
A search follows one path whose length is bounded by height.
Hint: Review tree structure and the relevant contract.
Which review concern is valid for trees and binary search trees?
A A BST is not automatically balanced. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
Search follows tree height, which can be logarithmic in a balanced tree or linear in a skewed one.
Show answer
Which traversal finds shortest hop counts in an unweighted graph?
A Breadth first search B Any depth first traversal C The answer depends only on the displayed label
BFS explores vertices in increasing edge distance from its start.
Hint: Review vertices and edges and the relevant contract.
Which review concern is valid for graphs and graph traversal?
A Traversal order can change when neighbor order changes. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
DFS explores a branch before alternatives and can use a stack or recursion.
Show answer
What must mutable backtracking restore?
A The state changed for the current choice B Every global variable C The answer depends only on the displayed label
Each branch should start from the correct state for its own choice.
Hint: Review problem decomposition and the relevant contract.
Which review concern is valid for recursive problem solving?
A Recursion does not by itself make an algorithm efficient. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
A branching recursive search can grow exponentially even when each call is simple.
Show answer
Why compare a learned model with a baseline?
A To check whether complexity improves useful performance B To avoid all evaluation C The answer depends only on the displayed label
A baseline makes the model improvement measurable.
Hint: Review features and targets and the relevant contract.
Which review concern is valid for introduction to machine learning?
A Training performance alone does not measure future usefulness. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
A model should be assessed on appropriate observations not used for its fitting choices.
Show answer
What does multimode help represent?
A Ties among most frequent values B Only the arithmetic average C The answer depends only on the displayed label
multimode returns all values tied for highest frequency.
Hint: Review mean and median and the relevant contract.
Which review concern is valid for mean, median, mode and deviation?
A Summary values do not describe every aspect of a distribution. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
Summary statistics can describe inputs and support simple baselines.
Show answer
Why can percentile calculations differ between tools?
A They can use different interpolation conventions B Percentiles are unrelated to ordering C The answer depends only on the displayed label
Different accepted calculation methods place and interpolate rank positions differently.
Hint: Review distribution shape and the relevant contract.
Which review concern is valid for data distribution and percentiles?
A A model fitted to an older distribution can lose relevance. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
A distribution can shift as users, processes or measurement rules change.
Show answer
What kind of target does ordinary linear regression predict?
A A numeric value B Only a category label C The answer depends only on the displayed label
Regression models numerical outcomes.
Hint: Review linear model and the relevant contract.
Which review concern is valid for linear and multiple regression?
A A fitted relationship alone does not prove causation. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
Assess held out numeric errors with meaningful units and compare a baseline.
Show answer
What does predict_proba provide?
A Estimated class probabilities B Guaranteed outcomes C The answer depends only on the displayed label
Probability estimates describe model confidence under its fitted assumptions.
Hint: Review classification and the relevant contract.
Which review concern is valid for logistic regression?
A Accuracy can hide poor performance on a rare class. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
Feature scaling and regularization affect fitting, and held out metrics assess outcomes.
Show answer
Why scale mixed KNN features?
A Because distance depends on their magnitudes B To guarantee perfect accuracy C The answer depends only on the displayed label
A large scale feature can dominate distances without suitable preprocessing.
Hint: Review tree splits and the relevant contract.
Which review concern is valid for decision trees and k-nearest neighbors?
A A readable tree can still reflect biased or unsuitable data. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
Trees expose decision conditions while KNN retains reference examples for prediction.
Show answer
Which observations should fit a preprocessing transformation?
A Training observations B The full dataset including test observations C The answer depends only on the displayed label
Held out information should not influence fitting.
Hint: Review data roles and the relevant contract.
Which review concern is valid for training and testing datasets?
A A fixed seed cannot repair a poorly designed split. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
Record split rules and random seeds where randomization is appropriate.
Show answer
Why include preprocessing inside the cross validation pipeline?
A To fit it separately on each training fold B To inspect the final test target C The answer depends only on the displayed label
Fold isolation prevents held out data from shaping preprocessing.
Hint: Review fold procedure and the relevant contract.
Which review concern is valid for cross-validation and evaluation?
A Preprocessing the full dataset first can leak held out information. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
A pipeline fits preprocessing inside each training fold before evaluating that fold.
Show answer
Do K-means cluster labels have inherent category meanings?
A No B Yes C The answer depends only on the displayed label
Their numeric identifiers distinguish fitted groups without supplying semantic names.
Hint: Review unsupervised grouping and the relevant contract.
Which review concern is valid for clustering and k-means?
A Clustering associations should not become unsupported judgments about people. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
Use stability, separation and domain interpretation to assess useful grouping.
Show answer
What should you identify before adapting an example?
A Its inputs, outputs and assumptions B Only its line count C The answer depends only on the displayed label
The example contract determines where its behavior remains useful.
Hint: Review example selection and the relevant contract.
Which review concern is valid for Python examples library?
A A reusable function should not depend on unexplained surrounding globals. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
Join small functions through clear input and return contracts.
Show answer
What should a challenge include besides an ordinary example?
A Boundary and adversarial cases B Only a time limit C The answer depends only on the displayed label
Contrasting cases expose incorrect assumptions and shortcuts.
Hint: Review challenge contracts and the relevant contract.
Which review concern is valid for Python coding challenges?
A Passing examples alone does not explain the algorithm. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
A challenge solution should explain its invariant and complexity.
Show answer
Why attempt a problem before reading its solution?
A To expose your current reasoning and gaps B To guarantee a perfect first answer C The answer depends only on the displayed label
An attempt makes comparison and feedback meaningful.
Hint: Review focused practice and the relevant contract.
Which review concern is valid for Python practice problems?
A Transfer requires understanding assumptions, not renaming variables. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
Apply the same idea to another domain after solving the first version.
Show answer
What makes an advanced exercise valuable?
A Design and tradeoff decisions with evidence B Only a larger line count C The answer depends only on the displayed label
Difficulty should reflect reasoning demands rather than unnecessary length.
Hint: Review beginner exercises and the relevant contract.
Which review concern is valid for python exercises by difficulty?
A A high score on repeated identical questions does not prove broad fluency. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
Existing exercise filters let learners choose topic, type and difficulty.
Show answer
How should a missed quiz question guide study?
A Review its explanation and apply the concept again B Memorize the option position C The answer depends only on the displayed label
Explanation plus a new application targets the actual misunderstanding.
Hint: Review topic selection and the relevant contract.
Which review concern is valid for Python quizzes by chapter?
A One quiz score is only one piece of evidence about readiness. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
Use chapter results to choose a focused review and a fresh application problem.
Show answer
What should the first project milestone provide?
A One small working behavior B Every planned feature at once C The answer depends only on the displayed label
A small deliverable supplies feedback and a stable base.
Hint: Review project scope and the relevant contract.
Which review concern is valid for beginner python projects?
A A demonstration that works only for one hardcoded input is incomplete. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
A finished project satisfies its stated cases and has usable instructions.
Show answer
Do adjacent half open booking intervals overlap?
A No B Yes C The answer depends only on the displayed label
An end equal to the next start has no shared interior time.
Hint: Review architecture decisions and the relevant contract.
Which review concern is valid for advanced python projects?
A A portfolio claim should reflect what the project actually demonstrates. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
A complete project includes setup instructions, configuration, tests and documented limits.
Show answer
When should the separate machine learning track be approached?
A After the core and relevant data science prerequisites B Before variables and collections C The answer depends only on the displayed label
It builds on programming and data preparation knowledge.
Hint: Review foundation route and the relevant contract.
Which review concern is valid for study plan and learning roadmap?
A Course completion or a quiz score does not guarantee expert status or employment. B One successful example proves every possible case C Renaming a variable repairs an incorrect assumption
Use finished projects, explained decisions and reproducible checks as progress evidence.
Show answer
No exercises match those filters.