Font size
WorksheetsPage 1
Total questions: 150
Worksheet time: 1hrs 15mins
Which reason best explains why Python is widely used for AI development?
Rich ecosystem of libraries and tools
Small developer community worldwide
Limited libraries for machine learning tasks
Complex, low-level syntax for control
What percentage in the graphic indicates Python reduces development time?
10% reduction shown
100% reduction shown
40% reduction shown
57% reduction shown
Which item highlights Python’s readable syntax benefit for AI work?
Prioritize complex pointer arithmetic
Emphasize writing long boilerplate code
Require deep memory management throughout
Focus on algorithms, not implementation details
Which statement about Python’s community support is correct?
Minimal documentation is available
Help resources are mostly private
Few forums discuss Python topics
Extensive documentation and tutorials exist
Which library is part of Python’s machine learning ecosystem?
COBOL for business processing
Excel for spreadsheets
Photoshop for image editing
NumPy for numerical computing
What does the slide suggest about Jupyter notebooks?
Used only for large-scale deployment
Replace all other IDEs completely
Designed mainly for hardware testing
Useful for rapid prototyping and sharing
According to the graphic, Python ranks what position for the ML library ecosystem?
#1 position listed
#2 position listed
#3 position listed
#4 position listed
Which phrase matches Python being the primary language of data scientists?
10M+ developers worldwide
57% primary language statistic
#1 ML ecosystem ranking
40% faster development metric
Choose the best explanation for how Python’s libraries help AI projects.
Require building algorithms entirely from scratch
Limit experiments to text processing only
Provide ready-made tools like TensorFlow and scikit-learn
Offer only visualization without computation
Why might beginners prefer Python for AI compared to lower-level languages?
It requires complex compilation steps
It features clean, readable syntax
It hides algorithms behind proprietary code
It forces manual memory allocation always
Which Python method adds a new item to the end of a list?
insert() at index position
append() at list end
concat using plus
extend() with another list
What does features.pop() do when called with no arguments?
removes first element
removes last element
removes middle element
removes all elements
Which expression correctly returns the number of items in a list named features?
size(features) function
count(features) method
len(features) function
length(features) method
Given data = [0,1,2,3,4,5,6,7,8,9], what does data[:8] produce?
elements after index eight
last eight elements
first eight elements
elements 2 through 8
For data = [0,1,2,3,4,5,6,7,8,9], what does data[8:] return?
items after index eight
items excluding index eight
items before index eight
items between five and eight
Which computation implements an 80/20 train split size for a list named data?
round(len(data)*0.5) count
int(len(data)*0.8) count
int(len(data)*0.2) count
len(data)-2 elements
Select the correct Python slice that creates the training subset using an 80/20 split.
data[:int(len(data)*0.8)]
data[int(len(data)*0.2):]
data[int(len(data)*0.8):]
data[:int(len(data)*0.2)]
Why is list slicing important in AI workflows?
trains models automatically
formats images and audio
creates splits and batches
compresses datasets losslessly
Which list best represents labels for a three-class classifier?
["cat","dog","bird"] strings
[1.0,2.0,3.0] numeric
[(1,2),(3,4),(5,6)] tuples
[{x:1},{y:2},{z:3}] dicts
You need to batch data samples for training from a long list. Which operation helps you take contiguous subsets efficiently?
copy by deep clone
shuffle inplace randomly
slice using start stop
map with lambda
Which statement chooses between multiple conditions in Python?
if/elif/else chain
try/except block
def/function header
import/module line
In the shown code, what prints when accuracy equals 0.85?
Excellent model!
Needs improvement
Good model
Training complete
What is the main purpose of a for loop in the example?
Handle runtime errors
Declare model variables
Check convergence repeatedly
Iterate over epochs
Which function is used to get both index and item while looping?
enumerate(data)
range(data)
len(data)
map(data)
When does the while loop continue executing in the example?
While loss > 0.01
Until epoch == 10
While accuracy >= 0.9
Until data list ends
Which keyword immediately exits the current loop as shown?
exit
return
stop
break
What printed message includes the current loop counter in the for loop?
"Training started"
"Needs improvement"
"Excellent model!"
f"Epoch {epoch} complete"
Which loop type is best for a known number of repetitions like epochs?
for loop with range
while loop with condition
do-while loop construct
recursion over function
Which control flow fits repeated updates until a threshold is met?
switch-case block
function definition
for loop over range
while loop
If accuracy is 0.92, which branch runs in the conditional?
else default block
None of the branches
elif accuracy >= 0.8
if accuracy >= 0.9
Which syntax correctly represents a basic Python list comprehension that produces values from an expression over an iterable?
(expression for item in iterable)
expression for item in iterable
{expression for item in iterable}
[expression for item in iterable]
What is the correct syntax to include a filtering condition in a Python list comprehension?
[expression for item in iterable if condition]
[expression if condition for item in iterable]
[if condition expression for item in iterable]
[expression for if condition in iterable]
Given range(10), which list comprehension builds squares of numbers 0 through 9?
[x2forxinrange(10)]
[x*x for x in range(9)]
[x**2 for x in range(10)]
[square(x) for x in range(10)]
A traditional loop creates squares by appending x**2 to a list for x in range(10). Which outcome matches that approach?
[0, 1, 4, 9, 16, ...]
[1, 4, 9, 16, 25, ...]
[0, 2, 4, 6, 8, ...]
[1, 3, 5, 7, 9, ...]
Which benefit is highlighted when using a list comprehension instead of a multi-line loop for building a list?
Same result with less code
Guaranteed lower memory use
Faster CPU clock speed
Automatic parallel execution
Choose the list comprehension that scales features using min-max normalization with min_val and range_val.
[(x + min_val) / range_val for x in features]
[(x - min_val) / range_val for x in features]
[(min_val - x) * range_val for x in features]
[x / (min_val + range_val) for x in features]
Select the comprehension that filters samples to keep only those with a non-None 'label' field.
[s for s in samples if s['label'] is not None]
[s for s in samples if label exists]
[s for s in samples where s['label'] != None]
[s in samples if s['label'] is not None]
Which part of the comprehension [x**2 for x in range(10)] is the iterable being traversed?
range(10)
x**2
x
for
You need the squares of even numbers under 10. Which comprehension correctly does this in one line?
[x**2 for x in range(10) if x % 2 == 0]
[x**2 if x % 2 == 0 for x in range(10)]
[x**2 for x if x % 2 == 0 in range(10)]
[x**2 for x in range(10) when even]
A teammate wrote squares = []; for x in range(10): squares.append(x**2). What is an equivalent, more concise one-line version?
[x**2 for x in range(10)]
list(x**2 for x in range(10))
{x**2 for x in range(10)}
map(lambda x: x**2, range(10))
Which Python method converts all letters in a string to lowercase?
text.split()
text.upper()
text.lower()
text.strip()
After applying strip() to the string ' Hello World ', what is the result?
'Hello World'
['Hello','World']
'hello world'
'HELLO WORLD'
Which method would you use to turn a sentence into a list of words separated by spaces?
lower()
upper()
split()
replace()
In text.replace("o","0"), what change is made to the text?
Remove all zeros
Change zeros to letters
Replace o with zero
Insert extra spaces
What is the typical first step in an NLP preprocessing pipeline for text?
Remove punctuation
Tokenize into characters
Count word frequencies
Convert to lowercase
Which sequence best matches the shown preprocess function steps?
Uppercase, tokenize, pad
Strip, uppercase, join
Lowercase, strip, split
Split, lowercase, strip
Why are string operations important in NLP before training models?
They clean text data
They increase dataset size
They store GPU settings
They replace models entirely
Given model = "ResNet" and acc = 0.956, what does print(f"{model}: {acc:.2%}") output?
ResNet: 0.96
ResNet: 95.60%
ResNet: 95%
ResNet: 95.6
What will print(f"Epoch {epoch:03d}/100") display when epoch is 5?
Epoch 5/100
Epoch 005/100
Epoch 05/100
Epoch 0005/100
Which option correctly describes f-strings in Python 3.6+?
A tool to sort lists
A method to split words
A library for neural nets
A way to format strings
What is the main drawback of repeating the same code for multiple datasets?
Lower memory usage overall
Higher bug risk from duplication
Faster execution for each dataset
Improved readability for beginners
Which statement best describes modular code in this context?
Code with more comments than logic
Code that relies on global variables
Code written in one long script
Code split into reusable functions
In the modular version, what do in_path and out_path represent in process_dataset?
Configuration flags for testing
Column names to transform
File paths for input and output
Loop counters
Which step is performed to handle missing values in the dataset?
data.dropna() removes missing rows
data.rename() changes column names
data.isna() prints NA counts
data.fillna() replaces with zeros
What transformation is applied to the 'price' column in the example?
Adding 1.1
Multiplying by 1.1
Rounding to nearest 1.1
Dividing by 1.1
Why is the modular function easier to test than repeated code?
It eliminates the need for parameters
It uses fewer variables overall
It consolidates logic into a single unit
It avoids reading any files at all
What does save_csv(data, out_path) accomplish in the workflow?
Deletes temporary variables
Displays data statistics
Writes cleaned data to a file
Loads data from disk
Which benefit is highlighted under 'Solution' when using a single function?
Guaranteed faster runtime
No need for code comments
Single function to update
Automatic GPU acceleration
If a new cleaning step is required, how would modular code simplify the change?
Change the step in every script
Add the step once inside the function
Create separate copies for each dataset
Disable testing to reduce effort
How many calls are needed after creating process_dataset to handle two datasets?
One call with both paths
Two calls, one per dataset
Three calls including a helper
Multiple calls per transformation
In the code snippet, what does the accuracy function return when labels is empty?
It returns the number of correct pairs
It returns None implicitly
It raises a ValueError exception
It returns zero as a float value
Which Python feature is used in the functions to document expectations for parameters and return types?
Type hints with annotations
Docstrings with examples
Comments with TODO notes
Runtime asserts for checks
What is computed inside accuracy using the expression sum(p == y for p, y in zip(preds, labels))?
Length of predictions list
Count of correct predictions
Mean of prediction errors
Total number of labels
Which module name is suggested for placing these metric utilities?
main.py for scripts
models.py for classes
utils.py for helpers
metrics.py for shared code
What does classification_report return in the provided example?
A dictionary with accuracy only
A string summary of metrics
A tuple of accuracy and loss
A list of per-class recalls
What is the main benefit stated for using shared metric utilities across projects?
They automatically tune hyperparameters
They allow training on larger datasets
They make code run significantly faster
They reduce bugs when comparing models
Why should functions be kept small as noted in the engineering notes?
To avoid importing libraries
To focus on a single concept
To minimize memory usage
To follow object inheritance
Which import statement is shown for using the utilities across projects?
from metrics import accuracy, classification_report
import metrics as m then m.accuracy
import accuracy from metrics
from utils import accuracy as acc
What Python typing types are imported at the top of the example?
Sequence and Dict generics
Optional and Union types
Set and FrozenSet classes
List and Tuple types
What is the overall theme described by the slide title?
Turning scripts into reusable utilities
Designing deep learning architectures
Building web apps with Flask
Optimizing GPU performance in Python
Which Python keyword starts a function definition?
define
func
def
call
What is the main purpose of a docstring inside a function?
Execute the code faster
Import external libraries automatically
Document what the function does
Store global variables forever
In the example, what does calculate_accuracy return?
The total number of predictions
The percentage of correct over total
A list of all correct indices
A boolean showing if all were correct
Which line ensures a function provides a result back to the caller?
print statement in the body
return statement in the body
docstring at the top
import statement at start
Choose the best description of parameters in a function.
Values the function prints
Settings for the Python interpreter
Names listed in the definition
Numbers stored in files
Given correct = 85 and total = 100, what value does calculate_accuracy(correct, total) compute?
85.0
85
0.85
100
Which concept helps reduce code duplication, as highlighted on the slide?
Writing comments everywhere
Encapsulating logic in functions
Copy-pasting similar blocks
Using long scripts repeatedly
What is the role of arguments when calling a function?
They return results automatically
They are values passed to parameters
They define scope rules
They create new keywords
Why is scope and variable lifetime important in functions?
It decides which libraries can be imported
It controls where variables exist and for how long
It sets the size of numbers in memory
It determines how fast code runs
Which code snippet correctly defines a simple function that returns a sum?
def add(a, b): return a + b
add(a, b): def return a + b
function add(a, b) = a + b
def add(a, b) print a + b
Which call uses positional arguments to pass data into a function named train?
train(model="ResNet", lr=0.001, epochs=100)
train(epochs=100, lr=0.001, model="ResNet")
train("ResNet", 100, 0.001)
train(model="ResNet")
What is a keyword argument in a function call?
A return value from the function
A parameter passed with its name specified
A variable defined inside the function
A value matched by position order
Which definition illustrates default parameter values in a function?
def train(model, epochs, lr): pass
def train(model, epochs=100, lr=0.001): pass
def train(): return model
def train(model="ResNet"): pass
In the best practice note, how should parameters be ordered in a function definition?
Required first, optional with defaults last
Largest data types first
Optional first, required last
Alphabetical order always
Given def train(model, epochs=100, lr=0.001): pass, which call uses all defaults except model?
train(model="ResNet", epochs=200)
train("ResNet", 100, 0.001)
train("ResNet")
train(epochs=200)
Which function call overrides just the epochs while keeping other defaults?
train("ResNet", epochs=200)
train(lr=0.001)
train("ResNet", 200, 0.001)
train(model="ResNet")
Why can keyword arguments make function calls clearer?
They allow longer function names
They specify parameter names explicitly
They remove the need for defaults
They enforce strict positional order
Which statement about positional arguments is correct?
They can only be optional
Their order maps to parameter positions
They must match parameter names
They require default values
If epochs has a default of 100, what happens when epochs is not provided in a call?
The function asks the user for input
The function uses epochs equal to 100
The function uses epochs equal to 0
The call fails immediately
A team wants cleaner function calls with optional parameters. What change should they make?
Place optional parameters before required
Use keyword arguments for optional parameters
Remove all default values from definitions
Always call with full positional lists
What does the *args parameter allow a Python function to do?
Return multiple values automatically
Accept any number of positional arguments
Accept any number of keyword arguments
Restrict input to a fixed number of arguments
In the example def sum_all(*numbers): return sum(numbers), what is the role of numbers?
Tuple of positional arguments
List of keyword pairs
Dictionary of settings
Generator of integers
What does the **kwargs parameter collect when used in a function definition?
Set of unique values
Tuple of positional arguments
List of ordered parameters
Dictionary of keyword arguments
Which call correctly passes keyword arguments to create_config(**settings)?
create_config(('lr', 0.01))
create_config(['lr', 'epochs'])
create_config(0.01, 50)
create_config(lr=0.01, epochs=50)
Choose the best reason to use *args in sum_all(1, 2, 3, 4, 5).
Handle variable-length inputs
Ensure static type checking
Force named parameters only
Improve code compilation speed
In build_model(architecture, **hyperparams), what does model.configure(**hyperparams) achieve?
Bind arguments at import time
Ignore unknown parameters safely
Convert settings to positional form
Pass all settings to the model
Which statement about *args and **kwargs is accurate?
*args collects positional, **kwargs collects keyword
Both require fixed-length inputs
*args collects keyword, **kwargs collects positional
Both collect only positional arguments
What is returned by sum_all(1, 2, 3, 4, 5) in the example?
A list of numbers
A tuple of five values
An error due to extra inputs
15 as the sum
Why might **kwargs be helpful when configuring machine learning models?
Allows flexible hyperparameter passing
Prevents runtime memory allocation
Ensures compile-time optimization
Limits models to default settings only
Which function signature enables both fixed and flexible inputs in the example?
build_model(architecture, **hyperparams)
configure_model(*args, **model)
sum_all(numbers, **kwargs)
create_config(*settings, lr)
In Python, what does the get_accuracy function return when given predictions and labels of equal length?
A list of all correct indices
The fraction of correct predictions
The number of correct predictions only
The sum of all label values
Which expression computes the count of correct matches in the shown get_accuracy code?
len(pred) - len(labels)
sum(p == l for p, l in zip(pred, labels))
pred.count(labels)
sum(zip(pred, labels))
What is the main purpose of zip(pred, labels) in the accuracy function?
To sort both lists together
To pair predictions with labels
To remove duplicates from lists
To concatenate two lists
In the train_test_split example, what does int(len(data)*0.8) represent?
The average of the data
The number of labels
The index where to split
The size of the test set
When a function returns two values in Python, how are they received in the example?
By tuple unpacking into two variables
As a single list result
Through a global variable update
By printing both values to console
Which line shows multiple return values from train_test_split?
return data[:split], data[split:]
return data[split:]
return split
return data
In the evaluate(model) example, what data structure is returned?
A tuple of three floats
A list of metric values
A string describing results
A dictionary with named metrics
Why might returning a dictionary of results be helpful, according to the pro tip?
It is faster than tuples
It avoids function calls
It is self-documenting with names
It uses less memory
If train, test = train_test_split(data) fails with a ValueError: not enough values to unpack, what likely changed in the function?
It returns no value now
It prints instead of returns
It uses zip instead of split
It returns only one value
Given evaluate(model) returns {'accuracy': 0.95, 'precision': 0.93, 'recall': 0.94}, which key should you access to get the recall value?
metrics['score']
test['recall']
result['recall']
model['recall']
In Python, where does a local variable defined inside a function exist?
Only inside that function body
Inside built-in namespace
Inside enclosing class scope
Across all modules globally
What happens when print(x) is executed outside the function where x was defined locally?
It raises a NameError
It accesses built-in x
It prints the local value
It returns None silently
Which statement correctly reads a global variable inside a function without modification?
Use it directly by name
Import builtins first
Declare it with global
Pass it as keyword
To modify a global variable inside a function, what must you do first?
Declare it with global
Use nonlocal keyword
Cast it to float
Define it as parameter
Which order describes Python’s LEGB lookup rule?
Local, Enclosing, Global, Built-in
Enclosing, Local, Built-in, Global
Global, Local, Built-in, Enclosing
Built-in, Global, Local, Enclosing
Given learning_rate = 0.001 at module level, what does train() printing learning_rate show if not redefined?
It raises UnboundLocalError
It prints 0.0001
It prints None
It prints 0.001
In update_lr(), why is the line global learning_rate used before assignment?
To prevent return value
To access built-in names
To create a local constant
To modify the module variable
Which practice improves code clarity and testability regarding state changes?
Avoid return statements
Rely on many globals
Pass values as parameters
Use hidden built-ins
Which keyword lets you modify a variable in an enclosing function scope?
static
extern
global
nonlocal
A function assigns learning_rate = 0.0001 without global. There is a module-level learning_rate = 0.001. What is printed inside that function?
An AttributeError
0.001 global value
A built-in default
0.0001 local value
What is the main purpose of a docstring in a function?
Explain algorithmic complexity and performance
Document usage, parameters, returns, and errors
Store runtime logs for debugging sessions
Define default values for all function arguments
In the code sample, which normalization methods are mentioned as valid options?
"average" and "median"
"standard" and "robust"
"minmean" and "maxscore"
"minmax" and "zscore"
Which section of the docstring lists the types and meanings of the function inputs?
Notes section
Args section
Returns section
Raises section
What does the Returns section describe for the normalize function?
A list of normalized values
A dictionary of parameter defaults
A single boolean success flag
A tuple of errors and warnings
According to the slide, which is a benefit of documenting code with docstrings?
Faster compilation of source files
Reduced memory usage at runtime
IDE shows docs on hover
Automatic variable type inference
Which statement best describes the Raises section in a docstring?
It lists environment variables to configure
It lists the external libraries required
It lists exceptions the function may throw
It lists performance benchmarks for the code
If an unrecognized method is passed to normalize, what should happen based on the docstring?
Log a warning and continue
Fallback silently to minmax
Raise ValueError for invalid method
Return None without changes
Why is documentation considered essential for open-source projects?
It optimizes code execution in production
It hides implementation details from contributors
It enables auto-generating API docs and collaboration
It prevents forks and derivative projects
Which docstring style is shown in the code block?
PEP 257 minimal docstring
reStructuredText style docstring
Google style docstring
NumPy style docstring
Which benefit is directly tied to developer experience in IDEs?
IDE shows documentation on hover
Easier maintenance after deployment
Essential for licensing compliance
Self-documenting code when compiled
Which phrase best defines a higher-order function in programming?
A function calling system libraries
A function manipulating raw memory
A function that returns other functions
A function storing global variables
What does apply_to_all(func, data) return when func is lambda x: x**2 and data is [1, 2, 3]?
It returns [3, 5, 7]
It returns [2, 4, 6]
It returns [1, 4, 9]
It returns [1, 2, 3]
In the code, what role does the parameter func play inside apply_to_all?
It is a data type converter
It is a function applied to each item
It is a loop counter variable
It is a number accumulator
Which built-in construct applies a function to every element of a list and produces an iterable?
zip
map
reduce
filter
Which statement best describes filter with lambda x: x > 0 on nums?
It removes duplicate numbers
It sorts numbers by absolute value
It converts nums to lowercase
It keeps only positive numbers
When sorting dictionaries with sorted(data, key=lambda x: x["val"]), what does key specify?
The field used to compare items
The comparison operator used
The type of sorting algorithm
The limit on items returned
Given numbers = [1, 2, 3, 4], which expression produces [2, 4, 6, 8]?
list(filter(lambda x: x%2==0, numbers))
sorted(numbers, key=lambda x: -x)
list(map(lambda x: x+1, numbers))
list(map(lambda x: x*2, numbers))
Which example shows passing a function as an argument?
apply_to_all(lambda x: x**2, numbers)
apply_to_all(data=True, func=False)
apply_to_all(numbers, lambda x: x**2)
apply_to_all(numbers, [1,2,3,4])
Why might AI preprocessing pipelines use higher-order functions?
To store models in global memory
To replace training data entirely
To compose stepwise transformations
To avoid using any loops
Which choice correctly converts all strings in ["a", "b"] to uppercase using a built-in?
list(filter(str.upper, ["a","b"]))
list(map(str.upper, ["a","b"]))
sorted(["a","b"], key=str.upper)
list(map(lambda x: x.lower, ["a","b"]))
What is the primary purpose of a decorator in Python?
Rendering graphics on the screen
Wrapping and extending a function’s behavior
Compiling code to machine instructions
Replacing variables with constant values
In the timing decorator shown, which function actually calls the original function?
timer outside wrapper
wrapper inside timer
train_model directly
time.time utility
Which statement records the start time in the timing decorator code?
return wrapper
print(f"{func.__name__} took ...")
result = func(*args, **kwargs)
start = time.time()
Why does the wrapper use *args and **kwargs when calling func?
To run code only once
To convert arguments to strings
To limit calls to no parameters
To accept any parameters flexibly
In the image’s use cases list, which is NOT a stated common use of decorators?
Authentication checks
Caching results (memoization)
Timing or profiling functions
Rendering 3D graphics
What does the print statement in the timing decorator display?
Number of decorator parameters
Operating system version info
CPU temperature and voltage
Function name and elapsed seconds
Which annotation is used to apply the timing decorator to train_model?
@timer above the function
#timer in a comment
timer() after the function
import timer from time
According to the Decorator Flow diagram, what is the sequence of steps?
Wrapper then timing/logging then function call
Function call then wrapper then timing/logging
Timing/logging then wrapper then function call
Wrapper then function call then timing/logging
Which import is necessary for the timing decorator to work as shown?
import time at the top
import math inside wrapper
from os import path
import random for delays
Which line ensures the original function’s return value is preserved?
print elapsed time to console
return wrapper at function end
start = time.time() before call
return result after printing
