exam studyguide
Replace the ??? in the following comprehension statement to include in list4 only the even values produced by the for clause: list4 = [item for item in range(1, 11) if item ???]
%2 == 0
The value of the expression of: In [1]: floor(-3.14159)
-4.0
What does the following for statement print? for counter in range(10):print(counter, end=' ')
0 1 2 3 4 5 6 7 8 9
What does the following line of code display? print(10, 20, 30, sep=', ')
10, 20, 30
The following creates an array from a _________-row-by-_________-column list: np.array([[1, 2, 3], [4, 5, 6]])
2 3
When Python "adds" the string values '7' and '3', it produces:
73
Which of the following statements is false? You can create an array from a range of elements, then use array method reshape to transform the one-dimensional array into a multidimensional array. The following code creates an array containing the values from 1 through 20, then reshapes it into four rows by five columns: np.arange(1, 21).reshape(4, 5) A 24-element one-dimensional array can be reshaped into a 2-by-12, 8-by-3 or 4-by-8 array, and vice versa. All of the above are true.
A 24-element one-dimensional array can be reshaped into a 2-by-12, 8-by-3 or 4-by-8 array, and vice versa.
Which of the following statements is false? You can delete a key-value pair from a dictionary with the del statement You can remove a key-value pair with the dictionary method pop, which returns the value for the removed key. Method clean deletes the dictionary's key-value pairs: Operators in and not in can determine whether a dictionary contains a specified key.
Method clean deletes the dictionary's key-value pairs:
Which of the following statements is true with respect to displaying an array of 1000 items or more? NumPy always drops the middle rows and middle columns from the output. NumPy always drops the middle rows from the output. NumPy always drops the middle columns from the output. NumPy drops the middle rows, middle columns or both from the output.
NumPy drops the middle rows, middle columns or both from the output.
Which of the following statements is false? The following assignment statement adds the values of variables x and y and assigns the result to the variable total: total = x + y The preceding snippet is read, "total is assigned the value of x + y." The = symbol is the assignment operator. The right side of the = symbol always executes first, then the result is assigned to the variable on the symbol's left side.
The = symbol is the assignment operator.
Which of the following statements is false? Tuples are immutable. Tuples must store heterogeneous data. A tuple's length is its number of elements. A tuple's length cannot change during program execution.
Tuples must store heterogeneous data.
The following session calls the string object s's object's lower and upper methods, which produce new strings containing all-lowercase and all-uppercase versions of the original string, leaving s unchanged: In [1]: s = 'Hello'In [2]: s.lower() # call lower method on string object sOut[2]: 'hello'In [3]: s.upper()Out[3]: 'HELLO' After the preceding session, s contains 'HELLO'.
fale
Based on the following function definition: def rectangle_area(length, width): """Return a rectangle's area.""" return length * width The following call results in results in TypeError because the order of keyword arguments matters—they need to match the corresponding parameters' positions in the function definition: rectangle_area(width=5, length=10)
false
The following code creates a dictionary with the country-name keys 'Finland', 'South Africa' and 'Nepal' and their corresponding Internet country code values 'fi', 'za' and 'np': country_codes = {'Finland', 'fi', 'South Africa', 'za', 'Nepal', 'np'}
false
The following code creates a list, then uses del to remove its first element: numbers = list(range(0, 10))del numbers[1]
false
The following code produces 10 random integers in the range 1-6 to simulate rolling a six-sided die: import randomfor roll in range(10):print(random.randrange(1, 6), end=' ')
false
he following code creates a Series of student grades from a list of integers: import pandas as pd grades = pd.Series([87, 100, 94]) By default, a Series has integer indexes numbered sequentially from 1, and the Series argument may be a tuple, a dictionary, an array, another Series or a single value.
false
Lists may store ________ data, that is, data of many different types.
heterogeneous
Consider the list color_names: color_names = ['orange', 'yellow', 'green'] Write the statement that uses the insert method to insert 'red' at index 0.
insert(0, 'red')
Assume the following array definitions: import numpy as npintegers = np.array([[1, 2, 3], [4, 5, 6]])floats = np.array([0.0, 0.1, 0.2, 0.3, 0.4]) The attribute contains an array's number of dimensions and the attribute contains a specifying an array's dimensions:
ndim, shape, tuple dim, size, tuple
Write the statement that creates a slice consisting of the elements at indices 2 through 6 of a numbers: numbers = [2, 3, 5, 7, 11, 13, 17, 19]
numbers[2:6]
We use array method ________ to produce two-dimensional arrays from one-dimensional ranges
reshape
What is the output of the following code for Out[5]: In [4]: x = 'dog'In [5]: type(x)Out[5]: Selected Answer: strCorrect Answer:
str
Assume x is 3, y is 7.1 and z is '11.5'. Which of the following statements is incorrect? type(x) is int the value of z is 11.5 the value of y is 7.1 type(z) is str
the value of z is 11.5
A dictionary is an unordered collection which stores key-value pairs that map immutable keys to values, just as a conventional dictionary maps words to definitions.
true
Assuming the following DataFrame grades: Wally Eva Sam Katie Bob Test1 87 100 94 100 83 Test2 96 87 77 81 65 Test3 70 90 90 82 85 rather than getting the summary statistics by student, you can get them by test. Simply call describe on grades.T, as in: grades.T.describe()
true
Assuming the following DataFrame grades: Wally Eva Sam Katie Bob Test1 87 100 94 100 83 Test2 96 87 77 81 65 Test3 70 90 90 82 85 To see the average of all the students' grades on each test, call mean on the T attribute: grades.T.mean()
true
Assuming the following array grades: grades = np.array([[87, 96, 70], [100, 87, 90], [94, 77, 90], [100, 81, 82]]) To select multiple sequential rows, use slice notation, as in grades[0:2] and to select multiple non-sequential rows, use a list of row indices, as in grades[[1, 3]]
true
Consider a Series of hardware-related strings: hardware = pd.Series(['Hammer', 'Saw', 'Wrench']) The following code calls string method contains on each element to determine whether the value of each element contains a lowercase 'a': hardware.str.contains('a') and returns a Series containing bool values indicating the contains method's result for each element.
true
Element-wise operations are applied to every array element, so given an integer array named numbers, the expression numbers * 2 multiplies every element by 2, and the expression numbers ** 3
true
For a two-dimensional array grades in which each row represents one student's grades on several exams, we can calculate each student's average grade with: grades.mean(axis=1)
true
If numbers is a five-element integer array, numbers * 2 is equivalent to: numbers * [2, 2, 2, 2, 2]
true
Sets may contain only immutable objects, like strings, ints, floats and tuples that contain only immutable elements.
true
The array methods sum, min, max, mean, std (standard deviation) and var (variance) are each functional-style programming reductions.
true
Which of the following statements is false? A function definition begins with the def keyword, followed by the function name, a set of parentheses and a semicolon (;). When you change a function's code, all calls to the function execute the updated version. The following code calls square first, then print displays the result: print('The square of 7 is', square(7)) The required parentheses contain the function's parameter list—a comma-separated list of parameters representing the data that the function needs to perform its task.
A function definition begins with the def keyword, followed by the function name, a set of parentheses and a semicolon (;).
Which of the following statements is false? A string delimited by single quotes may include double-quote characters: print('Display "hi" in quotes') A string delimited by double quotes may include single quote characters: print("Display the name O'Brien") A string delimited by double quotes may not include double quotes. To avoid using \' and \" inside strings, you can enclose such strings in triple quotes: print(""""Display the name O'Brien"""")
A string delimited by double quotes may not include double quotes.
Which of the following statements is incorrect: min(17, 19, 23, 29, 31, 37, 43) is a valid call to built-in function min, The range of values is simply the minimum through the maximum value. Much of data science is devoted to getting to know your data. All of the above are correct.
All of the above are correct.
Based on the following function definition that can receive an arbitrary number of arguments: In [1]: def average(*args):...: return sum(args) / len(args)...: which of the following statements is false? The following session calls average several times confirming that it works with arbitrary argument lists of different lengths: In [3]: average(5, 10, 15)Out[3]: 10.0 The following session calls average several times confirming that it works with arbitrary argument lists of different lengths: In [2]: average(5, 10)Out[2]: 7.5 The following session calls average several times confirming that it works with arbitrary argument lists of different lengths: In [4]: average(20, 20, 20, 20)Out[4]: 20 All of the above are true.
All of the above are true.
Assuming the following DataFrame grades: Wally Eva Sam Katie Bob Test1 87 100 94 100 83 Test2 96 87 77 81 65 Test3 70 90 90 82 85 Which of the following statements is false? One benefit of pandas is that you can quickly and conveniently look at your data in many different ways, including selecting portions of the data. The following expression selects 'Eva' column and returns it as a Series: grades['Eva'] If a DataFrame's column-name strings are valid Python identifiers, you can use them as attributes. The following code selects the 'Sam' column using the Sam attribute: grades.Sam All of the above statements are true.
All of the above statements are true.
Which of the following statement(s) will reverse the order of the below items list numbers: numbers = [2, 3, 4, 6, 7, 13, 17, 19] reversed_numbers = [item for item in reversed(numbers)] The following code concisely creates a new list in reverse order: numbers[::-1] To sort a list in descending order, call list method sort with the optional keyword argument reverse=True. numbers.sort(reverse=True) All of the above statements are true.
All of the above statements are true.
Which of the following statements about the IPython session below is true? In [1]: gender = 'Female' In [2]: age = 70 In [3]: if gender == 'Female' and age >= 65: ...: print('Senior female') ...: Senior female The session defines two variables, then tests a condition that's True if and only if both simple conditions are True—if either (or both) of the simple conditions is False, the entire and expression is False. The right side of the and operator evaluates only if the left side is True. The combined condition can be made clearer by adding redundant (unnecessary) parentheses (gender == 'Female') and (age >= 65) All of the above statements are true.
All of the above statements are true.
Which of the following statements is false? If randrange truly produces integers at random, every number in its range has an equal probability (or chance or likelihood) of being returned each time we call it. We can use Python's underscore (_) digit separator to make a value like 3000000 more readable as 3_000_000. The expression range(6,000,000) would be incorrect. Commas separate arguments in function calls, so Python would treat range(6,000,000) as a call to range with the three arguments 6, 0 and 0. All of the above statements are true.
All of the above statements are true.
Which of the following are reasons why Python is popular and everyone should consider learning it: It's open source, free and widely available with a massive open-source community. It's easier to learn than languages like C, C++, C# and Java, enabling novices and professional developers to get up to speed quickly. It's easier to read than many other popular programming languages. All of the above.
All of the above.
Which of the following statements is false? DataFrames have a describe method that calculates basic descriptive statistics for the data and returns them as two-dimensional array. In a DataFrame, the statistics are calculated by column. Method describe nicely demonstrates the power of array-oriented programming with a functional-style call—Pandas handles internally all the details of calculating these statistics for each column. You can control the precision of floating-point values and other default settings with pandas' set_option function.
DataFrames have a describe method that calculates basic descriptive statistics for the data and returns them as two-dimensional array.
Which of the following statements is false? The following if statement uses the == comparison operator to determine whether the values of variables number1 and number2 are equal: if number1 == number2:print(number1, 'is equal to', number2) Each if statement consists of the keyword if, the condition to test, and a colon (:) followed by an indented body called a suite. Each suite contains zero or more statements. Forgetting the colon (:) after the condition is a common syntax error.
Each suite contains zero or more statements.
Which of the following statements is false? The argument of each of the functions mean, median and mode must be an iterable. To help confirm the median and mode values of a grades list, you can use the built-in sorted function to get a copy of grades with its values arranged in increasing order, as in the following session, which makes it clear that both the median and the mode are 85: In [1]: grades = [85, 93, 45, 89, 85] In [2]: sorted(grades) Out[2]: [45, 85, 85, 89, 93] If a list's number of values is even, median returns the mode of the two middle values. The mode function causes a StatisticsError for lists like [85, 93, 45, 89, 85, 93] in which there are two or more "most frequent" values. Such a set of values is said to be bimodal.
If a list's number of values is even, median returns the mode of the two middle values.
Which of the following statements is false? Python applies the operators in arithmetic expressions according to the rules of operator precedence, which are generally the same as those in algebra. Parentheses have the highest level of precedence, so expressions in parentheses evaluate first—thus, parentheses may force the order of evaluation to occur in any sequence you desire. In expressions with nested parentheses, such as (a / (b - c)), the expression in the innermost parentheses (that is, b - c) evaluates first. If an expression contains several exponentiation operations, Python applies them from left to right.
If an expression contains several exponentiation operations, Python applies them from left to right.
Which of the following statements is false? Using the equality operator == instead of the assignment symbol = in an assignment statement can lead to subtle problems. If instead of defining a variable grade with the assignment: grade = 85 we accidentally write: grade == 85 then grade would be undefined and we'd get a NameError. If grade had been defined before the statement grade == 85, the statement would evaluate to True or False, depending on grade's value, and not perform the intended assignment—fortunately, this is harmless. All of the above statements are true.
If grade had been defined before the statement grade == 85, the statement would evaluate to True or False, depending on grade's value, and not perform the intended assignment—fortunately, this is harmless.
Which of the following statements is false? NumPy arrays use only zero-based integer indexes. Like arrays, Series use only zero-based integer indexes. Series may have missing data, and many Series operations ignore missing data by default. All of the above statements are true.
Like arrays, Series use only zero-based integer indexes.
Which of the following statements is false? Pandas is the most popular library for dealing with mixed data types, customized indexing, missing data, and data that needs to be manipulated into forms appropriate for the databases and data analysis packages. Data science presents unique demands for which more customized data structures are required. NumPy's array is optimized for heterogeneous numeric data that's accessed via integer indices. Pandas provides two key collections—Series for one-dimensional collections and DataFrames for two-dimensional collections.
NumPy's array is optimized for heterogeneous numeric data that's accessed via integer indices.
Which of statements a), b) or c) is false? A variable name, such as x, is an identifier. Each identifier may consist of letters, digits and underscores (_) but may not begin with a digit. Python is case insensitive, so number and Number are the same identifier despite the fact that one begins with a lowercase letter and the other begins with an uppercase letter. All of the above statements are true.
Python is case insensitive, so number and Number are the same identifier despite the fact that one begins with a lowercase letter and the other begins with an uppercase letter.
When using IPython in interactive mode to evaluate a simple arithmetic expression in a new session, which of the following is false? The text "In [1]:" is a prompt, indicating that IPython is waiting for your input. You can type ? for help or you can begin entering snippets After you type an expression like 45 + 72 and press Enter, IPython reads the snippet, evaluates it and prints its result in Out[1]:. Then IPython displays the In [2] prompt to show that it's waiting for you to enter your second snippet Python uses x for multiplication and the forward slash (/) for division.
Python uses x for multiplication and the forward slash (/) for division.
Which of the following statements about libraries is false? Using existing libraries helps you avoid "reinventing the wheel," thus leveraging your program-development efforts. Rather than developing lots of original code—a costly and time-consuming process—you can simply create an object of a pre-existing library class, which takes only three Python statements. Libraries help you perform significant tasks with modest amounts of code. All of the above statements are false.
Rather than developing lots of original code—a costly and time-consuming process—you can simply create an object of a pre-existing library class, which takes only three Python statements.
Which of the following statements is false? You can determine the number of items in a set with the built-in len function. Sets are not iterable, so you cannot process each set element with a for loop. You can check whether a set contains a particular value using the in and not in operators. Sets are unordered, so there's no significance to the iteration order.
Sets are not iterable, so you cannot process each set element with a for loop
Which of the following statements is false? True division (/) divides a numerator by a denominator and yields a floating-point number with a decimal point. Floor division (//) divides a numerator by a denominator, yielding the highest integer that's not greater than the result. Python truncates (discards) the fractional part. The expression -13 / 4 evaluates to -3.25. The expression -13 // 4 evaluates to -3.
The expression -13 // 4 evaluates to -3.
Which of the following statements is false? Each function should perform a single, well-defined task. The following code calls function square twice. The first call produces the int value 49 and the second call produces the int value 0: In [1]: def square(number):...: """Calculate the square of a number.""" ...: return number ** 2 ...:In [2]: square(7)Out[2]: 49In [3]: square(.1)Out[3]: 0 The statements defining a function arewritten only once, but may be called "to do their job" from many points in a program and as often as you like. Calling square with a non-numeric argument like 'hello' causes a TypeError because the exponentiation operator (**) works only with numeric values.
The following code calls function square twice. The first call produces the int value 49 and the second call produces the int value 0: In [1]: def square(number):...: """Calculate the square of a number.""" ...: return number ** 2 ...:In [2]: square(7)Out[2]: 49In [3]: square(.1)Out[3]: 0
Which of the following statements is false? The while statement allows you to repeat one or more actions while a condition remains True. Such a statement often is called a loop. The following code finds the first power of 3 larger than 50: product = 3while product < 50:product = product * 3 Something in a while statement's suite must ensure that the condition eventually becomes False. Otherwise, a logic error called an infinite loop occurs. In applications executed from a Terminal, Command Prompt or shell, type Ctrl + c or control + c (depending on your keyboard) to terminate an infinite loop.
The following code finds the first power of 3 larger than 50: product = 3while product < 50:product = product * 3
Which of the following statements about DataFrames is false? The index can be a slice. In the following slice containing, the range specified includes the high index ('Test3'): grades.loc['Test1':'Test3'] When using slices containing integer indices with iloc, the range you specify excludes the high index (2): grades.iloc[0:2] To select specific rows, use a tuple rather than slice notation with loc or iloc. All of the above statements are true.
To select specific rows, use a tuple rather than slice notation with loc or iloc.
Which of the following statements is false? The descriptive statistics mean, median and mode are measures of central tendency—each is a way of producing a single value that is in some sense typical of the others. The following session creates a list called grades, then uses the built-in sum and len functions to calculate the median "by hand"—sum calculates the total of the grades (397) and len returns the number of grades (5): In [1]: grades = [85, 93, 45, 89, 85] In [2]: sum(grades) / len(grades) Out[2]: 79.4 Like functions min and max, sum and len are both examples of functional-style programming reductions—they reduce a collection of values to a single value. The Python Standard Library's statistics module provides functions for calculating the mean, median and mode—these, too, are reductions.
The following session creates a list called grades, then uses the built-in sum and len functions to calculate the median "by hand"—sum calculates the total of the grades (397) and len returns the number of grades (5): In [1]: grades = [85, 93, 45, 89, 85] In [2]: sum(grades) / len(grades) Out[2]: 79.4
Which of the following statements is false. You can import all identifiers defined in a module with a wildcard import of the form from modulename import * A wildcard import makes all of the module's identifiers available for use in your code. The following session is an example of safe use of a wildcard import: In [1]: e = 'hello'In [2]: from math import *In [3]: eOut[3]: 2.718281828459045 Importing a module's identifiers with a wildcard import can lead to subtle errors—it's considered a dangerous practice that you should avoid.
The following session is an example of safe use of a wildcard import: In [1]: e = 'hello'In [2]: from math import *In [3]: eOut[3]: 2.718281828459045
Which of the following statements is false? Function range's one-argument version produces a sequence of consecutive integers from 0 up to, but not including, the argument's value. The following snippet produces the sequence 5 6 7 8 9. for number in range(5, 10):print(number, end=' ') The following snippet produces the sequence 0 2 4 6 8. for number in range(0, 10, 2):print(number, end=' ') The following snippet produces the sequence 10 8 6 4 2 0. for number in range(10, 0, -2):print(number, end=' ')
The following snippet produces the sequence 10 8 6 4 2 0. for number in range(10, 0, -2):print(number, end=' ')
In the following code segment: # process 10 students for student in range(10): # get one exam result result = int(input('Enter result (1=pass, 2=fail): ')) if result == 1: passes = passes + 1 else: failures = failures + 1 The if statement is nested in the for statement. The if statement follows the for statement in sequence. The for statement is nested in the if statement. None of the above.
The if statement is nested in the for statement.
Which of the following statements is false? Augmented assignments abbreviate assignment expressions in which the same variable name appears on the left and right of the assignment's =, as total does in: for number in [1, 2, 3, 4, 5]:total = total + number The following code re-implements the preceding for statement using an addition augmented assignment (+=) statement: for number in [1, 2, 3, 4, 5]:total += number The statement f = f ** 3 may be replaced by the more concise augmented assignment statement f *= 3. All of the above statements are true.
The statement f = f ** 3 may be replaced by the more concise augmented assignment statement f *= 3.
Consider a Series of hardware-related strings: hardware = pd.Series(['Hammer', 'Saw', 'Wrench']) The following code uses the Series str attribute to invoke string method upper on every Series element, producing a new Series containing the uppercase versions of each element in hardware: hardware.str.upper()
True
Which of the following statements is false?Python requires you to indent the statements in suites. Incorrect indentation of the statements in a suite can cause errors. Using the assignment symbol (=) instead of the equality operator (==) in an if statement's condition is a common logic error. Using == in place of = in an assignment statement can lead to subtle problems.
Using the assignment symbol (=) instead of the equality operator (==) in an if statement's condition is a common logic error.
Which of the following statements is false? When you evaluate expressions in interactive mode, the text that print displays is preceded by Out[] with a snippet number in the square brackets. print does not display a string's quotes, though there is a way to display quotes in strings. You also may enclose a string in double quotes ("), as in: print("Welcome to Python!") but Python programmers generally prefer single quotes. When print completes its task, it positions the screen cursor at the beginning of the next line.
When you evaluate expressions in interactive mode, the text that print displays is preceded by Out[] with a snippet number in the square brackets.
List comprehensions can replace many for statements that iterate over existing sequences and create new lists, such as: list1 = [] for item in range(1, 6): Write the statement that can accomplish the same task in a single line of code with a list comprehension:
[item for item in range(1, 6)]
The following code creates the dictionary roman_numerals, which maps roman numerals to their integer equivalents (the value for 'X' is intentionally wrong): roman_numerals = {'I': 1, 'II': 2, 'III': 3, 'V': 5, 'X': 100} Replacing the value associated with the key 'X' with a new value 10, can be done by the following statement: In [1]: roman_numerals['X'] = 10
true
The following code produces different values are likely to be displayed each time you run the code: import randomfor roll in range(10):print(random.randrange(1, 6), end=' ')
true
The following code, which has a dictionary with unique values, reverses the key-value pairs: months = {'January': 1, 'February': 2, 'March': 3} months2 = {number: name for name, number in months.items()}
true
The following update call receives a dictionary key-value pair to insert or update: country_codes.update({'Australia': 'ar'}) Provided an incorrect country code for Australia. The following code corrects this by using a keyword argument to update the value associated with 'Australia': country_codes.update(Australia='au')
true
The following statements replaced the results of the four list comparisons below with blank. What are those output values for Out [4], Out [5], Out[6] and Out[7]. Type your answers for each output respectively. In [1]: a = [1, 2, 3] In [2]: b = [1, 2, 3] In [3]: c = [1, 2, 3, 4] In [4]: a == b Out[4]: In [5]: a == c Out[5]: In [6]: a < c Out[6]: In [7]: c >= b Out[7]:
true false true true
Two sets are disjoint if they do not have any common elements. You can determine this with the set type's isdisjoint method. What values are actually displayed for ??? in Out[1] and Out[2]: In [1]: {1, 3, 5}.isdisjoint({2, 4, 6})Out[1]: ??? In [2]: {1, 3, 5}.isdisjoint({4, 6, 1})Out[2]: ???
true, false
The following lists contain names and the grade point average of that name respectively: names = ['Bob', 'Sue', 'Amanda'] grade_point_averages = [3.5, 4.0, 3.75] Write the zip call statement that produces the tuples ('Bob', 3.5), ('Sue', 4.0) and ('Amanda', 3.75) consisting of the elements at index 0, 1 and 2 of each list, respectively:
zip(names, grade_point_averages)
Which of the following would be displayed for ??? by Out[3]? In [1]: numbers = list(range(10)) + list(range(5)) In [2]: numbers Out[2]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4] In [3]: set(numbers) Out[3]: ???
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}