Python for Data Analysis
- 142Unfamiliar
- 0Learning
- 0Familiar
- 0Mastered
What does computer programming mean?
What does computer programming mean?
142 questions
- 1
What does computer programming mean?
- A
The process of giving a computer instructions to perform actions
- B
The process of converting every program into a spreadsheet
- C
The process of storing computer hardware in an organized format
- D
The process of connecting computers to a shared network
Correct answer
AThe process of giving a computer instructions to perform actions
Explanation
Programming is the process of giving a computer instructions to perform actions. A programming language provides a way to write those instructions.
- A
- 2
Why are transistors relevant to the way computers process instructions?
- A
They translate spoken language directly into computer instructions
- B
They store high-level programming syntax as text
- C
They organize program files into reusable libraries
- D
They control electrical flow through on and off states
Correct answer
DThey control electrical flow through on and off states
Explanation
Transistors act like switches that control electrical flow. Their on and off states correspond to binary values, which underpin how computers represent instructions.
- A
- 3
What does binary represent in the explanation of computer operation?
- A
It represents the sequence of steps in a for loop
- B
It represents on and off states using ones and zeros
- C
It describes the rules for naming variables in Python
- D
It stores data using rows and columns
Correct answer
BIt represents on and off states using ones and zeros
Explanation
Binary represents the on and off states of transistors using ones and zeros. Computers ultimately operate on these binary representations.
- A
- 4
Which description best characterizes early low-level programming languages?
- A
They are written primarily to organize tabular data
- B
They use familiar syntax and work across many types of tasks
- C
They were difficult to use and often machine-specific
- D
They are libraries that contain reusable mathematical functions
Correct answer
CThey were difficult to use and often machine-specific
Explanation
Low-level languages were difficult to use, required extensive training, and often worked only on the machine for which they were designed.
- A
- 5
What is a defining feature of a high-level programming language?
- A
They communicate with hardware only through electrical signals
- B
They are limited to controlling a computer's transistors
- C
They use more human-friendly syntax and structures
- D
They can only be used to write data visualization programs
Correct answer
CThey use more human-friendly syntax and structures
Explanation
High-level languages use syntax designed to be more familiar to humans than binary or low-level instructions.
- A
- 6
Which statement best describes Python?
- A
It requires users to write all common functions from scratch
- B
It is a low-level language designed for one specific machine
- C
It is a versatile, approachable, powerful high-level language
- D
It is limited to writing instructions for web browsers
Correct answer
CIt is a versatile, approachable, powerful high-level language
Explanation
Python is presented as a versatile, approachable, powerful high-level language. Its open-source ecosystem also includes many libraries and tools.
- A
- 7
What is a Python library?
- A
A single value stored in a variable's memory location
- B
A sequence of instructions that can only run once
- C
A reusable collection of code for common or specialized tasks
- D
A rule that determines the order of arithmetic operations
Correct answer
CA reusable collection of code for common or specialized tasks
Explanation
A library is a reusable collection of code. Using an existing library can save time compared with writing common functionality yourself.
- A
- 8
Which set of tasks is described as part of Python's role in data work?
- A
It replaces the need to inspect or clean data
- B
It is used only to enter data into spreadsheets
- C
It is used only to create machine learning models
- D
It supports tasks from data exploration through model building
Correct answer
DIt supports tasks from data exploration through model building
Explanation
Python can support many stages of data work, including exploration, cleaning, visualization, and machine learning model development.
- A
- 9
What is a Jupyter Notebook?
- A
A Python data type that stores rows and columns
- B
A terminal command that runs a program line by line without editing
- C
An open-source web application combining code, text, and outputs
- D
A library used exclusively to generate random numbers
Correct answer
CAn open-source web application combining code, text, and outputs
Explanation
A Jupyter Notebook is an open-source web application for documents that can combine live code, text, mathematical formulas, and visualizations.
- A
- 10
What is a practical advantage of organizing notebook work into cells?
- A
They prevent users from changing or rearranging code
- B
They convert every code statement into a spreadsheet row
- C
They force every instruction to run only once in a fixed order
- D
They divide notebook content into modular input/output fields
Correct answer
DThey divide notebook content into modular input/output fields
Explanation
Notebook cells make it easier to organize code into modules or sections, move or remove code, and keep output and explanations together.
- A
- 11
What role does Markdown play in a Jupyter Notebook?
- A
It is a method that sorts a list from least to greatest
- B
It lets users add formatted explanatory text in a coding environment
- C
It is a data structure that stores unique, unordered values
- D
It is the Python command for changing a variable's data type
Correct answer
BIt lets users add formatted explanatory text in a coding environment
Explanation
Markdown is a way to write formatted text in a coding environment, including elements such as headings, bullets, tables, and formulas.
- A
- 12
What is the central idea of object-oriented programming?
- A
It organizes data together with code that operates on it
- B
It stores all program data in one global variable
- C
It prevents functions from acting on stored data
- D
It organizes programs only as sequences of arithmetic operators
Correct answer
AIt organizes data together with code that operates on it
Explanation
Object-oriented programming organizes code around objects that can contain data and methods that manipulate that data.
- A
- 13
Which explanation best describes a Python variable?
- A
A variable is the memory location itself and cannot refer to a value
- B
A variable is a Python function that prints a value
- C
A variable is a fixed data type that cannot be reassigned
- D
A variable is a name that refers to a value stored in memory
Correct answer
DA variable is a name that refers to a value stored in memory
Explanation
A variable is a name that points to a value stored in memory; it is not the value itself.
- A
- 14
What does a data type describe?
- A
A label used only to identify the creator of a program
- B
A process that repeatedly executes a block of code
- C
A description of data based on its values or possible operations
- D
A rule for arranging lines of code in a notebook
Correct answer
CA description of data based on its values or possible operations
Explanation
A data type describes data in terms of its values, language representation, or the operations it can perform.
- A
- 15
What does dynamic typing mean in Python?
- A
A variable's data type is permanently fixed at its first assignment
- B
A variable must be declared with its type before any assignment
- C
A variable can refer only to strings and integers
- D
A variable can refer to objects of different data types
Correct answer
DA variable can refer to objects of different data types
Explanation
Python uses dynamic typing: a variable can refer to objects of different data types as it is reassigned.
- A
- 16
Why should a variable be initialized before it is used?
- A
Variables must be initialized with a Boolean value
- B
Variables can be called before their names are assigned
- C
A variable generally needs a value assigned before it is called
- D
Variables are initialized automatically as empty strings
Correct answer
CA variable generally needs a value assigned before it is called
Explanation
Most variables need an initial assignment before they can be used. That first assignment is often called initialization.
- A
- 17
Why is a descriptive variable name generally preferable to a vague name?
- A
Names should always match the name of a built-in function
- B
Names should be as short as possible, even if their meaning is unclear
- C
Names should help readers understand the value or purpose stored
- D
Names should indicate only the programming language being used
Correct answer
CNames should help readers understand the value or purpose stored
Explanation
A meaningful name such as age_list communicates the contents more clearly than a vague name such as x.
- A
- 18
Which comparison correctly distinguishes an assignment from an expression?
- A
An assignment converts strings; an expression prevents reassignment
- B
An assignment creates a loop; an expression names a variable
- C
An assignment stores a value; an expression evaluates to a result
- D
An assignment compares two values; an expression stores a function
Correct answer
CAn assignment stores a value; an expression evaluates to a result
Explanation
An assignment stores a value in a variable. An expression combines values, symbols, or variables to produce a result when evaluated.
- A
- 19
How do integers and floats differ?
- A
Integers represent decimal numbers; floats represent whole numbers
- B
Integers store text; floats store only Boolean values
- C
Integers and floats both represent sequences of characters
- D
Integers represent whole numbers; floats represent decimal numbers
Correct answer
DIntegers represent whole numbers; floats represent decimal numbers
Explanation
Integers represent whole numbers without fractions, while floats represent numbers with decimal components.
- A
- 20
What is a string?
- A
Strings are whole numbers that cannot contain a decimal point
- B
Strings are sequences of characters used to represent text
- C
Strings are Boolean expressions that evaluate to true or false
- D
Strings are ordered collections of numeric values without punctuation
Correct answer
BStrings are sequences of characters used to represent text
Explanation
Strings are sequences of characters and punctuation used to represent textual information. They are typically written within quotation marks.
- A
- 21
What does it mean that strings are immutable?
- A
Strings can be modified only if they contain numbers
- B
Strings can be changed in place, but only by using a loop
- C
Strings cannot be combined with other strings
- D
Strings cannot be changed in place; a changed value must be reassigned
Correct answer
DStrings cannot be changed in place; a changed value must be reassigned
Explanation
Strings are immutable: their characters cannot be changed in place. A modified string must be assigned as a new value to a variable.
- A
- 22
What does the Python type function do?
- A
It returns the number of elements in an object
- B
It checks whether one value is greater than another
- C
It reports the data type of an object
- D
It converts any object into a string
Correct answer
CIt reports the data type of an object
Explanation
Python's type function identifies an object's type, such as str, int, or float.
- A
- 23
Which situation is an example of implicit type conversion?
- A
A variable is renamed without changing its stored value
- B
The interpreter automatically converts a value to another type
- C
A string is split into individual characters
- D
The programmer explicitly calls int, float, or str
Correct answer
BThe interpreter automatically converts a value to another type
Explanation
Implicit conversion happens automatically without the programmer explicitly requesting a type conversion. For example, mixed integer and float arithmetic can convert the integer to a float.
- A
- 24
What is explicit type conversion?
- A
A function returns multiple values in a tuple
- B
The interpreter changes a type without any instruction from the user
- C
A variable is overwritten with a value of the same type
- D
The programmer uses a conversion function to request a new type
Correct answer
DThe programmer uses a conversion function to request a new type
Explanation
Explicit conversion, also called typecasting, uses functions such as int, float, or str to convert an object to a specified type.
- A
- 25
How do the operators = and == differ in Python?
- A
A single equals sign assigns values; two equals signs test equality
- B
Both forms compare values, but the single form compares types
- C
A single equals sign compares values; two equals signs assign values
- D
Both forms assign values, but the second is used for strings
Correct answer
AA single equals sign assigns values; two equals signs test equality
Explanation
A single equals sign assigns a value, while two equals signs compare values for equality.
- A
- 26
Why should a Python keyword not be used as a variable name?
- A
Keywords are names for values returned by functions
- B
Keywords are valid variable names if written in lowercase
- C
Keywords are user-created labels for data structures
- D
Keywords are reserved for specific language purposes
Correct answer
DKeywords are reserved for specific language purposes
Explanation
Python treats keywords such as if, for, and else as reserved words with specific language purposes, so they should not be used as variable names.
- A
- 27
Which rule applies to Python variable names?
- A
A name may use any punctuation if it begins with a letter
- B
A name must start with a number and cannot contain underscores
- C
A name may contain spaces if each word starts with a capital letter
- D
A name may use letters, numbers, and underscores, but cannot start with a number
Correct answer
DA name may use letters, numbers, and underscores, but cannot start with a number
Explanation
Variable names can contain letters, numbers, and underscores, but must start with a letter or underscore and cannot contain spaces or special characters such as ampersands.
- A
- 28
What does it mean that Python is case-sensitive?
- A
Capitalization matters only for names of functions
- B
Capitalization is ignored for all variable names
- C
Names that differ only by capitalization are treated as different
- D
Capitalization matters only when a name contains numbers
Correct answer
CNames that differ only by capitalization are treated as different
Explanation
Python is case-sensitive, so capitalization changes the spelling of an identifier and may make it refer to a different name.
- A
- 29
How do methods and attributes differ?
- A
A method performs an operation; an attribute stores an associated value
- B
A method names a class; an attribute converts one class into another
- C
A method is a value without behavior; an attribute is a reusable function
- D
A method belongs only to a notebook; an attribute belongs only to a list
Correct answer
AA method performs an operation; an attribute stores an associated value
Explanation
A method is a function associated with a class. It typically performs an operation on an object, while an attribute represents an associated value or characteristic.
- A
- 30
What is dot notation used for in Python?
- A
It assigns a new value using a single equals sign
- B
It indicates the start of a comment in a Python script
- C
It separates keys from values in a dictionary
- D
It accesses methods or attributes attached to an object
Correct answer
DIt accesses methods or attributes attached to an object
Explanation
Dot notation accesses methods and attributes associated with an object, as in object.method() or object.attribute.
- A
- 31
Which statement describes a user-defined Python function?
- A
A reusable block of code defined with the def keyword
- B
A data type that stores an ordered collection of values
- C
A value that can be stored only in a dictionary
- D
A comment that is executed each time a program runs
Correct answer
AA reusable block of code defined with the def keyword
Explanation
A function is reusable code for performing a task. A function definition begins with the def keyword and includes a name and, optionally, parameters.
- A
- 32
Which statement correctly distinguishes function parameters from arguments?
- A
Parameters and arguments are both values returned by a function
- B
Parameters are comments; arguments are the function's indented body
- C
Parameters are supplied when calling a function; arguments are written only in its definition
- D
Parameters are names in the definition; arguments are values passed to the function
Correct answer
DParameters are names in the definition; arguments are values passed to the function
Explanation
Parameters are the names in a function definition; arguments are the actual values or information supplied when the function is called.
- A
- 33
How is a function body indicated in Python?
- A
The function body is written only after the function is called
- B
The function body must use a different indentation on every line
- C
The function body is indented beneath the function definition
- D
The function body must be placed before the def line
Correct answer
CThe function body is indented beneath the function definition
Explanation
The function body contains the instructions to execute and is indented beneath the function definition. Consistent indentation makes the code structure clear.
- A
- 34
What is the key role of return in a function?
- A
It displays a message but prevents the value from being reused
- B
It changes every argument into a string
- C
It provides a result that can be stored or used elsewhere
- D
It repeats the function body until a condition changes
Correct answer
CIt provides a result that can be stored or used elsewhere
Explanation
A return statement gives a value back from a function, allowing that value to be stored or used in later calculations rather than merely printed.
- A
- 35
Why is a return value useful when writing reusable code?
- A
Returned values are printed automatically and cannot be stored
- B
Returning a value prevents a function from being called again
- C
Returned values can be assigned and combined with later operations
- D
A returned value can be used only as a function argument
Correct answer
CReturned values can be assigned and combined with later operations
Explanation
A function that returns values can be composed with other operations. For example, separate function results can be stored and then added together.
- A
- 36
What does code reusability mean?
- A
Defining code once and using it repeatedly
- B
Combining all program instructions into one long statement
- C
Using code only once and then deleting it
- D
Writing a new copy of the same code for every input
Correct answer
ADefining code once and using it repeatedly
Explanation
Reusability means defining code once and using it multiple times, rather than rewriting the same logic for each use.
- A
- 37
What is modularity in programming?
- A
Changing code structure without preserving its behavior
- B
Converting every function into a global variable
- C
Dividing code into components that work together and can be reused
- D
Writing all code in a single block to avoid dependencies
Correct answer
CDividing code into components that work together and can be reused
Explanation
Modularity means writing code in separate components that can work together and be reused in other programs.
- A
- 38
What is refactoring?
- A
Converting a reusable function into a comment
- B
Removing a program's outputs while keeping its inputs
- C
Restructuring code while preserving its functionality
- D
Changing a function's purpose while retaining its name
Correct answer
CRestructuring code while preserving its functionality
Explanation
Refactoring restructures code while preserving its original functionality. It can make code clearer without changing what it does.
- A
- 39
What is self-documenting code?
- A
Code whose names and structure make its purpose understandable
- B
Code that requires a separate explanation for every line
- C
Code that contains no variable names or expressions
- D
Code that runs only when every statement is commented out
Correct answer
ACode whose names and structure make its purpose understandable
Explanation
Self-documenting code is written so that its purpose is clear from its structure, names, and expressions. Comments can supplement that clarity.
- A
- 40
How does Python treat a line that begins with #?
- A
A comment begins with a colon and defines a function
- B
A comment begins with two equals signs and tests a condition
- C
A comment begins with # and is ignored by Python execution
- D
A comment begins with parentheses and returns a value
Correct answer
CA comment begins with # and is ignored by Python execution
Explanation
A comment begins with the # character, and Python ignores the remainder of that line when executing the program.
- A
- 41
What is a function docstring used for?
- A
A string placed after a function call to change its output
- B
A variable that stores every comment in a program
- C
A string at the start of a function that documents its behavior
- D
A reserved keyword that causes a function to repeat
Correct answer
CA string at the start of a function that documents its behavior
Explanation
A docstring is a string at the beginning of a function body that summarizes its behavior and explains its arguments and return values.
- A
- 42
What is an algorithm?
- A
A rule that says how many spaces must follow a comment
- B
A reusable library that contains programming languages
- C
A collection of data values stored in a table
- D
A set of instructions for solving a problem or task
Correct answer
DA set of instructions for solving a problem or task
Explanation
An algorithm is a set of instructions for solving a problem or accomplishing a task. A recipe is an everyday example of an algorithm.
- A
- 43
How can comments help when developing a function for a complex task?
- A
They guarantee that a function will return a correct value
- B
They execute each planned step automatically
- C
They can provide a step-by-step scaffold for planning code
- D
They convert a complex problem into a data type
Correct answer
CThey can provide a step-by-step scaffold for planning code
Explanation
Comments can outline the stages of a solution before the code is written, helping break a problem into manageable steps.
- A
- 44
Which set lists Python's six comparison operators described in the content?
- A
Greater than, greater than or equal to, less than, less than or equal to, equal, and not equal
- B
Append, insert, remove, pop, sort, and reverse
- C
And, or, not, in, is, and return
- D
Add, subtract, multiply, divide, exponentiate, and assign
Correct answer
AGreater than, greater than or equal to, less than, less than or equal to, equal, and not equal
Explanation
The six comparisons described are greater than, greater than or equal to, less than, less than or equal to, equal to, and not equal to.
- A
- 45
What do comparator operators produce?
- A
They combine separate functions into a single library
- B
They compare values and produce Boolean results
- C
They convert numerical values into strings
- D
They repeat a block until a process is complete
Correct answer
BThey compare values and produce Boolean results
Explanation
Comparators compare two values and produce Boolean results, such as True or False.
- A
- 46
When does an and expression evaluate to True?
- A
True whenever at least one expression is True
- B
True whenever the expressions have different data types
- C
True only when both expressions are True
- D
True only when both expressions are False
Correct answer
CTrue only when both expressions are True
Explanation
The and operator returns True only when both expressions are True. If either expression is False, the combined result is False.
- A
- 47
When does an or expression evaluate to True?
- A
Only when both of its expressions are False
- B
When at least one of its expressions is True
- C
When the two expressions have the same value
- D
Only when both of its expressions are True
Correct answer
BWhen at least one of its expressions is True
Explanation
An or expression is True if either expression is True, and is False only if both expressions are False.
- A
- 48
What does the logical operator not do?
- A
It compares the expression with a string
- B
It combines the expression with the next statement using and
- C
It reverses the expression's Boolean value
- D
It repeats the expression until it becomes True
Correct answer
CIt reverses the expression's Boolean value
Explanation
The not operator inverts the Boolean value of the expression that follows it: True becomes False and False becomes True.
- A
- 49
How are two strings compared when their first characters match?
- A
It compares the number of spaces in each string
- B
It compares the strings' lengths before comparing their characters
- C
It compares characters in sequence, proceeding to later characters when needed
- D
It treats every string comparison as a numeric comparison
Correct answer
CIt compares characters in sequence, proceeding to later characters when needed
Explanation
For string comparisons, Python compares characters in order. When initial characters match, later characters are compared; alphabetically earlier letters are considered smaller.
- A
- 50
What is branching in a program?
- A
It automatically changes a false condition into a true one
- B
It forces every line in a program to run in reverse order
- C
It selects program behavior according to a condition
- D
It converts a condition into a reusable function
Correct answer
CIt selects program behavior according to a condition
Explanation
A conditional statement allows a program to choose which code to execute based on whether a condition is true.
- A
- 51
When does the body of an if statement execute?
- A
It runs only when the if condition evaluates to True
- B
It runs repeatedly until the condition becomes false
- C
It runs only after a matching else block has run
- D
It runs once whether the condition is true or false
Correct answer
AIt runs only when the if condition evaluates to True
Explanation
The indented body of an if block runs only when its condition evaluates to True. If the condition is False, that body is skipped.
- A
- 52
What is the purpose of an else statement?
- A
It executes before the if condition is evaluated
- B
It repeats the preceding if condition a second time
- C
It executes when the preceding if condition is False
- D
It executes whenever the if condition is True
Correct answer
CIt executes when the preceding if condition is False
Explanation
An else block provides an alternative path that executes when the preceding if condition is False.
- A
- 53
When is elif useful?
- A
It executes only when every preceding condition is True
- B
It repeats the first condition until it becomes True
- C
It tests a further condition when earlier conditions were False
- D
It defines a function that returns several conditions
Correct answer
CIt tests a further condition when earlier conditions were False
Explanation
An elif statement tests another condition when the preceding conditions were not true, avoiding many nested if-else blocks.
- A
- 54
What does the modulo operator return?
- A
It converts the divisor to a Boolean value
- B
It returns the remainder after division
- C
It returns the result of multiplying two values
- D
It returns the quotient after integer division
Correct answer
BIt returns the remainder after division
Explanation
The modulo operator returns the remainder after division. An integer divided by 2 has remainder 0 when it is even.
- A
- 55
How can a function test whether an integer is even using modulo?
- A
Check whether the number multiplied by 2 equals 0
- B
Check whether the number divided by 2 is greater than 0
- C
Check whether the number modulo 2 equals 0
- D
Check whether the number is less than 2
Correct answer
CCheck whether the number modulo 2 equals 0
Explanation
A number is even if dividing it by 2 leaves a remainder of 0, so a modulo check can test evenness.
- A
- 56
How does a while loop determine whether to continue?
- A
It repeats its body while its condition evaluates to True
- B
It executes its body only when the condition is False
- C
It executes its body exactly once, regardless of its condition
- D
It iterates through a fixed sequence of values only
Correct answer
AIt repeats its body while its condition evaluates to True
Explanation
A while loop repeatedly executes its body while its condition is True. The condition must eventually change or the loop may continue indefinitely.
- A
- 57
In a while loop that starts with x = 0, runs while x < 5, and adds 1 each time, when does the loop stop?
- A
It stops after x reaches 5 and the condition is false
- B
It stops before printing the value of x
- C
It stops when x first becomes 1
- D
It continues indefinitely because x is initialized to 0
Correct answer
AIt stops after x reaches 5 and the condition is false
Explanation
The while-loop example initializes x at 0, checks x < 5, and increments x by 1 on each iteration. The loop stops when x reaches 5.
- A
- 58
What is the defining behavior of a for loop?
- A
It repeats only while a manually updated Boolean remains true
- B
It runs only when a list contains no duplicate elements
- C
It executes a body once for each variable in a function
- D
It iterates over the values of a sequence or iterable
Correct answer
DIt iterates over the values of a sequence or iterable
Explanation
A for loop iterates over the values in a sequence or other iterable, assigning each value in turn to its loop variable.
- A
- 59
Which statement correctly distinguishes an iteration from an iterable?
- A
An iteration is one execution; an iterable is an object traversed by a loop
- B
An iteration is a data type; an iterable is a variable assignment
- C
An iteration is a collection; an iterable is one execution of a function
- D
An iteration is a conditional; an iterable is a comment in a loop
Correct answer
AAn iteration is one execution; an iterable is an object traversed by a loop
Explanation
An iteration is one execution of a block of code. A loop is the code that carries out iterations, and an iterable is an object whose values can be traversed.
- A
- 60
What sequence does range(5) generate by default?
- A
It starts at the specified stop value and counts backward
- B
It starts at 0 and includes the specified stop value
- C
It starts at 1 and includes the specified stop value
- D
It starts at 0 and stops before the specified stop value
Correct answer
DIt starts at 0 and stops before the specified stop value
Explanation
The range function starts at 0 by default, advances by 1, and stops before its specified stop value. Thus, range(5) produces 0 through 4.
- A
- 61
How does range(1, 10) support a loop that calculates the factorial of 9?
- A
It multiplies the integers 1 through 9, excluding 10
- B
It multiplies every integer from 1 through 10
- C
It multiplies every second integer from 1 through 10
- D
It multiplies the integers 0 through 9, excluding 1
Correct answer
AIt multiplies the integers 1 through 9, excluding 10
Explanation
The range function can take start, stop, and step values. Since the stop value is excluded, range(1, 10) covers integers 1 through 9.
- A
- 62
What does the third parameter of range specify?
- A
It selects whether the sequence begins at zero or one
- B
It specifies how many times the loop body must be printed
- C
It changes the range stop value into an inclusive endpoint
- D
It specifies the increment between successive values
Correct answer
DIt specifies the increment between successive values
Explanation
The third range parameter specifies the step size. For a sequence from 0 to 100 in increments of 10, the stop must be 101 to include 100.
- A
- 63
Which guideline best distinguishes when to use for and while loops?
- A
Use for loops for a sequence and while loops for a condition-controlled repetition
- B
Use while loops for every list and for loops only for integers
- C
Use for loops when no iterable exists and while loops for fixed-length data
- D
Use while loops only when the loop body should execute once
Correct answer
AUse for loops for a sequence and while loops for a condition-controlled repetition
Explanation
A for loop is a natural choice when iterating over a known sequence or fixed collection. A while loop is useful when repetition should continue until a Boolean condition changes.
- A
- 64
Why must a guessing-game loop update its number-of-guesses counter?
- A
The loop should increase its limit after every incorrect guess
- B
The loop should leave its counter unchanged so the user can retry
- C
The loop should update an attempt counter so it can reach its limit
- D
The loop should compare the guess only with a string value
Correct answer
CThe loop should update an attempt counter so it can reach its limit
Explanation
A loop that keeps a counter of incorrect or total guesses can limit the user to a fixed number of attempts. Updating the counter is necessary for the condition to eventually end the loop.
- A
- 65
Why should a number entered with input be converted before comparing it with a generated integer?
- A
Input returns a string, so a numeric guess must be converted to an integer
- B
Input returns a Boolean, so it must be converted to a float
- C
Input returns an integer, so the generated number must become a string
- D
Input returns a list, so it must be converted to a tuple
Correct answer
AInput returns a string, so a numeric guess must be converted to an integer
Explanation
The input function returns the user's entry as a string. Converting a numeric guess to an integer allows it to be compared with a randomly generated integer.
- A
- 66
What does the break keyword do inside a loop?
- A
It runs the loop's else block before each new iteration
- B
It skips only the current iteration and always repeats the loop
- C
It exits the loop immediately
- D
It resets the loop's counter to its initial value
Correct answer
CIt exits the loop immediately
Explanation
The break keyword exits a loop immediately, allowing execution to continue after the loop without waiting for its condition to become false.
- A
- 67
Which operations can concatenate and repeat strings?
- A
Use + to join strings and * to repeat a string
- B
Use / to join strings and + to repeat a string
- C
Use ** to join strings and - to repeat a string
- D
Use - to join strings and / to repeat a string
Correct answer
AUse + to join strings and * to repeat a string
Explanation
Strings can be concatenated with + and repeated with *. The content must include whitespace if a space is desired between concatenated strings.
- A
- 68
What does a backslash do when used as an escape character in a string?
- A
It makes a string mutable while a program runs
- B
It assigns special meaning to every character in the string
- C
It converts the string into a list of characters
- D
It changes the usual interpretation of a following character
Correct answer
DIt changes the usual interpretation of a following character
Explanation
A backslash can act as an escape character, changing the normal interpretation of characters that follow it, such as quotation marks in a string.
- A
- 69
What does \n normally represent in a Python string?
- A
It represents the end of a string, and escaping it starts one
- B
It represents a quotation mark, and escaping it deletes the mark
- C
It represents a tab, and escaping it removes the tab
- D
It represents a newline, and escaping it allows literal characters
Correct answer
DIt represents a newline, and escaping it allows literal characters
Explanation
The sequence \n represents a newline. To display the characters backslash and n literally, the backslash itself must be escaped.
- A
- 70
What is indexing, and where is the first element located in Python?
- A
Indexing changes an iterable into an unordered collection
- B
Indexing accesses an element by position, beginning at 0
- C
Indexing identifies only the data type of an element
- D
Indexing finds every occurrence of a substring
Correct answer
BIndexing accesses an element by position, beginning at 0
Explanation
Indexing identifies an element by its position in an iterable. Python uses zero-based indexing, so the first element is at index 0.
- A
- 71
How do negative indices work in a string or other sequence?
- A
Negative indices select only elements with negative values
- B
Negative indices remove elements from the sequence
- C
Negative indices count backward from the end of a sequence
- D
Negative indices count forward from the beginning
Correct answer
CNegative indices count backward from the end of a sequence
Explanation
Negative indexing counts from the end of a sequence. Index -1 refers to the last element, and -2 to the second-to-last.
- A
- 72
Which positions are selected by the slice [1:4]?
- A
It includes indices 0 through 4
- B
It includes indices 1 through 3, excluding the endpoint
- C
It includes indices 1 through 4, including both endpoints
- D
It includes only index 4
Correct answer
BIt includes indices 1 through 3, excluding the endpoint
Explanation
A slice such as [1:4] includes indices 1, 2, and 3 but excludes the ending index 4.
- A
- 73
What do omitted start and end indices mean in a slice?
- A
An omitted start defaults to 0; an omitted end defaults to the sequence's end
- B
Omitting either index makes the slice empty
- C
An omitted start defaults to the sequence's end; an omitted end defaults to 0
- D
An omitted start means the slice begins at index 1; an omitted end means it stops at index 0
Correct answer
AAn omitted start defaults to 0; an omitted end defaults to the sequence's end
Explanation
If the starting index is omitted, a slice begins at 0. If the ending index is omitted, it continues through the end of the sequence.
- A
- 74
How can Python check whether one string is contained in another?
- A
It returns the position of the last matching substring
- B
It checks for membership and produces a Boolean result
- C
It changes the sequence to contain the searched value
- D
It removes the searched substring from the sequence
Correct answer
BIt checks for membership and produces a Boolean result
Explanation
The in keyword tests whether a substring or element occurs in a sequence and produces a Boolean result.
- A
- 75
What behavior does the string index method have?
- A
It returns the last match's position and inserts missing text
- B
It returns the number of matches and deletes the first one
- C
It returns the first match's position and errors if no match exists
- D
It returns every matching position and returns zero if none exist
Correct answer
CIt returns the first match's position and errors if no match exists
Explanation
The str.index method returns the position of the first matching character or substring. It raises a ValueError if no match exists.
- A
- 76
What does the string format method do?
- A
It converts a string into an iterable without placeholders
- B
It changes the order of arguments automatically based on their types
- C
It joins only strings that have the same data type
- D
It inserts supplied values into designated placeholders
Correct answer
DIt inserts supplied values into designated placeholders
Explanation
The format method inserts supplied values into designated braces. Arguments can be placed by position, by explicit keyword, or by numeric position.
- A
- 77
What does the format specification .2f indicate?
- A
It converts the float into a two-character string
- B
It aligns the value two spaces to the left
- C
It rounds the value to two significant digits and removes decimals
- D
It displays a float with two digits after the decimal point
Correct answer
DIt displays a float with two digits after the decimal point
Explanation
In formatted output, a specification such as .2f displays a floating-point value with two digits after the decimal point.
- A
- 78
Which description best fits a Python list?
- A
They are immutable sequences containing only characters
- B
They are ordered, mutable collections that can contain duplicates
- C
They are unordered and immutable collections of unique values
- D
They are key-value collections accessed only by keys
Correct answer
BThey are ordered, mutable collections that can contain duplicates
Explanation
Lists are ordered, mutable collections. They can contain repeated elements and support indexing and slicing.
- A
- 79
How is a list typically written in Python?
- A
Quotation marks enclose the list, and periods separate its elements
- B
Braces enclose the list, and equal signs separate its elements
- C
Parentheses enclose the list, and colons separate its elements
- D
Square brackets enclose the list, and commas separate its elements
Correct answer
DSquare brackets enclose the list, and commas separate its elements
Explanation
Lists use square brackets, with commas separating their elements. Their elements can have different data types.
- A
- 80
Which comparison between lists and strings is correct?
- A
Both are mutable, but only strings support indexing
- B
Both are ordered sequences, but only lists are mutable
- C
Lists are unordered, while strings are ordered
- D
Both are immutable, but only lists support slicing
Correct answer
BBoth are ordered sequences, but only lists are mutable
Explanation
Lists and strings are both ordered sequences that support indexing and slicing and can contain duplicate elements. Lists are mutable, while strings are immutable.
- A
- 81
What does the list append method do?
- A
It adds an element to the end of a list
- B
It replaces the element at a specified index
- C
It inserts an element at the beginning of a list
- D
It removes the first matching element
Correct answer
AIt adds an element to the end of a list
Explanation
The append method adds one element to the end of a list.
- A
- 82
How does the list insert method work?
- A
It takes an index and an element to insert at that position
- B
It takes an element and removes the matching list item
- C
It takes a list and adds it as several separate elements
- D
It takes an index and returns the element without removing it
Correct answer
AIt takes an index and an element to insert at that position
Explanation
The insert method takes an index and an element, then inserts that element at the specified position in the list.
- A
- 83
What does the list remove method do?
- A
It removes the element at a given index and returns it
- B
It removes a matching value and raises an error if that value is absent
- C
It removes the final element whether or not a value is specified
- D
It removes all duplicate values and returns a new list
Correct answer
BIt removes a matching value and raises an error if that value is absent
Explanation
The remove method deletes the first matching element by value. If the requested value is not present, it raises a ValueError.
- A
- 84
What is the behavior of the list pop method?
- A
It replaces a value at an index with a new value
- B
It adds an element at the end of a list
- C
It removes and returns the element at a specified index
- D
It removes the first occurrence of a specified value
Correct answer
CIt removes and returns the element at a specified index
Explanation
The pop method removes an element by index. The removed element is extracted from the list.
- A
- 85
How does mutability affect changing a list element versus a string character?
- A
A string can be changed in place, but a list cannot
- B
A list can be changed in place, but a string cannot
- C
Both can be changed in place only if they contain numbers
- D
Neither lists nor strings can be changed at a particular index
Correct answer
BA list can be changed in place, but a string cannot
Explanation
Lists are mutable, so an element can be changed directly at an index. Strings are immutable, so changing one character in place produces an error; a new string must be assigned instead.
- A
- 86
What is a tuple?
- A
An immutable sequence that can contain different data types
- B
A mutable, unordered collection of unique elements
- C
A key-value collection whose values must be strings
- D
A numerical array whose elements must share one data type
Correct answer
AAn immutable sequence that can contain different data types
Explanation
A tuple is an immutable sequence that can contain elements of different data types and is commonly written with parentheses.
- A
- 87
What does it mean to unpack a tuple?
- A
Converting each element of a tuple into a dictionary key
- B
Sorting a tuple into a list of key-value pairs
- C
Assigning a tuple's elements to separate variables
- D
Changing the tuple's elements without creating a new tuple
Correct answer
CAssigning a tuple's elements to separate variables
Explanation
Tuple unpacking assigns the elements of a tuple to separate variables, allowing those variables to be used individually.
- A
- 88
How does Python represent multiple values returned by a function?
- A
It returns a tuple containing the values
- B
It returns several independent values without a container
- C
It returns a list that cannot be unpacked
- D
It returns a dictionary whose keys are the values
Correct answer
AIt returns a tuple containing the values
Explanation
When a function returns more than one value, Python packages those values as a tuple, which can then be unpacked.
- A
- 89
Why might player records be stored as tuples inside a list?
- A
Use a string for the collection and a tuple for each column
- B
Use a mutable list for the collection and an immutable tuple for each record
- C
Use a set for the collection and a dictionary for each record
- D
Use a tuple for the collection and a list for each immutable record
Correct answer
BUse a mutable list for the collection and an immutable tuple for each record
Explanation
A list can hold a collection of records, while each record can be a tuple to indicate that the record's values are not intended to change.
- A
- 90
How does a dictionary provide access to its data?
- A
It stores an ordered sequence that is accessed by integer index
- B
It stores only values, while keys are generated during iteration
- C
It maps positions to values and supports lookup in either direction
- D
It maps keys to values, and lookup by key retrieves the associated value
Correct answer
DIt maps keys to values, and lookup by key retrieves the associated value
Explanation
A dictionary maps keys to values. Looking up a key provides its associated value; looking up a value does not automatically find its key.
- A
- 91
Which describes two ways to create a dictionary?
- A
With braces and key=value pairs, or with dict and list indices
- B
Only with square brackets containing comma-separated values
- C
Only with parentheses containing positional indices
- D
With braces and key:value pairs, or with dict and suitable keyword arguments
Correct answer
DWith braces and key:value pairs, or with dict and suitable keyword arguments
Explanation
A dictionary can be created with braces using colons between keys and values, or with dict and keyword arguments when keys are strings.
- A
- 92
Which constraint applies to dictionary keys?
- A
Keys must be lists so they can be changed after insertion
- B
Keys must be mutable, so lists are valid but strings are not
- C
Keys must be unique strings and cannot be numbers or tuples
- D
Keys must be immutable, so a list cannot be used as a key
Correct answer
DKeys must be immutable, so a list cannot be used as a key
Explanation
Dictionary keys must be immutable, so strings, numbers, and tuples can be keys, while mutable lists cannot.
- A
- 93
What should you use if the position order of a collection matters?
- A
Dictionaries are indexed by position, so they are preferred for ordered records
- B
Dictionaries are always sorted by their values
- C
Dictionaries preserve positions only when all keys are integers
- D
Dictionaries are accessed by keys, so lists suit order-dependent data better
Correct answer
DDictionaries are accessed by keys, so lists suit order-dependent data better
Explanation
Dictionaries are unordered in the described model and are accessed by keys, not by positional index. A list is a better choice when position order matters.
- A
- 94
What does key in dictionary test?
- A
It checks whether a value appears anywhere in the dictionary
- B
It checks whether a key exists in the dictionary
- C
It checks whether a key's value is truthy
- D
It checks whether a dictionary is in a particular position
Correct answer
BIt checks whether a key exists in the dictionary
Explanation
Using in with a dictionary checks whether a key exists. It does not test whether a value occurs in the dictionary.
- A
- 95
What do the dictionary methods keys, values, and items provide?
- A
keys returns keys, values returns values, and items returns pairs
- B
keys returns values, values returns pairs, and items returns keys
- C
keys returns pairs, values returns keys, and items returns values
- D
All three methods return only dictionary keys
Correct answer
Akeys returns keys, values returns values, and items returns pairs
Explanation
The keys, values, and items methods retrieve, respectively, dictionary keys, dictionary values, and key-value pairs.
- A
- 96
What does a basic for loop over a dictionary iterate over by default?
- A
It yields the values only
- B
It yields key-value pairs only
- C
It yields the keys by default
- D
It yields values in sorted order
Correct answer
CIt yields the keys by default
Explanation
When looping directly over a dictionary, iteration yields its keys by default. The values or pairs can be accessed through the corresponding methods.
- A
- 97
Which description best fits a Python set?
- A
It contains unique, unordered elements and is itself mutable
- B
It contains only numerical values and is immutable
- C
It contains ordered, repeated values and cannot be modified
- D
It contains key-value pairs that are accessed by index
Correct answer
AIt contains unique, unordered elements and is itself mutable
Explanation
A set contains unique, unordered elements. Its elements must be immutable, although the set itself can be modified.
- A
- 98
What happens when a list with duplicate elements is passed to set?
- A
It turns every iterable into a dictionary of positions
- B
It sorts the iterable and converts each element to a string
- C
It keeps only unique elements from the iterable
- D
It preserves every duplicate and keeps the iterable's order
Correct answer
CIt keeps only unique elements from the iterable
Explanation
Passing an iterable to set creates a set of its distinct elements. Repeated values are removed; a string is treated as an iterable of characters.
- A
- 99
How should an empty set be created?
- A
Use (), because empty parentheses create an empty set
- B
Use set(), because empty braces create a dictionary
- C
Use {}, because empty braces always create a set
- D
Use [], because square brackets create an empty set
Correct answer
BUse set(), because empty braces create a dictionary
Explanation
Empty braces create an empty dictionary, not a set. Use set() to create an empty set.
- A
- 100
Why can a set not be accessed with ordinary positional indexing?
- A
They can be indexed only by negative positions
- B
They can be indexed but cannot be sliced
- C
They cannot be indexed or sliced by position
- D
They can be sliced only if their values are strings
Correct answer
CThey cannot be indexed or sliced by position
Explanation
Sets do not support positional indexing or slicing because their elements are unordered.
- A
- 101
Which description correctly compares common set operations?
- A
Intersection returns one-sided elements; union returns shared elements; difference returns all; symmetric difference returns duplicates
- B
Intersection returns all elements; union returns shared elements; difference returns paired elements
- C
Intersection returns shared elements; union returns all; difference returns one-sided elements; symmetric difference returns elements not shared
- D
Intersection removes duplicates; union sorts values; difference reverses the sets; symmetric difference returns their common elements
Correct answer
CIntersection returns shared elements; union returns all; difference returns one-sided elements; symmetric difference returns elements not shared
Explanation
Intersection returns elements common to both sets; union returns all elements in either set; difference returns elements in one set but not the other; symmetric difference returns elements in exactly one set.
- A
- 102
How does set difference differ from symmetric difference?
- A
Difference is directional, while symmetric difference returns nonshared elements from both sets
- B
Difference returns shared elements, while symmetric difference returns only elements from the first set
- C
Both operations return all elements from both sets
- D
Difference is symmetric, while symmetric difference depends on operand order
Correct answer
ADifference is directional, while symmetric difference returns nonshared elements from both sets
Explanation
Difference is directional: A - B contains elements in A that are not in B. Symmetric difference returns elements found in either set but not both.
- A
- 103
What is a list comprehension?
- A
It changes an existing list into a tuple without copying values
- B
It creates a dictionary by placing keys after the for clause
- C
It sorts an existing list by applying a comparison function
- D
It builds a new list by expressing the element calculation before the for clause
Correct answer
DIt builds a new list by expressing the element calculation before the for clause
Explanation
A list comprehension creates a new list from an existing iterable by placing the desired expression before the for clause.
- A
- 104
What is a nested loop?
- A
A loop placed inside another loop
- B
A loop that contains two conditions but no body
- C
Two loops that run once in alternating order
- D
A loop that calls itself until a list is empty
Correct answer
AA loop placed inside another loop
Explanation
A nested loop is a loop inside another loop. For each outer-loop iteration, the inner loop runs through its sequence.
- A
- 105
What is a Python library or package?
- A
A data structure used exclusively for unordered values
- B
A reusable collection of code that may contain modules
- C
A file format that separates values with commas
- D
A single variable accessible only inside a function
Correct answer
BA reusable collection of code that may contain modules
Explanation
A library or package is a reusable collection of code that may contain modules and documentation. The terms are often used interchangeably.
- A
- 106
What is a Python module?
- A
A variable that can only be accessed within one function
- B
A single notebook cell that cannot be reused
- C
A Python file containing reusable code components
- D
A table with labeled rows and columns
Correct answer
CA Python file containing reusable code components
Explanation
A module is a Python file containing collections of functions, classes, or global variables that can be imported into a program.
- A
- 107
What distinguishes a global variable?
- A
They are values that cannot be reassigned
- B
They can be accessed only inside the function that creates them
- C
They are variables that exist only in imported libraries
- D
They can be accessed from anywhere in a program or script
Correct answer
DThey can be accessed from anywhere in a program or script
Explanation
Global variables can be accessed from anywhere in a program or script, unlike variables limited to a local scope.
- A
- 108
Which comparison of common Python data libraries is accurate?
- A
Matplotlib creates visualizations; Seaborn simplifies common plots; NumPy supports numerical computation; pandas analyzes tabular data
- B
Matplotlib tests models; Seaborn manages files; NumPy formats tables; pandas controls program flow
- C
Matplotlib stores arrays; Seaborn reads databases; NumPy creates reports; pandas generates random values
- D
Matplotlib analyzes tables; Seaborn performs random sampling; NumPy formats strings; pandas creates modules
Correct answer
AMatplotlib creates visualizations; Seaborn simplifies common plots; NumPy supports numerical computation; pandas analyzes tabular data
Explanation
Matplotlib creates visualizations; Seaborn is based on Matplotlib and provides a simpler interface for common plots. NumPy supports numerical computation, while pandas focuses on tabular data manipulation and analysis.
- A
- 109
What does vectorization mean in NumPy?
- A
It converts all data into strings before calculation
- B
It performs an operation on multiple data components together
- C
It applies an operation to one element per separate loop iteration
- D
It stores each element in a separate Python module
Correct answer
BIt performs an operation on multiple data components together
Explanation
Vectorization applies operations to multiple components at once. This can make code simpler and faster and can reduce memory use compared with element-by-element iteration.
- A
- 110
What is a NumPy ndarray?
- A
A dictionary whose keys are numeric indices
- B
A two-dimensional table that can contain arbitrary mixed types
- C
A module that contains only plotting functions
- D
An N-dimensional array used for vectorized operations
Correct answer
DAn N-dimensional array used for vectorized operations
Explanation
The NumPy ndarray is its core data structure. It is an N-dimensional array that supports vectorized computation.
- A
- 111
Which statement about modifying a NumPy array is correct?
- A
Both values and size can always be changed in place
- B
Element values can change, but changing the array's size requires reassignment
- C
Array size can change in place, but element values cannot
- D
Neither element values nor array size can ever change
Correct answer
BElement values can change, but changing the array's size requires reassignment
Explanation
NumPy arrays are mutable, so their elements can be changed. Their size cannot be changed in place; changing the size requires creating and assigning a replacement array.
- A
- 112
What happens when a NumPy array is created from values of mixed types?
- A
Arrays can contain only integers and floats together
- B
All elements share one data type, with conversion when possible
- C
Each element must have a different data type
- D
Mixed types always cause an error when the array is created
Correct answer
BAll elements share one data type, with conversion when possible
Explanation
An ndarray must have one element data type. NumPy may coerce mixed input values to a common type, such as converting integers to strings when possible.
- A
- 113
What information do shape, ndim, and dtype provide for a NumPy array?
- A
shape gives the element type, ndim gives the shape, and dtype gives the dimension count
- B
shape gives the dimensions, ndim gives the dimension count, and dtype gives the element type
- C
shape gives the dimension count, ndim gives the element type, and dtype gives the shape
- D
All three attributes report the number of array elements
Correct answer
Bshape gives the dimensions, ndim gives the dimension count, and dtype gives the element type
Explanation
The shape attribute gives an array's dimensions, while ndim reports the number of dimensions. The dtype attribute identifies the element data type.
- A
- 114
How can a two-dimensional NumPy array be created from Python data?
- A
It is created from a tuple of keys and values and has two dimensions
- B
It is created from a list of unequal-length strings and has one dimension
- C
It can be created from equally sized lists, with rows and columns
- D
It must contain two arrays of different data types
Correct answer
CIt can be created from equally sized lists, with rows and columns
Explanation
A two-dimensional array can be constructed from a list of equally sized lists. Its shape corresponds to its number of rows and columns.
- A
- 115
What does the NumPy reshape method do?
- A
It changes every value to a different data type
- B
It converts the array's elements into dictionary keys
- C
It reorganizes an array into a specified compatible shape
- D
It appends a new element to the array
Correct answer
CIt reorganizes an array into a specified compatible shape
Explanation
The reshape method changes the organization and dimensions of an array. The requested shape must be compatible with the number of elements.
- A
- 116
Why is NumPy commonly imported with the alias np?
- A
It prevents NumPy's array functions from being used
- B
It provides a shorter name for referring to NumPy
- C
It converts NumPy into a built-in Python function
- D
It creates a second copy of the NumPy library
Correct answer
BIt provides a shorter name for referring to NumPy
Explanation
The alias np is the conventional short name for NumPy. Aliasing makes references shorter, while following the standard makes code familiar to other readers.
- A
- 117
Why is understanding NumPy useful when learning pandas?
- A
Pandas is a replacement for Python's built-in syntax
- B
Pandas is built on NumPy, so NumPy knowledge supports pandas work
- C
Pandas requires every operation to be written as a Python loop
- D
Pandas is a plotting library that cannot use numerical arrays
Correct answer
BPandas is built on NumPy, so NumPy knowledge supports pandas work
Explanation
Pandas is built on NumPy and uses NumPy arrays and functionality. Understanding NumPy concepts helps when working with pandas.
- A
- 118
What is a pandas DataFrame?
- A
A one-dimensional sequence of unlabeled values
- B
A function that reads only comma-separated text
- C
An unordered collection of unique elements
- D
A two-dimensional labeled structure with rows and columns
Correct answer
DA two-dimensional labeled structure with rows and columns
Explanation
A pandas DataFrame is a two-dimensional labeled data structure with rows and columns, similar to a spreadsheet or SQL table.
- A
- 119
What is a pandas Series?
- A
A two-dimensional unlabeled matrix containing only numbers
- B
A one-dimensional labeled array, often representing a row or column
- C
A module that imports CSV files into Python
- D
A collection of dictionary keys with no associated values
Correct answer
BA one-dimensional labeled array, often representing a row or column
Explanation
A pandas Series is a one-dimensional labeled array and commonly represents one row or column from a DataFrame.
- A
- 120
Which pandas tools can create DataFrames from Python objects and CSV files?
- A
Use read_csv for dictionaries and DataFrame only for text files
- B
Use DataFrame for Python objects and read_csv for CSV files
- C
Use type for CSV files and shape for dictionaries
- D
Use Series for every table and read_csv for NumPy arrays
Correct answer
BUse DataFrame for Python objects and read_csv for CSV files
Explanation
Pandas provides a DataFrame function for creating DataFrames from sources such as dictionaries and NumPy arrays, as well as a read_csv function for CSV files.
- A
- 121
What does CSV stand for, and how are values separated in it?
- A
A pandas object that stores row and column labels
- B
A plaintext format that uses commas to separate values
- C
A module that converts strings into Python functions
- D
A file format that stores values only in binary form
Correct answer
BA plaintext format that uses commas to separate values
Explanation
CSV means comma-separated values. It is a plaintext format in which commas separate distinct values.
- A
- 122
Which statement correctly describes common DataFrame attributes and methods?
- A
columns reports memory use, shape reports non-null counts, and info returns row labels
- B
columns gives column labels, shape gives dimensions, and info summarizes structure
- C
columns reports row counts, shape reports data types, and info returns only column names
- D
All three return the actual values from every cell in the DataFrame
Correct answer
Bcolumns gives column labels, shape gives dimensions, and info summarizes structure
Explanation
The columns attribute provides column labels, shape provides the number of rows and columns, and info summarizes columns, types, non-null counts, and memory use.
- A
- 123
How are null values commonly represented in pandas?
- A
Missing values are represented as the string 'null' in every case
- B
Missing values are always represented as zero
- C
Missing values are represented as NaN
- D
Missing values are represented as an empty dictionary
Correct answer
CMissing values are represented as NaN
Explanation
Pandas represents missing or null values as NaN, short for 'not a number.'
- A
- 124
What is returned when selecting one column versus multiple columns by name?
- A
Selecting one column returns a DataFrame, while several columns return a Series
- B
Both single- and multiple-column selection return a NumPy array
- C
Selecting one column returns a dictionary, while several return a tuple
- D
Selecting one column returns a Series, while several return a DataFrame
Correct answer
DSelecting one column returns a Series, while several return a DataFrame
Explanation
Selecting one DataFrame column by name returns a Series. Selecting multiple columns using a list of names returns a DataFrame.
- A
- 125
Which statement about selecting DataFrame columns by name is accurate?
- A
Dot notation and bracket notation always return different data types
- B
Bracket notation is general, while dot notation has restrictions on column names
- C
Dot notation works for every column name, including names with spaces
- D
Bracket notation selects rows only, while dot notation selects columns only
Correct answer
BBracket notation is general, while dot notation has restrictions on column names
Explanation
Bracket notation can select columns by name. Dot notation can also work for simple column names without whitespace, but brackets are more general and often clearer.
- A
- 126
How does iloc select rows and columns?
- A
It selects rows and columns only by their labels
- B
It selects columns by name and rows by Boolean value
- C
It selects values by their data types
- D
It selects by integer position, with a range excluding its endpoint
Correct answer
DIt selects by integer position, with a range excluding its endpoint
Explanation
iloc selects by integer position. A single integer selects a row, and ranges use a start-inclusive, end-exclusive convention.
- A
- 127
What is the primary difference between loc and iloc?
- A
Both select only by column names
- B
loc selects by integer positions, while iloc selects by labels
- C
loc selects by labels, while iloc selects by integer positions
- D
Both select only by Boolean masks
Correct answer
Cloc selects by labels, while iloc selects by integer positions
Explanation
loc selects using labels, such as named row indices and column names, whereas iloc selects by integer position.
- A
- 128
How does Boolean masking filter a DataFrame?
- A
It overlays column names and keeps only matching labels
- B
It filters rows according to aligned True and False values
- C
It sorts all rows according to their Boolean values
- D
It changes every False value in the DataFrame to NaN
Correct answer
BIt filters rows according to aligned True and False values
Explanation
A Boolean mask is a Boolean Series aligned with the DataFrame's index. Applying it keeps rows marked True and filters out rows marked False.
- A
- 129
Which symbols represent and, or, and not in pandas Boolean filtering?
- A
Use | for and, & for or, and ~ for equality
- B
Use + for and, - for or, and / for not
- C
Use & for and, | for or, and ~ for not
- D
Use ~ for and, & for not, and | for equality
Correct answer
CUse & for and, | for or, and ~ for not
Explanation
In pandas Boolean conditions, & represents and, | represents or, and ~ represents not. Parentheses around each condition help ensure the logic is evaluated as intended.
- A
- 130
What does the pandas groupby method do?
- A
It changes every column into a separate Series
- B
It joins two DataFrames using matching column names
- C
It groups rows by column values for subsequent analysis
- D
It filters rows by a single Boolean condition
Correct answer
CIt groups rows by column values for subsequent analysis
Explanation
The groupby method creates groups based on values in one or more columns. Applying an aggregation such as mean or sum then summarizes each group.
- A
- 131
What is the purpose of the pandas agg method?
- A
It applies one or more calculations to grouped data
- B
It concatenates rows without grouping them
- C
It converts every group into a dictionary key
- D
It creates a Boolean mask from a DataFrame
Correct answer
AIt applies one or more calculations to grouped data
Explanation
The agg method applies one or more aggregation functions to grouped data, such as mean, median, or a custom-defined function.
- A
- 132
What do axes 0 and 1 indicate when concatenating DataFrames?
- A
Axis 0 sorts rows; axis 1 sorts columns
- B
Axis 0 selects keys; axis 1 selects values
- C
Axis 0 is vertical across rows; axis 1 is horizontal across columns
- D
Axis 0 is horizontal across columns; axis 1 is vertical across rows
Correct answer
CAxis 0 is vertical across rows; axis 1 is horizontal across columns
Explanation
The concat function can combine DataFrames vertically or horizontally. Axis 0 is vertical across rows; axis 1 is horizontal across columns.
- A
- 133
What is the role of reset_index(drop=True) after vertically concatenating DataFrames?
- A
Vertical concatenation adds rows, and drop=True prevents keeping the old index as a column
- B
Vertical concatenation adds columns, and reset_index deletes all data
- C
Vertical concatenation adds keys, and reset_index sorts the values
- D
Vertical concatenation adds rows, but reset_index always removes all columns
Correct answer
AVertical concatenation adds rows, and drop=True prevents keeping the old index as a column
Explanation
Concatenating compatible DataFrames vertically adds rows. Resetting the index can create a fresh sequential index; drop=True prevents the old index from becoming a column.
- A
- 134
What is a key in the context of merging DataFrames?
- A
It adds rows by matching their integer positions only
- B
It combines only DataFrames that have identical row counts
- C
It joins DataFrames based on shared points of reference called keys
- D
It appends columns without considering common values
Correct answer
CIt joins DataFrames based on shared points of reference called keys
Explanation
A merge joins DataFrames using shared keys, which provide common points of reference for matching rows.
- A
- 135
How do inner and outer joins differ?
- A
Inner keeps keys from the left; outer keeps keys from the right
- B
Inner keeps keys from the right; outer keeps keys from the left
- C
Inner keeps all keys; outer keeps only shared keys
- D
Inner keeps shared keys; outer keeps keys from both DataFrames
Correct answer
DInner keeps shared keys; outer keeps keys from both DataFrames
Explanation
An inner join keeps matching keys found in both DataFrames. An outer join keeps all keys from both, with missing values where a row has no matching data.
- A
- 136
Which statement correctly describes left and right joins?
- A
A left join retains all right keys; a right join retains all left keys
- B
A left join retains all keys from both; a right join retains shared keys
- C
Both joins retain only keys shared by the DataFrames
- D
A left join retains all left keys; a right join retains all right keys
Correct answer
DA left join retains all left keys; a right join retains all right keys
Explanation
A left join retains every key from the left DataFrame; a right join retains every key from the right DataFrame.
- A
- 137
What happens to unmatched data during an outer join?
- A
The unmatched columns are represented with NaN values
- B
The unmatched key is removed from the outer join
- C
The merge fails unless every key is present in both inputs
- D
The missing values are replaced with zeros automatically
Correct answer
AThe unmatched columns are represented with NaN values
Explanation
When an outer join includes a key that has no matching row in one DataFrame, the missing values from that DataFrame appear as NaN in the result.
- A
- 138
Which structure defines a tidy dataset?
- A
Each file is a row, each business case is a column, and each variable is a table
- B
Each observation is a column, each variable is a row, and each dataset is a cell
- C
Each variable is a column, each observation is a row, and each observational unit is a table
- D
Each variable is a separate table, each row is a data type, and columns are observations
Correct answer
CEach variable is a column, each observation is a row, and each observational unit is a table
Explanation
Tidy data is structured so each variable is a column, each observation is a row, and each type of observational unit is a table.
- A
- 139
What is the purpose of data tidying?
- A
It structures data to facilitate analysis and related tasks
- B
It converts every value to a string so formats are consistent
- C
It removes all rows that contain more than one variable
- D
It merges unrelated datasets into one table without keys
Correct answer
AIt structures data to facilitate analysis and related tasks
Explanation
Tidying structures a dataset so that it is easier to manipulate, model, and visualize.
- A
- 140
What is the central data task in the portfolio project?
- A
To build a machine learning model without examining the data
- B
To create visualizations before the data is loaded
- C
To load, clean, and structure data for a selected business scenario
- D
To convert the dataset into a Python library
Correct answer
CTo load, clean, and structure data for a selected business scenario
Explanation
The project task is to load, clean, and structure data from unstructured files so the result is a tidy dataset suited to a business scenario.
- A
- 141
Why document project steps and decisions in a strategy document?
- A
It replaces the need to prepare a structured dataset
- B
It records the process and reasoning for later explanation
- C
It automatically determines which business scenario is correct
- D
It converts unstructured files into Python functions
Correct answer
BIt records the process and reasoning for later explanation
Explanation
Documenting the steps and reasoning in a PACE strategy document can help explain the work and thought process to future hiring managers.
- A
- 142
How should a data professional adapt an explanation of a project for an audience?
- A
Focus only on tools and omit the business challenge
- B
Consider the audience's goals, knowledge, and information needs
- C
Assume every interviewer has the same technical background
- D
Use the same technical detail regardless of the audience
Correct answer
BConsider the audience's goals, knowledge, and information needs
Explanation
When explaining a technical project, consider the audience's goals, existing knowledge, and information needs so the explanation is relevant to them.
- A

Ask anything
We've read this whole study set, so questions about it get the best answers.