python final exam

Ace your homework & exams now with Quizwiz!

Which of the following statements a), b) or c) is false? A dictionary's keys must be mutable (such as strings, numbers or tuples) and unique (that is, no duplicates). A dictionary associates keys with values. Each key maps to a specific value. Multiple keys can have the same value, such as two different inventory codes that have the same quantity in stock. All of the above statements are true.

A dictionary's keys must be mutable (such as strings, numbers or tuples) and unique (that is, no duplicates).

Which of the following statements a), b) or c) is false? The following code creates a student_tuple with a first name, last name and list of grades:student_tuple = ('Amanda', 'Blue', [98, 75, 87]) Even though the tuple in Part (a) is immutable, its list element is mutable. In the expression student_tuple[2][1], Python views student_tuple[2] as the element of the tuple containing the list [98,75,87], then uses [1] to access the list element containing 75. All of the above statements are true.

All of the above statements are true.

Which of the following statements a), b) or c) is false? All of the above statements are true. You can access a global variable's value inside a function. By default, you cannot modify a global variable in a function-when you first assign a value to a variable in a function's block, Python creates a new local variable. To modify a global variable in a function's block, you must use a global statement to declare that the variable is defined in the global scope.

All of the above statements are true.

Which of the following statements a), b) or c) is false? The array function copies its argument's dimensions and creates a new array. NumPy auto-formats arrays, based on their number of dimensions, aligning the columns within each row. The following creates an array from a two-row-by-three-column list:np.array([[1, 2, 3], [4, 5, 6]]) All of the above statements are true.

All of the above statements are true.

Which of the following statements a), b) or c) is false? 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} The following code gets the value associated with the key 'V' in Part (a):roman_numerals['V'] You can update a key's associated value in an assignment statement. The following code replaces the incorrect value associated with the key 'X' in Part (a):roman_numerals['X'] = 10 All of the above statements are true.

All of the above statements are true.

Which of the following statements a), b) or c) is false? The following code makes numbers2 a slice that views only the first three elements of numbers:import numpy as npnumbers = np.arange(1, 6)numbers2 = numbers[0:3] After the statement in Part (a) executes, numbers and numbers2 are different objects. After the statement in Part (a) executes, modifying an element in numbers2 also modifies the corresponding element in numbers. All of the above statements are true.

All of the above statements are true.

Which of the following statements a), b) or c) is false? The preferred mechanism for accessing an element's index and value is the built-in function enumerate, which receives an iterable and creates an iterator that, for each element, returns a tuple containing the element's index and value. The following for loop unpacks each tuple returned by enumerate into the variables index and value and displays them:for index, value in enumerate(colors):​print(f'{index}: {value}') The following code uses the built-in function list to create a list of tuples containing enumerate's results:colors = ['red', 'orange', 'yellow']colors_list = list(enumerate(colors)) All of the above statements are true.

All of the above statements are true.

Which of the following statements a), b) or c) is false? By default, %timeit executes a statement in a loop, and it runs the loop seven times. The following code uses the random module's randrange function with a list comprehension to create a list of six million die rolls and time the operation using %timeit:import random%timeit rolls_list = \​[random.randrange(1, 7) for i in range(0, 6_000_000)] After executing the statement, %timeit displays the statement's average execution time, as well as the standard deviation of all the executions. All of the above statements are true.

All of the above statements are true.

Which of the following statements a), b) or c) is false? NumPy provides functions zeros, ones and full for creating arrays containing 0s, 1s or a specified value, respectively. The array returned by NumPy function full contains elements with the second argument's value and type. The first argument to the functions in Part (a) must be an integer or a tuple of integers specifying the desired dimensions. For an integer, each function returns a one-dimensional array with the specified number of elements. For a tuple of integers, these functions return a multidimensional array with the specified dimensions.

All of the above statements are true.

Which of the following statements a), b) or c) is false? The following call to dictionary method update receives a dictionary containing one key—value pair to insert or update:country_codes.update({'South Africa': 'za'}) Method update can convert keyword arguments into key—value pairs to insert. The following call converts the parameter name Australia into the string key 'Australia' and associates the incorrect value 'ar' with that key:country_codes.update(Australia='ar') The snippet in Part (b) provided an incorrect country code ('ar') for Australia. The following code corrects this by using a keyword argument to update the value associated with'Australia':country_codes.update(Australia='au') All of the above statements are true.

All of the above statements are true.

Which of the following statements a), b) or c) is false? Displaying animation frames to the screen is relatively fast compared to the die rolls, which occur at the computer's CPU speeds. For each animation frame, a Matplotlib FuncAnimation calls a function that you define to specify how to change the plot. If we roll only one die per animation frame, we won't be able to run a large number of rolls in a reasonable amount of time. You can increase the execution speed of the simulation by rolling the die more times per animation frame. All of the above statements are true.

Displaying animation frames to the screen is relatively fast compared to the die rolls, which occur at the computer's CPU speeds.

Which of the following statements is false? The built-in function any returns True if any item in its iterable argument is True. Non-empty iterable objects also evaluate to True, whereas any empty iterable evaluates to False. Functions any and all are examples of external iteration in functional-style programming. The built-in function all returns True if all items in its iterable argument are True.

Functions any and all are examples of external iteration in functional-style programming.

Which of the following statements a), b) or c) is false? If the values in Part (b) were not unique, then the code would generate a ValueError. The following code, which has a dictionary with unique values, reverses the key—value pairs, so the values become the keys and vice versa:months = {'January': 1, 'February': 2, 'March': 3}months2 = {number: name for name, number in months.items()} Dictionary comprehensions provide a convenient notation for quickly generating dictionaries, often by mapping one dictionary to another. All of the above statements are true.

If the values in Part (b) were not unique, then the code would generate a ValueError.

Which of the following statements a), b) or c) is false? In the following dictionary, the keys are lists of three integer student grades and the values are strings representing the students' names.grade_book = { ​'Susan': [92, 85, 100], ​'Eduardo': [83, 95, 79], ​'Azizi': [91, 89, 82], ​'Pantipa': [97, 91, 92] } The comparison operators == and != can be used to determine whether two dictionaries have identical or different contents. An equals (==) comparison evaluates to True if both dictionaries have the same key—value pairs, regardless of the order in which those pairs were added to each dictionary. All of the above statements are true.

In the following dictionary, the keys are lists of three integer student grades and the values are strings representing the students' names.grade_book = { ​'Susan': [92, 85, 100], ​'Eduardo': [83, 95, 79], ​'Azizi': [91, 89, 82], ​'Pantipa': [97, 91, 92] }

Which of the following statements is false? Concatenating the tuple (40, 50) to tuple1 from Part (b), as intuple1 += (40, 50)creates a new tuple, then assigns a reference to it to the variable tuple1-tuple2 still refers to the original tuple. In the following snippets, after the two assignments, tuple1 and tuple2 are two different copies of the same tuple object:In [1]: tuple1 = (10, 20, 30)In [2]: tuple2 = tuple1In [3]: tuple2Out[3]: (10, 20, 30) The += augmented assignment statement can be used with strings and tuples, even though they're immutable. For a string or tuple, the item to the right of += must be a string or tuple, respectively-mixing types causes a TypeError.

In the following snippets, after the two assignments, tuple1 and tuple2 are two different copies of the same tuple object:In [1]: tuple1 = (10, 20, 30)In [2]: tuple2 = tuple1In [3]: tuple2Out[3]: (10, 20, 30)

Which of the following statements a), b) or c) is false? Other mutable set methods are intersection augmented assignment &=, difference augmented assignment -= and symmetric difference augmented assignment ^=. Their corresponding methods with iterable arguments are intersection_update, difference_update and symmetric_difference_update. Like operator |, union augmented assignment |= performs a set union operation, but |= doesn't modify its left operand. The set type's update method performs a union operation modifying the set on which it's called-the argument can be any iterable. All of the above statements are true.

Like operator |, union augmented assignment |= performs a set union operation, but |= doesn't modify its left operand.

Which of the following statements a), b) or c) is false? The following list comprehension uses the expression item**3 to map each value in a range to the value's cube:list3 = [item ** 3 for item in range(1, 6)] A list comprehension's expression can perform tasks, such as calculations, that map elements to new values (possibly of different types). Mapping is a common functional-style programming operation that produces a result with more elements than the original data being mapped. All of the above statements are true.

Mapping is a common functional-style programming operation that produces a result with more elements than the original data being mapped.

Which of the following statements A), B) and C) is false? The following for statement iterates through dictionary days_per_month's key—value pairs. Dictionary method items returns each key—value pair as a tuple, which is unpacked into the target variables month and days:for month, days in days_per_month.items():​print(f'{month} has {days} days') The following dictionary maps month-name strings to int values representing the numbers of days in the corresponding month:days_per_month = {'January': 31, 'February': 28, 'March': 31} Multiple keys in a dictionary can have the same value. All of the above statements are true.

Multiple keys in a dictionary can have the same value.

Which of the following statements is false? Many calculation methods can be performed on specific array dimensions, known as the array's axes. These methods receive an axis keyword argument that specifies which dimension to use in the calculation, giving you a quick way to perform calculations by row or column in a two-dimensional array. Assume that you want to calculate the average grade on each exam, represented by the columns of grades. Specifying axis=0 performs the calculation on all the row values within each column. Similarly, specifying axis=1 performs the calculation on all the column values within each individual row. 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) NumPy does not display trailing 0s to the right of the decimal point. Also, it does not display all element values in the same field width.

NumPy does not display trailing 0s to the right of the decimal point. Also, it does not display all element values in the same field width.

Which of the following statements a), b) or c) is false? Assigning a value to a nonexistent key could be a logic error. Assigning a value to a nonexistent key inserts the key—value pair in the dictionary. String keys are case insensitive. All of the above statements are true.

String keys are case insensitive.

Which of the following statements is false? T returns a transposed copy of the DataFrame. Assuming the following grades DataFrame: ​WallyEvaSamKatieBob Test1871009410083 Test29687778165 Test37090908285 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() To see the average of all the students' grades on each test, call mean on the T attribute:grades.T.mean() You can quickly transpose a DataFrame's rows and columns-so the rows become the columns, and the columns become the rows-by using the T attribute.

T returns a transposed copy of the DataFrame.

Which of the following statements is false? Series provides many methods for common tasks including producing various descriptive statistics, like count, mean, min, max, etc. Calling Series method describe produces all the Part (a) descriptive stats and more. Each of the descriptive statistics in Part (a) is a functional-style reduction. The 25%, 50% and 75% statistics produced by Series method describe are quartiles: 50% represents the median of the sorted values, 25% represents the median of every second one of the sorted values and 75% represents the median of every fourth one of the sorted values.

The 25%, 50% and 75% statistics produced by Series method describe are quartiles: 50% represents the median of the sorted values, 25% represents the median of every second one of the sorted values and 75% represents the median of every fourth one of the sorted values.

Which of the following statements is false? The argument to issubset or issuperset must be a set. You also can check for an improper subset with the set method issubset. You can check for an improper superset with the set method issuperset. The <= operator tests whether the set to its left is an improper subset of the one to its right-that is, all the elements in the left operand are in the right operand, and the sets might be equal.

The argument to issubset or issuperset must be a set.

Which of the following statements is false? When you assign a new object to a variable the original object that the variable referenced will be garbage collected if no other variables refer to it. The following code deletes only the first three elements of numbers by assigning an empty list to the three-element slice:numbers[0:3] = [] The following code assigns a list's elements to a slice of every other element of numbers:numbers = [2, 3, 5, 7, 11, 13, 17, 19]numbers[2:2:2] = [100, 100, 100, 100] The following code deletes all the elements in numbers, leaving the existing list empty:numbers[:] = []

The following code assigns a list's elements to a slice of every other element of numbers:numbers = [2, 3, 5, 7, 11, 13, 17, 19]numbers[2:2:2] = [100, 100, 100, 100]

Which of the following statements is false? The following code calls function square twice. We've replaced each of the output values with ???. The first call produces the int value 49 and the second call produces the int value 6:In [1]: def square(number): ​...: """Calculate the square of number.""" ​...: return number ** 2 ​...: In [2]: square(7)Out[2]: ???In [3]: square(2.5)Out[3]: ??? The statements defining a function are written only once, but may be called "to do their job" from many points in a program and as often as you like. Each function should perform a single, well-defined task. 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. We've replaced each of the output values with ???. The first call produces the int value 49 and the second call produces the int value 6:In [1]: def square(number): ​...: """Calculate the square of number.""" ​...: return number ** 2 ​...: In [2]: square(7)Out[2]: ???In [3]: square(2.5)Out[3]: ???

Which of the following statements is false? Slice operations can modify mutable sequences. Slice operations that do not modify a sequence work identically for lists, tuples and strings. The following code creates a slice consisting of the elements at indices 2 through 6 of the list numbers:numbers = [2, 3, 5, 7, 11, 13, 17, 19]numbers2 = numbers[2:6] You can slice sequences to create new sequences of the same type containing subsets of the original elements. When taking a slice of a list, the original list is not modified.

The following code creates a slice consisting of the elements at indices 2 through 6 of the list numbers:numbers = [2, 3, 5, 7, 11, 13, 17, 19]numbers2 = numbers[2:6]

Assume the array numbers contains the values 10, 20, 30, 40, 50, 60. Which of the following statements is false? The following code uses the multiply universal function to multiply every element of numbers by the scalar value 5:import numpy as npnp.multiply(numbers, 5) If a universal function receives two arrays of different shapes that do not support broadcasting, a ValueError occurs. The following code reshapes numbers into a 2-by-3 array, then multiplies its values by a one-dimensional array of three elements:numbers2 = numbers.reshape(2, 3)numbers3 = np.array([2, 4, 6])np.multiply(numbers2, numbers3)The preceding code works because numbers3 has the same length as each column of numbers2. The following code uses the multiply universal function to multiply every element of numbers by the scalar value 5:numbers * 5

The following code reshapes numbers into a 2-by-3 array, then multiplies its values by a one-dimensional array of three elements:numbers2 = numbers.reshape(2, 3)numbers3 = np.array([2, 4, 6])np.multiply(numbers2, numbers3)The preceding code works because numbers3 has the same length as each column of numbers2.

Which of the following statements is false? The following uses a step in the slice to delete every other element from the entire list:del numbers[::2] The following code creates a list, then uses del to remove its last element:numbers = list(range(0, 10))del numbers[1] You can use del with a list to remove the element at any valid index or the element(s) from any valid slice. The following deletes the list's first two elements:del numbers[0:2]

The following deletes the list's first two elements:del numbers[0:2]

Which of the following statements is false? When you output a tuple, Python always displays its contents in parentheses. You can pack a tuple by separating its values with commas. The following statement creates a one-element tuple:a_singleton_tuple = ('red') You may surround a tuple's comma-separated list of values with optional parentheses.

The following statement creates a one-element tuple:a_singleton_tuple = ('red')

Which of the following statements a), b) or c) is false? The more die rolls we attempt, the closer each die value's percentage of the total rolls gets to 16.667%. This is a manifestation of Moore's Law. For six-sided die rolls, each value 1 through 6 should occur about one-sixth of the time, so the probability of any one of these values occurring is 1/6th or about 16.667%. If the random module's randrange function indeed produces integers at random, then every number in the specified range has an equal probability (or likelihood) of being chosen each time the function is called. All of the above statements are true.

The more die rolls we attempt, the closer each die value's percentage of the total rolls gets to 16.667%. This is a manifestation of Moore's Law.

Which of the following statements is false? The set methods may receive any iterable object as an argument. The operands of the binary set operators, like |, must both be any iterable. You can calculate the union with the | operator or with the set type's union method. The union of two sets is a set consisting of all the unique elements from both sets.

The operands of the binary set operators, like |, must both be any iterable.

Which of the following statements a), b) or c) is false? To sort a list in descending order, call list method sort with the optional keyword argument reverse=False. Built-in function sorted returns a new list containing the sorted elements of its argument sequence-the original sequence is unmodified. You can use list method sort as follows to arrange a list's elements in ascending order:numbers = [10, 3, 7, 1, 9, 4, 2, 8, 5, 6]numbers.sort() All of the above statements are true.

To sort a list in descending order, call list method sort with the optional keyword argument reverse=False.

We've replaced the results of the four list comparisons in snippets [4] through [7] below with ???. What are those four values?In [1]: a = [1, 2, 3]In [2]: b = [1, 2, 3]In [3]: c = [1, 2, 3, 4]In [4]: a == bOut[4]: ???In [5]: a == cOut[5]: ???In [6]: a < cOut[6]: ???In [7]: c >= bOut[7]: ???

True, False, True, True.

Which of the following statements is false? The function modify_elements multiplies each element of its list argument by 2:def modify_elements(items): ​""""Multiplies all element values in items by 2.""" ​for i in range(len(items)): ​items[i] *= 2 When you pass a tuple to a function, attempting to modify the tuple's immutable elements results in a TypeError. Tuples may contain mutable objects, such as lists, but those objects cannot be modified when a tuple is passed to a function. Part (a)'s function modify_elements' items parameter receives a reference to the original list, so the statement in the loop's suite modifies each element in the original list object.

Tuples may contain mutable objects, such as lists, but those objects cannot be modified when a tuple is passed to a function.

Which of the following statements is false? Tuples are immutable. Tuples must store heterogeneous data (that is, data of different types). A tuple's length cannot change during program execution. A tuple's length is its number of elements.

Tuples must store heterogeneous data (that is, data of different types).

The value 10.5 is a(n) ________ (that is, a number with a decimal point).

floating-point number

The popular programming languages Python and ________ are the two most widely used data-science languages.

R

________ is an informal English-like language for "thinking out" algorithms.

Pseudocode

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.

We use array method ________ to produce two-dimensional arrays from one-dimensional ranges.

reshape

Views are also known as ________ copies.

shallow

Which of the following statements is false? Arithmetic between arrays of integers and floating-point numbers results in an array of integers. You may perform arithmetic operations and augmented assignments between arrays of the same shape. You can compare arrays with individual values and with other arrays. Comparisons are performed element-wise. Such comparisons produce arrays of Boolean values in which each element's True or False value indicates the comparison result. The expression numbers >= 13 uses broadcasting to determine whether each element of numbers is greater than or equal to 13.

Arithmetic between arrays of integers and floating-point numbers results in an array of integers.

What does the int function attempt to do in the following code? value = input('Enter an integer: ')value = int(value) Convert a non-object to an object. Convert a string to an integer. Convert an integer to a string. None of the above.

Convert a string to an integer.

A pandas ________ is an enhanced two-dimensional array.

DataFrame

Lists may store ________ data, that is, data of many different types.

heterogeneous

What does the following for statement print? for counter in range(10): ​print(counter, end=' ') It doesn't run because it's syntactically incorrect. 0 1 2 3 4 5 6 7 8 9 10 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9

0 1 2 3 4 5 6 7 8 9

Which of the following statements a), b) or c) is false? The following code searches the list numbers for the value 5 starting from index 7 and continuing through the end of the list:numbers.index(5, 7) After the following snippet, the list numbers contains two copies of the original list's contents:numbers *= 2 You can use *= to multiply a sequence-that is, append a sequence to itself multiple times. All of the above statements are true.

All of the above statements are true.

Which of the following statements a), b) or c) is false? A generator expression does not create a list. A generator expression is similar to a list comprehension, but is enclosed in parentheses (rather than []) and creates an iterable generator object that produces values on demand. The generator expression in the following for statement squares and returns only the odd values in numbers:numbers = [10, 3, 7, 1, 9, 4, 2, 8, 5, 6]for value in (x ** 2 for x in numbers if x % 2 != 0): ​print(value, end=' ') All of the above statements are true.

All of the above statements are true.

Which of the following statements a), b) or c) is false? DataFrames can have custom row and column indices, and offer additional operations and capabilities that make them more convenient for many data-science oriented tasks. The Series representing each column may contain different element types. DataFrames support missing data. All of the above statements are true.

All of the above statements are true.

Which of the following statements a), b) or c) is false? The times displayed by %timeit on one system may vary from those shown on another. Most array operations execute significantly faster than corresponding list operations. With the IPython %timeit magic command, you can time the average duration of operations. All of the above statements are true.

All of the above statements are true.

Which of the following statements a), b) or c) is false? After the statement in Part (b) executes, numbers2 has a separate copy of the data in numbers. Assuming numbers is an array of integers, the following statement creates a deep copy of that array:import numpy as npnumbers = np.arange(1, 6)numbers2 = numbers.copy() The array method copy returns a new array object with a deep copy of the original array object's data. All of the above statements are true.

All of the above statements are true.

Which of the following statements a), b) or c) is false? The following code unpacks a sequence produced by range:number1, number2, number3 = range(3) A ValueError occurs if the number of variables to the left of the assignment symbol is not identical to the number of elements in the sequence on the right. You can unpack any sequence's elements by assigning the sequence to a comma-separated list of variables. All of the above statements are true.

All of the above statements are true.

Which of the following statements is false? Collections are prepackaged data structures consisting of related data items. Tuples can dynamically resize as necessary, growing and shrinking at execution time. Lists are modifiable and tuples are not. Each can hold items of the same or different types. Examples of collections include your favorite songs on your smartphone, your contacts list, a library's books, your cards in a card game, your favorite sports team's players, the stocks in an investment portfolio, patients in a cancer study and a shopping list.

Tuples can dynamically resize as necessary, growing and shrinking at execution time.

Which of the following statements about AI is false:

For many decades, AI has been a field with solutions and no problems.

Which of the following statements is false? After deleting numbers from the interactive session, attempting to display it displays an empty list. The following code deletes the variable numbers from the interactive session:del numbers The following code deletes all of the list's elements:del numbers[:] The del statement can delete any variable.

After deleting numbers from the interactive session, attempting to display it displays an empty list.

Assuming the following array grades:import numpy as npgrades = np.array([[87, 96, 70], [100, 87, 90], ​[94, 77, 90], [100, 81, 82]]) Which of the following statements a), b) or c) is false? To select a single row, specify only one index in square brackets, as ingrades[1] The following code selects an element in grades by specifying a tuple containing the element's row and column indices in square brackets:grades[0, 1] To select multiple sequential rows, use slice notation, as ingrades[0:2]and to select multiple non-sequential rows, use a list of row indices, as ingrades[[1, 3]] All of the above statements are true.

All of the above statements are true.

Which of the following statements is false? The following code uses built-in function filter to obtain the odd values in numbers:numbers = [10, 3, 7, 1, 9, 4, 2, 8, 5, 6]def is_odd(x): ​"""Returns True only if x is odd.""" ​return x % 2 != 0 list(filter(is_odd, numbers)) Function filter returns an iterator, so filter's results are produced immediately. Python functions are objects that you can assign to variables, pass to other functions and return from functions. Function filter's first argument must be a function that receives one argument and returns True if the value should be included in the result.

Function filter returns an iterator, so filter's results are produced immediately.

Which of the following statements is false? The following code uses built-in function map with a lambda to square each value in numbers:list(map(lambda x: x ** 2, numbers)) Function map's first argument is a function that receives one value and returns a new value-in Part (a), a lambda that squares its argument. Function map's second argument is an iterable of values to map. The equivalent list comprehension to Part (a) is:[item ** 2 for item in numbers] Function map uses eager evaluation.

Function map uses eager evaluation.

Which of the following statements a), b) or c) is false? It is easier to display a list than a Series in a nice two-column format. After listing the Series elements, pandas shows the data type (dtype) of the underlying array's elements. Pandas displays a Series in two-column format with the indexes left aligned in the left column and the values right aligned in the right column. All of the above statements are true.

It is easier to display a list than a Series in a nice two-column format.

Which of the following statements a), b) or c) is false? Like arrays, Series use only zero-based integer indexes. Series may have missing data, and many Series operations ignore missing data by default. NumPy arrays use only zero-based integer indexes. All of the above statements are true.

Like arrays, Series use only zero-based integer indexes.

Which of the following statements is false? In IPython interactive mode, the line that begins with ----> shows the code that caused the exception. Python reports an exception with a traceback. Most exception names end with Exception. Dividing by zero with / or // is not allowed and results in an exception-an indication that a problem occurred.

Most exception names end with Exception.

Which of the following statements is true with respect to displaying an array of 1000 items or more? NumPy always drops only the middle rows from the output. NumPy drops the middle rows, middle columns or both from the output. NumPy always drops only the middle columns from the output. NumPy always drops the middle rows and middle columns from the output.

NumPy drops the middle rows, middle columns or both from the output.

Which of the following statements is false? You also can create custom reductions using the functools module's reduce function. The built-in functions len, sum, min and max perform reductions. Reductions process a sequence's elements into a small number of values. In the worlds of big data and Hadoop, MapReduce programming is based on the filter, map and reduce operations in functional-style programming.

Reductions process a sequence's elements into a small number of values.

Which of the following statements is false? Set method add inserts its argument if the argument is not already in the set; otherwise, the set remains unchanged. You can remove the first element of a set with pop. Set method remove removes its argument from a set. A KeyError occurs if the value is not in the set. Method discard also removes its argument from a set but does not cause an exception if the value is not in the set.

Set method remove removes its argument from a set. A KeyError occurs if the value is not in the set.

Which of the following statements a), b) or c) is false? The Matplotlib visualization library is built over the Seaborn visualization library and simplifies many Seaborn operations. Visualizations help you "get to know" your data. Visualizations give you a powerful way to understand data that goes beyond simply looking at raw data. All of the above statements are true.

The Matplotlib visualization library is built over the Seaborn visualization library and simplifies many Seaborn operations.

Which of the following statements is false? Usually, you iterate over a tuple's elements. Assigning a value to a tuple element causes a TypeError. Like list indices, tuple indices start at 0. The following snippets create a time_tuple representing an hour, minute and second, display the tuple, then use its elements to calculate the number of seconds since midnight:In [1]: time_tuple = (9, 16, 1)In [2]: time_tupleOut[2]: (9, 16, 1)In [3]: time_tuple[0] * 3600 + time_tuple[1] * 60 + time_tuple[2]Out[3]: 33361

Usually, you iterate over a tuple's elements.

Consider a two-dimensional list with three rows and four columns (i.e., a 3-by-4 list) that might represent the grades of three students who each took four exams in a course:a = [[77, 68, 86, 73], [96, 87, 89, 81], [70, 90, 86, 81]]Which of the following statements a), b) or c) is false? Writing the list as follows makes its row and column tabular structure clearer: a =[77, 68, 86, 73], # first student's grades ​96, 87, 89, 81], # second student's grades ​[70, 90, 86, 81] # third student's grades The following nested for statement outputs the rows of the two-dimensional list a one row at a time:for row in a: ​for item in row: ​print(item, end=' ') ​print() The element names in the last column all have 3 as the second index. All of the above statements are true.

Writing the list as follows makes its row and column tabular structure clearer: a =[77, 68, 86, 73], # first student's grades ​96, 87, 89, 81], # second student's grades ​[70, 90, 86, 81] # third student's grades

Which of the following statements a), b) or c) is false? Transposing does not modify the original array. If a grades array represents two students' grades (the rows) on three exams (the columns), the following code transposes the rows and columns to view the data as the grades on three exams (the rows) for two students (the columns):grades.T You can quickly transpose an array's rows and columns-that is "flip" the array, so the rows become the columns and the columns become the rows. The T attribute returns a transposed deep copy of the array. All of the above statements are true.

You can quickly transpose an array's rows and columns-that is "flip" the array, so the rows become the columns and the columns become the rows. The T attribute returns a transposed deep copy of the array.

Which of the following statements is false? You push using list method append, which adds a new element to the end of the list. You pop using list method pop with no arguments, which removes and returns the item at the front of the list. You can run out of memory if you keep pushing items faster than you pop them. Python does not have a built-in stack type, but you can think of a stack as a constrained list.

You pop using list method pop with no arguments, which removes and returns the item at the front of the list.

If you need ________ copies of other types of Python objects, pass them to the ________ module's ________ function. shallow, copy, copy shallow, shallowcopy, copy deep, copy, deepcopy deep, deepcopy, copy

deep, copy, deepcopy

The interquartile range is the 75% quartile minus the 25% quartile, which is another measure of ________, like standard deviation and variance.

dispersion

The NumPy array function receives as an argument an array or other collection of elements and returns a new array containing the argument's elements. Based on the statement:import numpy as npnumbers = np.array([2, 3, 5, 7, 11])what type will be output by the following statement?type(numbers)

numpy.ndarray

Information on secondary storage devices is ________ - it's preserved even when the computer's power is turned off.

persistent

Which Python Standard Library module do we use for performance analysis?

timeit

Consider the following session:In [1]: numbers = list(range(10)) + list(range(5))In [2]: numbersOut[2]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4]In [3]: set(numbers)Out[3]: ???Which of the following would be displayed where we wrote ??? in Out[3]? (0, 1, 2, 3, 4, 5, 6, 7, 8, 9) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] {[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]} {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

Which of the following statements is false?

Interpreter programs, developed to execute high-level language programs directly, avoid the delay of compilation, and run faster than compiled programs.

Which of the following statements is false? Python calls end a keyword argument, and end is a Python keyword. The end keyword argument is optional. If you do not include it, print uses a newline ('\n') by default. Built-in function print displays its argument(s), then moves the cursor to the next line. You can change this behavior with the argument end, as inprint(character, end=' ') Keyword arguments are sometimes called named arguments.

Keyword arguments are sometimes called named arguments.

Which of the following statements is false? A line that begins with the hash character (#) is a comment. The Style Guide for Python Code states that each script should start with a docstring that explains the script's purpose. Comments do not cause the computer to perform any action when the code executes. If a line has a comment on it, that comment must begin the line with a hash character (#).

If a line has a comment on it, that comment must begin the line with a hash character (#).

Which of the following statements a), b) or c) is false? The built-in max and min functions also can receive an iterable, such as a list but not a string. The built-in max and min functions know how to determine the largest and smallest of their two or more arguments, respectively. All of the above statements are true. Using built-in functions or functions from the Python Standard Library's modules rather than writing your own can reduce development time and increase program reliability, portability and performance.

The built-in max and min functions also can receive an iterable, such as a list but not a string.

Which of the following statements is false? The diamond flowchart symbol has three flowlines emerging from it. One flowline emerging from the diamond flowchart symbol indicates the direction to follow when the condition in the symbol is True. This points to the action (or group of actions) that should execute. Another flowline emerging from the diamond flowchart symbol indicates the direction to follow when the condition is False. This skips the action (or group of actions). The decision (diamond) symbol contains a condition that can be either True or False.

The diamond flowchart symbol has three flowlines emerging from it.

A(n) ________ is the smallest data item in a computer. It can have the value 0 or 1.

bit

The most important flowchart symbol is the ________, which indicates that a decision is to be made, such as in an if statement.

diamond

Which of the following statements about arithmetic operators is false?

Expressions containing an integer and a floating-point number are mixed-type expressions-these always produce an integer.

A program might call a bank-account object's deposit ________ to increase the account's balance.

method

What value is produced when Python evaluates the following expression?5 * (12.7 - 4) / 2

21.75

Which of the following statements a), b) or c) is false? 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. The following code creates an array containing the values from 1 through 20, then reshapes it into four rows by five columns:import numpy as npnp.arange(1, 21).reshape(4, 5) 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. All of the above statements 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.

Consider the list c:c = [-45, 6, 0, 72, 1543] Which of the following statements a), b) or c) is false? The length of c is 5. The names of c's elements are c[0], c[1], c[2], c[3] and c[4]. You reference a list element by writing the list's name followed by the element's index (that is, its position number) enclosed in square brackets. All of the above statements are true.

All of the above statements are true.

You may spread a lengthy statement over several lines with the ________ continuation character. Correct! \ ^ % @

\

Once Waze converts a spoken command to text, it must determine the correct action to perform, which requires:

natural language processing

The attribute ________ contains an array's number of dimensions and the attribute ________ contains a ________ specifying an array's dimensions: dim, size, tuple

ndim, shape, tuple

What values are actually displayed where we've inserted ??? 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

Objects that "see" the data in other objects, rather than having their own copies of the data are called ________ objects.

view

Python provides two iteration statements-________ and ________.

while, for

Which of the following statements a), b) or c) is false? Each identifier has a scope that determines where you can use it in your program. For that portion of the program, the identifier is said to be "in scope." A local variable's identifier has local scope. It's "in scope" only from its definition to the end of the program. It "goes out of scope" when the function returns to its caller. All of the above statements are true. A local variable can be used only inside the function that defines it.

A local variable's identifier has local scope. It's "in scope" only from its definition to the end of the program. It "goes out of scope" when the function returns to its caller.

Which of the following statements is false? The NumPy (Numerical Python) library is the preferred Python array implementation-it offers a high-performance, richly functional n-dimensional array type called ndarray, which you can refer to by its synonym, array. A strength of NumPy is "array-oriented programming," which uses functional-style programming with external iteration to make array manipulations concise and straightforward, eliminating the kinds of bugs that can occur with the internal iteration of explicitly programmed loops. Operations on arrays are up to two orders of magnitude faster than those on lists. Many popular data science libraries such as Pandas, SciPy (Scientific Python) and Keras (for deep learning) are built on or depend on NumPy.

A strength of NumPy is "array-oriented programming," which uses functional-style programming with external iteration to make array manipulations concise and straightforward, eliminating the kinds of bugs that can occur with the internal iteration of explicitly programmed loops.

Which of the following statements is false? The following code creates an array and a view of that array:import numpy as npnumbers = np.arange(1, 6)numbers2 = numbers.view() After the statements in Part (a) execute, numbers and numbers2 are the same object. If we modify an element in numbers2, numbers "sees" the updated data. If we modify an element in numbers, numbers2 "sees" the updated data.

After the statements in Part (a) execute, numbers and numbers2 are the same object.

Which of the following statements about NumPy's linspace function is false? The optional keyword argument num specifies the number of evenly spaced values to produce-this argument's default value is 50. You can produce evenly spaced floating-point ranges with linspace. The function's first two arguments specify the starting and ending values in the range, and the ending value is included in the array. All of the above statements are tru

All of the above statements are true

Assuming the following array grades:import numpy as npgrades = np.array([[87, 96, 70], [100, 87, 90], ​[94, 77, 90], [100, 81, 82]]) Which of the following statements about two-dimensional arrays is false? The following code selects only the elements in the first column:grades[:, 0] You can select consecutive columns using a slice, as ingrades[:, 1:3]or specific columns using a list of column indices, as ingrades[:, [0, 2]] All of the above statements are true.

All of the above statements are true.

Consider the list color_names:color_names = ['orange', 'yellow', 'green']Which of the following statements a), b) or c) is false? Method insert adds a new item at a specified index. The following inserts 'red' at index 0:color_names.insert(0, 'red') You can add a new item to the end of a list with method append. Lists also have methods that add and remove elements. All of the above statements are true.

All of the above statements are true.

Which of the following statements a), b) or c) is false? Element-wise operations are applied to every array element, so given an integer array named numbers, the expressionnumbers * 2multiplies every element by 2, and the expressionnumbers ** 3cubes every element. The expressions in Part (a) do not modify the array numbers. Augmented assignments modify every element in the right operand. All of the above statements are true.

All of the above statements are true.

Which of the following statements a), b) or c) is false? List elements can be accessed via their indices and the subscription operator ([]). A TypeError occurs if the + operator's operands are different sequence types-for example, concatenating a list and a tuple is an error. You can concatenate two lists, two tuples or two strings using the + operator. The result is a new sequence of the same type containing the left operand's elements followed by the right operand's elements. All of the above statements are true.

All of the above statements are true.

Which of the following statements a), b) or c) is false? The list comprehension's for clause in Part (b) iterates over the sequence produced by range(1, 6). For each item, the list comprehension evaluates the expression to the left of the for clause and places the expression's value (in this case, the item itself) in the new list. 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): ​list1.append(item) We can accomplish the same task in a single line of code with a list comprehension:list2 = [item for item in range(1, 6)] List comprehensions provide a concise and convenient notation for creating new lists. All of the above statements are true.

All of the above statements are true.

Which of the following statements a), b) or c) is false? When specifying the indexes, you must provide a one-dimensional collection that has the same number of elements as there are rows in the DataFrame; otherwise, a ValueError occurs. The following code uses the index attribute to change the DataFrame's indexes from sequential integers to labels:grades.index = ['Test1', 'Test2', 'Test3'] With DataFrames you can specify custom indexes with the index keyword argument when we create a DataFrames, as in:grades_dict = {'Wally': [87, 96, 70], 'Eva': [100, 87, 90], ​'Sam': [94, 77, 90], 'Katie': [100, 81, 82], ​'Bob': [83, 65, 85]} import pandas as pdpd.DataFrame(grades_dict, index=['Test1', 'Test2', 'Test3']) All of the above statements are true.

All of the above statements are true.

Which of the following statements a), b) or c) is false? All of the above statements are true. You also may call maximum with mixed types, such as ints and floats:In [5]: maximum(13.5, -3, 7)Out[5]: 13.5 The following session defines a maximum function that determines and returns the largest of three values-then calls the function three times with integers, floating-point numbers and strings, respectively.In [1]: def maximum(value1, value2, value3):​...:"""Return the maximum of three values."""​...:max_value = value1​...:if value2 > max_value:​...:max_value = value2​...:if value3 > max_value:​...:max_value = value3​...:return max_value​...:In [2]: maximum(12, 27, 36)Out[2]: 36In [3]: maximum(12.3, 45.6, 9.7)Out[3]: 45.6In [4]: maximum('yellow', 'red', 'orange')Out[4]: 'yellow' The call maximum(13.5, 'hello', 7) results in TypeError because strings and numbers cannot be compared to one another with the greater-than (>) operator.

All of the above statements are true.

Which of the following statements a), b) or c) is false? Breaking a string into words is known as tokenizing the string. The following code builds a dictionary to count the number of occurrences of each word in a string named text-the dictionary's keys will be the unique words, and its values will be integer counts of how many times each word appears in text:word_counts = {}for word in text.split():​if word in word_counts:​word_counts[word] += 1​else:​word_counts[word] = 1 Python automatically concatenates strings separated by whitespace in parentheses. All of the above statements are true.

All of the above statements are true.

Which of the following statements a), b) or c) is false? By default, a Series has integer indexes numbered sequentially from 0. The following code creates a Series of student grades from a list of integers:import pandas as pdgrades = pd.Series([87, 100, 94]) The Series argument in Part (b)'s code also may be a tuple, a dictionary, an array, another Series or a single value. All of the above statements are true.

All of the above statements are true.

Which of the following statements a), b) or c) is false? You can calculate the intersection with the & operator or with the set type's intersection method. You can calculate the difference with the - operator or with the a set's difference method. The difference between two sets is a set consisting of the elements in the left operand that are not in the right operand. All of the above statements are true.

All of the above statements are true.

Which of the following statements a), b) or c) is false? You can modify a list by assigning to a slice of it-the rest of the list is unchanged. The following code creates a new list in reverse order:numbers[::-1] You can use a negative step to select slices in reverse order. All of the above statements are true.

All of the above statements are true.

Which of the following statements a), b) or c) is false? You can take a multidimensional array and flatten it into a single dimension with the methods flatten and ravel. Modifying a flattened array does not modify the original array's data. Method flatten deep copies the original array's data. All of the above statements are true.

All of the above statements are true.

Which of the following statements about FuncAnimation is false? The FuncAnimation argument interval is the number of milliseconds between animation frames (the default is 200). The FuncAnimation argument fargs (short for "function arguments") is a tuple of other arguments to pass to the function you specify in FuncAnimation's second argument. FuncAnimation has two required arguments-the Figure object in which to display the animation, and a function to call once per animation frame. All of the above statements are true.

All of the above statements are true.

Which of the following statements about functional-style programming is false? With functional-style programming capabilities you can write code that is more concise, clearer and easier to debug (find and correct errors). Other reductions you'll see include the sum, average, variance and standard deviation of a collection of values. The min and max functions are examples of a functional-style programming concept called reduction. They reduce a collection of values to a single value. All reductions are built into Python-you cannot define custom reductions.

All reductions are built into Python-you cannot define custom reductions.

Which of the following statements about energy consumption is false?

Another enormous electricity consumer is the blockchain-based cryptocurrency Bitcoin-processing just one Bitcoin transaction uses approximately the same amount of energy as powering the average American home for a year.

Which of the following statements a), b) or c) is false? You can iterate through a multidimensional array as if it were one-dimensional by using its flat attribute. You'll generally manipulate arrays using concise functional-style programming techniques with internal iteration. Because arrays are iterable, you cannot use external iteration with them. All of the above statements are true.

Because arrays are iterable, you cannot use external iteration with them.

Which of the following statements a), b) or c) is false? Consider the following comparison:'Red' < 'orange'The letter 'R' "comes after" 'o' in the alphabet, so 'Red' is greater than 'orange' and the condition above is False. Built-in function ord returns the numerical value of a character. Sometimes you'll need to find the minimum and maximum of more complex objects, such as strings. All of the above statements are true.

Consider the following comparison:'Red' < 'orange'The letter 'R' "comes after" 'o' in the alphabet, so 'Red' is greater than 'orange' and the condition above is False.

Which of the following statements is false? 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. DataFrames have a describe method that calculates basic descriptive statistics for the data and returns them as a two-dimensional array. 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 a two-dimensional array.

Which of the following statements is false? Dictionaries, strings and sets are built-in non-sequence collections A set is an unordered collection of unique immutable elements. 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. Lists and tuples are built-in sequence collections.

Dictionaries, strings and sets are built-in non-sequence collections.

Which of the following statements is false? The following statement creates x and uses the assignment symbol (=) to give x a value.x = 7 Every statement stops at the end of the line in which it begins. Once x and y are created and assigned values, you can use the values in expressions like:x + y Variables store values for later use in your code.

Every statement stops at the end of the line in which it begins.

Which of the following statements is false?. To do filtering in a list comprehension, use the if clause.d The following list comprehension includes in list4 only the even values produced by the for clause:list4 = [item for item in range(1, 11) if item % 2 == 0] Filtering typically produces a list with more elements than the data being filtered. A common functional-style programming operation is filtering elements to select only those that match a condition.

Filtering typically produces a list with more elements than the data being filtered.

Which of the following statements is false? For 600 die rolls, we expect about 100 occurrences of each die face. As we run a die-rolling simulation for 60,000 die rolls, the bars will become much closer in size. At 6,000,000 die rolls, they'll appear to be exactly the same size. This is the "principal of least privilege" at work. The larger the number of die rolls, the closer the frequency percentages will be to the expected 16.667%. For 6,000,000 rolls, we expect about 1,000,000 of each face. Seaborn refers to the following type of graph as a bar plot:

For 600 die rolls, we expect about 100 occurrences of each die face. As we run a die-rolling simulation for 60,000 die rolls, the bars will become much closer in size. At 6,000,000 die rolls, they'll appear to be exactly the same size. This is the "principal of least privilege" at work.

Which of the following statements is false? For single-digit year values 1—9, the format specifier >2 displays a value followed by the space character, thus right aligning the years in the first column. The placeholder {year:>2} uses the format specifier >2 to indicate that year's value should be right aligned (>) in a field of width 2-the field width specifies the number of character positions to use when displaying the value. The format specifier 10.2f in the placeholder {amount:>10.2f} formats amount as a floating-point number (f) right aligned (>) in a field width of 10 with a decimal point and two digits to the right of the decimal point (.2). Formatting a column of amounts this way aligns their decimal points vertically, as is typical with monetary amounts. The following statement uses an f-string with two placeholders to format year and amount:print(f'{year:>2}{amount:>10.2f}')

For single-digit year values 1—9, the format specifier >2 displays a value followed by the space character, thus right aligning the years in the first column.

Assuming the following function definition, which of the following statements is false?def rectangle_area(length=2, width=3): ​"""Return a rectangle's area.""" ​return length * width For the following call, the interpreter passes the default parameter value 3 for the width as if you had called rectangle_area(3, 10):rectangle_area(10) Any parameters with default parameter values must appear in the parameter list to the right of parameters that do not have defaults. The following call to rectangle_area has arguments for both length and width, so IPython ignores the default parameter values:rectangle_area(10, 5) You specify a default parameter value by following a parameter's name with an = and a value.

For the following call, the interpreter passes the default parameter value 3 for the width as if you had called rectangle_area(3, 10):rectangle_area(10)

Which of the following statements a), b) or c) is false? You can specify custom indices for a Series with the index keyword argument when creating the Series, as inimport pandas as pdgrades = pd.Series([87, 100, 94], index=['Wally', 'Eva', 'Sam']) In Part (a), we used string indices, but you can use other immutable types, even including integers not beginning at 0 and nonconsecutive integers. If you initialize a Series with a dictionary, its values become the Series' indices, and its keys become the Series' element values. All of the above statements are true.

If you initialize a Series with a dictionary, its values become the Series' indices, and its keys become the Series' element values.

Which of the following statements a), b) or c) is false? All of the above statements are true. The following code shows two statements in the else suite of an if...else statement:grade = 49if grade >= 60:print('Passed')else:print('Failed')print('You must take this course again') In the code of Part (a), even if you do not indent the else suite's second print statement, it's still in the else's suite. So, the code runs correctly. In the code in Part (a), grade is less than 60, so both statements in the else's suite execute.

In the code of Part (a), even if you do not indent the else suite's second print statement, it's still in the else's suite. So, the code runs correctly.

Which of the following statements is false? List method count searches for its argument in a list and returns the number of times it is found. List method reverse reverses the contents of a list in place. List method copy returns a new list containing a shallow copy of the original list. List method remove deletes the first element with a specified value-a NameError occurs if remove's argument is not in the list.

List method remove deletes the first element with a specified value-a NameError occurs if remove's argument is not in the list.

Which of the following statements is false? The iterator is like a bookmark-it always knows where it is in the sequence, so it can return the next item when it's called upon to do so. Each sequence has an iterator. The for statement uses the iterator "behind the scenes" to get each consecutive item until there are no more to process. Lists are unordered and a list's items are mutable.

Lists are unordered and a list's items are mutable.

Which of the following statements is false An empty dictionary evaluates to False. You can use a dictionary as a condition to determine if it's empty-a non-empty dictionary evaluates to True. Method clean deletes the dictionary's key—value pairs: When you pass a dictionary to built-in function len, the function returns the number of key—value pairs in the dictionary.

Method clean deletes the dictionary's key—value pairs:

Which of the following statements a), b) or c) is false? Method reshape returns a deep copy of the original array with the new dimensions. It does not modify the original array. Method resize modifies the original array's shape. The array methods reshape and resize both enable you to change an array's dimensions. All of the above statements are true.

Method reshape returns a deep copy of the original array with the new dimensions. It does not modify the original array.

Which of the following statements a), b) or c) is false? Consider a Series of hardware-related strings:import pandas as pdhardware = 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() Pandas left-aligns string element values and the dtype for strings is object. 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. All of the above statements are true.

Pandas left-aligns string element values and the dtype for strings is object.

Which of the following statements is false? Sets are iterable, so they are sequences and they support indexing and slicing with square brackets, [] Dictionaries do not support slicing. Sets may contain only immutable objects, like strings, ints, floats and tuples that contain only immutable elements. A set is an unordered collection of unique values.

Sets are iterable, so they are sequences and they support indexing and slicing with square brackets, [].

Which of the following statements is false? With slices, the new sequence's elements refer to the same objects as the original sequence's elements, rather than to separate copies. When you specify a slice and omit the starting index, 0 is assumed.So, the slice numbers[:6] is equivalent to the slice numbers[0:6]. If you omit the ending index, Python assumes the sequence's length. Omitting both the start and end indices on a slice copies the entire sequence. Slices make deep copies of the sequence's elements.

Slices make deep copies of the sequence's elements.

Which of the following statements about the following code is false?word_counts = {}for word in text.split(): ​if word in word_counts: ​word_counts[word] += 1 ​else: ​word_counts[word] = 1 The expression word_counts[word] += 1 inserts a new key-value pair in the dictionary. The expression text.split()tokenizes text by calling string method split, which separates the words using the method's delimiter string argument-if you do not provide an argument, split uses a space. Method split returns a list of tokens (that is, the words in text). All of the above statements are true.

The expression word_counts[word] += 1 inserts a new key-value pair in the dictionary.

Which of the following statements is false? 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 while statement allows you to repeat one or more actions while a condition remains True. The following code sets product to the first power of 2 larger than 64:product = 2while product < 64:product = product * 2 Something in a while statement's suite must ensure that the condition eventually becomes False. Otherwise, a logic error called an infinite loop occurs.

The following code sets product to the first power of 2 larger than 64:product = 2while product < 64:product = product * 2

Which of the following statements a), b) or c) is false? The NumPy library provides the high-performance ndarray collection, which is typically much faster than lists. Specifying the keyword argument return_counts=True tells unique to count each unique value's number of occurrences. The following code uses a list comprehension to create a list of 600 random die values, then uses NumPy's unique function to determine the unique roll values (guaranteed to include all six possible face values) and their frequencies:rolls = [random.randrange(1, 7) for i in range(600)]values, frequencies = np.unique(rolls, return_counts=True) All of the above statements are true.

The following code uses a list comprehension to create a list of 600 random die values, then uses NumPy's unique function to determine the unique roll values (guaranteed to include all six possible face values) and their frequencies:rolls = [random.randrange(1, 7) for i in range(600)]values, frequencies = np.unique(rolls, return_counts=True)

Which of the following statements a), b) or c) is false? The following looks for the value 7 in the range of elements with indices 0 through 4:numbers.index(7, 0, 4) In a call to list method index, specifying the starting and ending indices (as the second and third arguments) causes index to search from the starting index up to but not including the ending index location. The call:numbers.index(5, 7)is equivalent to:numbers.index(5, 7, len(numbers)) All of the above statements are true.

The following looks for the value 7 in the range of elements with indices 0 through 4:numbers.index(7, 0, 4)

Which of the following statements is false? Function calls can be embedded in expressions. The following return statement first terminates the function, then squares number and gives the result back to the caller:return number ** 2 Executing a return statement without an expression terminates the function and implicitly returns the value None to the caller. When there's no return statement in a function, it implicitly returns the value None after executing the last statement in the function's block. The following code calls square first, then print displays the result:print('The square of 7 is', square(7))

The following return statement first terminates the function, then squares number and gives the result back to the caller:return number ** 2

Which of the following statements is false? Importing a module's identifiers with a wildcard import can lead to subtle errors-it's considered a dangerous practice that you should avoid. A wildcard import makes all of the module's identifiers available for use in your code. The following session is a safe use of a wildcard import:In [1]: e = 'hello'In [2]: from math import *In [3]: eOut[3]: 2.718281828459045 You can import all identifiers defined in a module with a wildcard import of the formfrom modulename import *

The following session is a 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? You can create a dictionary by enclosing in curly braces, {}, a comma-separated list of key—value pairs, each of the form key: value. When you output a dictionary, its comma-separated list of key—value pairs is always enclosed in curly braces. The following statement 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'} You can create an empty dictionary with {}.

The following statement 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'}

Which of the following statements is false? Parentheses in an expression are said to be redundant (unnecessary) if removing them yields the same result. Algebraic expressions must be typed in straight-line form using Python's operators. The following code multiplies 10 times the quantity 5 + 3, yielding the result 80:10 * (5 + 3) The parentheses in Part (b) above are redundant.

The parentheses in Part (b) above are redundant.

Which of the following statements is false? The following snippet produces the integer sequence 0 1 2 3 4 5 6 7 8 9:for number in range(100):if number == 10:break ​print(number, end=' ') The following code snippet produces the sequence 0 1 2 3 4 5 5 6 7 8 9:for number in range(10): ​if number == 5: ​continue ​print(number, end=' ') Executing a break statement in a while or for immediately exits that statement. The while and for statements each have an optional else clause that executes only if the loop terminates normally.

The while and for statements each have an optional else clause that executes only if the loop terminates normally.

Which of the following statements a), b) or c) is false? lists can contain other lists as elements. Multidimensional lists can have more than two indices. To identify a particular table element, we specify two indices-by convention, the first identifies the element's column, the second the element's row. All of the above statements are true

To identify a particular table element, we specify two indices-by convention, the first identifies the element's column, the second the element's row.

Assuming the following grades DataFrame: ​Wally Eva Sam Katie Bob Test 1 87 100 94 100 83 Test 2 96 87 77 81 65 Test 3 70 90 90 82 85 which of the following statements about DataFrames is false? 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. The index can be a slice. In the following slice containing, the range specified includes the high index ('Test3'):grades.loc['Test1':'Test3'] 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? You may perform arithmetic between Decimals and floating-point numbers. You typically create a Decimal from a string. You may perform arithmetic between Decimals and integers. Decimals support the standard arithmetic operators +, -, *, /, //, ** and %, as well as the corresponding augmented assignments.

You may perform arithmetic between Decimals and floating-point numbers.

Which of the following popular Python data science libraries are central to machine learning, deep learning and/or reinforcement learning:

all of the above

Which of the following statements is true? A.When you have many statements to execute as a group, you typically write them as a script stored in a file with the .py (short for Python) extension. B.The if statement uses a condition to decide whether to execute a statement (or a group of statements). C. IPython interactive mode is helpful for executing brief code snippets and seeing immediate results. D. All of the above statements are true

all of the above statements are true

The applications-development methodology of ________ enables you to rapidly develop powerful software applications by combining (often free) complementary web services and other forms of information feeds.

mashups

Reworking programs to make them clearer and easier to maintain while preserving their correctness and functionality is called ________.

refactoring

Assume x is 3, y is 7.1 and z is '11.5'. Which of the following statements is incorrect?

the value of z is 11.5

Which of the following statements is false? A lambda explicitly returns its expression's value. For simple functions that return only a single expression's value, you can use a lambda expression to define the function inline where it's needed-typically as it's passed to another function. A lambda expression is an anonymous function-that is, a function without a name. In the following filter call the first argument is the lambda:filter(lambda x: x % 2 != 0, numbers)

A lambda explicitly returns its expression's value.

Which of the following statements a), b) or c) is false? Calculating the mean of an array totals all of its elements regardless of its shape, then divides by the total number of elements. The array methods sum, min, max, mean, std (standard deviation) and var (variance) are each functional-style programming reductions. You can perform array calculations on each array dimension as well. For example, in a two-dimensional array, you can calculate each row's mean or each column's mean. All of the above statements are true.

All of the above statements are true.

Which of the following statements a), b) or c) is false? To use Decimal, you must first import its module, as inimport decimaland refer to the Decimal type as decimal.Decimal, or you must indicate a specific capability to import using from...import, as in:from decimal import Decimalwhich imports only the type Decimal from the decimal module so that you can use it in your code. The Python Standard Library is divided into modules-groups of related capabilities. The decimal module defines type Decimal and its capabilities. All of the above statements are true.

All of the above statements are true.

Which of the following statements is false? Broadcasting can only be applied between arrays of the same size and shape, enabling some concise and powerful manipulations. Normally, the arithmetic operations on arrays require as operands two arrays of the same size and shape. When one operand is a single value, called a scalar, NumPy performs the element-wise calculations as if the scalar were an array of the same shape as the other operand, but with that scalar value in all its elements. If numbers is a five-element integer array, numbers * 2 is equivalent to:numbers * [2, 2, 2, 2, 2]

Broadcasting can only be applied between arrays of the same size and shape, enabling some concise and powerful manipulations.

Which of the following statements is false? When you change a function's code, all calls to the function execute the updated version. Experience has shown that the best way to develop and maintain a large program is to construct it from a small number of large, proven pieces-this technique is called divide and conquer. Using existing functions as building blocks for creating new programs is a key aspect of software reusability-it's also a major benefit of object-oriented programming. Packaging code as a function allows you to execute it from various locations in your program just by calling the function, rather than duplicating the possibly lengthy code.

Experience has shown that the best way to develop and maintain a large program is to construct it from a small number of large, proven pieces-this technique is called divide and conquer.

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])Which of the following statements a), b) or c) is false? The array function determines an array's element type from its argument's elements. For performance reasons, NumPy is written in the Java programming language and uses Java's data types. You can check the element type with an array's dtype attribute. All of the above statements are true.

For performance reasons, NumPy is written in the Java programming language and uses Java's data types.

Which of the following statements a), b) or c) is false? Identifiers with global scope can be used in a .py file or interactive session anywhere after they're defined. Identifiers defined outside any function (or class) have script scope-these may include functions, variables and classes. All of the above statements are true.

Identifiers defined outside any function (or class) have script scope-these may include functions, variables and classes.

Which of the following statements is false? Often, you'll want to determine whether a sequence (such as a list, tuple or string) contains a value that matches a particular key value. Searching is the process of locating a key in a sequence. List method index raises a ValueError if the value you're searching for is not in the list. List method index takes as an argument a search key-the value to locate in the list-then searches through the list from index 1 and returns the index of the first element that matches the search key.

List method index takes as an argument a search key-the value to locate in the list-then searches through the list from index 1 and returns the index of the first element that matches the search key.

Which of the following statements is false? Data science presents unique demands for which more customized data structures are required. Big data applications must support mixed data types, customized indexing, missing data, data that's not structured consistently and data that needs to be manipulated into forms appropriate for the databases and data analysis packages you use. Pandas is the most popular library for dealing with such data. 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.

NumPy's array is optimized for heterogeneous numeric data that's accessed via integer indices.

Which of the following statements is false? Functions are objects that you can pass to other functions as data. In pure functional programming languages you focus on writing pure functions. A pure function's result depends only on the argument(s) you pass to it. Also, given particular arguments, a pure function always produces the same result. For example, built-in function sum's return value depends only on the iterable you pass to it. The following session demonstrates that when you call the pure function sum, it does not modify its argument.In [1]: values = [1, 2, 3]In [2]: sum(values)Out[2]: 6In [3]: sum(values) # same call always returns same resultOut[3]: 6In [4]: valuesOut[4]: [1, 2, 3] Pure functions can have side effects-for example, if you pass a mutable list to a pure function, the list can contain different values before and after the function call.

Pure functions can have side effects-for example, if you pass a mutable list to a pure function, the list can contain different values before and after the function call.

Which of the following statements a), b) or c) is false? The built-in function frozenset creates a frozenset from any iterable. A frozenset is an immutable set-it cannot be modified after you create it, so a set can contain frozensets as elements. Sets are immutable, so sets can have other sets as elements. All of the above statements are true.

Sets are immutable, so sets can have other sets as elements.

Which of the following statements is false? Sets are not iterable, so you cannot process each set element with a for loop. Sets are unordered, so there's no significance to the iteration order. You can determine the number of items in a set with the built-in len function. You can check whether a set contains a particular value using the in and not in operators.

Sets are not iterable, so you cannot process each set element with a for loop.

Which of the following statements a), b) or c) is false? The following code creates a set of strings named colors:colors = {'red', 'orange', 'yellow', 'green', 'red', 'blue'} Sets are ordered, so you can write code that depends on the order of their elements. Duplicate elimination is automatic when creating a set. All of the above statements are true.

Sets are ordered, so you can write code that depends on the order of their elements.

Which of the following statements is false? Sometimes, you may want to guarantee reproducibility of a random sequence-for debugging, for example. You can do this with the random module's repeat function. You can introduce the element of chance via the Python Standard Library's random module. Different values are likely to be displayed each time you run the code in Part (b). 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, 7), end=' ')

Sometimes, you may want to guarantee reproducibility of a random sequence-for debugging, for example. You can do this with the random module's repeat function.

Which of the following statements is false? The right side of the = symbol always executes first, then the result is assigned to the variable on the symbol's left side. The snippet in Part (a) is read, "total is assigned the value of x + y." The = symbol is the assignment operator. The following assignment statement adds the values of variables x and y and assigns the result to the variable total:total = x + y

The = symbol is the assignment operator.

Which of the following statements is false? One of Python's most common iterable sequences is the list, which is a comma-separated collection of items enclosed in square brackets ([ and ]). The sequence to the right of the for statement's keyword in must be an iterable. An iterable is an object from which the for statement can take one item at a time until no more items remain. The following code totals five integers in a list:total = 0for number in [2, -3, 0, 17, 9]:total + number

The following code totals five integers in a list: total = 0 for number in [2, -3, 0, 17, 9]:total + number

Which of the following statements a), b) or c) is false? Series and DataFrames make it easy for you to perform common tasks like selecting elements a variety of ways, filter/map/reduce operations (central to functional-style programming and big data), mathematical operations, visualization, data preparation and more. NumPy and pandas are intimately related. Series and DataFrames use arrays "under the hood." Series and DataFrames are valid arguments to many NumPy operations. Similarly, arrays are valid arguments to many Series and DataFrame operations. Correct! The name pandas is derived from The name pandas is derived from the term "panel data," which is data for spatial measurements, such as stock prices or historical temperature readings. All of the above statements are true.

The name pandas is derived from the term "panel data," which is data for spatial measurements, such as stock prices or historical temperature readings.

Which of the following statements is false? You can use the remainder operator for applications such as determining whether one number is a multiple of another. The value of the following expression is 3:17 % 5 You can use the remainder operator to determine whether a number is odd or even. The value of the following expression is 0.5:7.5 % 3.5

The value of the following expression is 3: 17 % 5

Which of the following statements is false? When you iterate over a view, it "sees" a copy of the dictionary's current contents. Dictionary methods keys and values can be used to iterate through a dictionary's keys or values, respectively. You should not modify a dictionary while iterating through a view. According to the Python Standard Library documentation, either you'll get a RuntimeError or the loop might not process all of the view's values. Dictionary methods items, keys and values each return a view of a dictionary's data.

When you iterate over a view, it "sees" a copy of the dictionary's current contents.

Which of the following statements a), b) or c) is false? To square a number, you can use the exponent 1/2 (that is, 0.5), as in:9 ** (1 / 2) All of the above statements are true. Python uses the asterisk (*) as the multiplication operator (e.g., 7 * 4). The exponentiation (**) operator raises one value to the power of another (e.g., 2 ** 10).

To square a number, you can use the exponent 1/2 (that is, 0.5), as in:9 ** (1 / 2)

Which of the following statements a), b) or c) is false?'' Using a keyword as an identifier causes a ValueError. A condition is a Boolean expression with the value True or False. All of the above statements are true. True and False are keywords-words that Python reserves for its language features.

Using a keyword as an identifier causes a ValueError.

The value of the expression '7' + '3' is the ________.

string '73'

A new class of objects can be created conveniently by inheritance-the new class (called the ________) starts with the characteristics of an existing class (called the ________), possibly customizing them and adding unique characteristics of its own.

subclass, superclass

Various Python statements enable you to specify that the next statement to execute may be other than the next one in sequence. This is called ________ and is achieved with Python control statements.

transfer of control

Which of the following statements a), b) or c) is false? An algorithm is a procedure for solving a problem in terms of the actions to execute, and the order in which these actions execute. All of the above statements are true. You can solve any computing problem by executing a series of actions in a specific order. Program control specifies the order in which statements (actions) execute in a program.

All of the above statements are true.

Which of the following statements is false?

Programmers use the Python Standard Library and various other libraries to "reinvent the wheel."

What does the following line of code display?print(10, 20, 30, sep=', ') 10 20 30 102030 10, 20, 30 10,20,30

10, 20, 30

The chained comparison 3 < y <= 11 is false for which of the following values of y: 11 10 3 4

3

Which of the following statements is incorrect ? The range of values is simply the minimum through the maximum value. Much of data science is devoted to getting to know your data. min(17, 19, 23, 29, 31, 37, 43) is a valid call to built-in function min. all of the above are correct

All of the above are correct.

Which of the following statements about the cloud is false?

Azure is Google's set of cloud-based services.

Which of the following statements is false about Berners lee

Berners-Lee also wrote communication protocols such as JavaScript Object Notation (JSON) to form the backbone of his new hypertext information system, which he referred to as the World Wide Web.

Which of the following statements is false? Financial institutions like banks that deal with millions or even billions of transactions per day have to tie out their transactions "to the penny." Floating-point numbers can represent some but not all monetary amounts with to-the-penny precision. Floating-point values are stored and represented precisely in binary format. Many applications require precise representation of numbers with decimal points. For monetary calculations and other applications that require precise representation and manipulation of numbers with decimal points, the Python Standard Library provides type Decimal, which uses a special coding scheme to solve the problem of "to-the-penny precision." Banks also have to deal with other issues such as using a fair rounding algorithm when they're calculating daily interest on accounts. Type Decimal offers such capabilities.

Floating-point values are stored and represented precisely in binary format.

Which of the following statements a), b) or c) is false? In an f-string, you can optionally follow a replacement-text expression with a colon (:) and a format specifier that describes how to format the replacement text. The format specifier .2f formats data as a floating-point number (f) with two digits to the right of the decimal point (.2). Formatting floating-point data with .2f rounds it to the tenths position. All of the above statements are true.

Formatting floating-point data with .2f rounds it to the tenths position.

Which of the following statements is false? Python allows you to split long code lines in parentheses without using continuation characters. Together, blank lines, space characters and tab characters are known as white space. Python ignores all white space. You use blank lines and space characters to make code easier to read.

Python ignores all white space.

Which of statements a), b) or c) is false? A variable name, such as x, is an identifier. 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. Each identifier may consist of letters, digits and underscores (_) but may not begin with a digit. 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.

Which of the following statements is false? The numpy module is typically imported withimport numpy as npy Typically, when importing a module, you should use import or import...as statements, then access the module through the module name or the abbreviation following the as keyword, respectively. This ensures that you do not accidentally import an identifier that conflicts with one in your code. import...as is frequently used to import Python libraries with convenient abbreviations, like stats for the statistics module. Sometimes it's helpful to import a module and use an abbreviation for it to simplify your code. The import statement's as clause allows you to specify the name used to reference the module's identifiers. For example, we can import the statistics module and access its mean function as follows:In [1]: import statistics as statsIn [2]: grades = [85, 93, 45, 87, 93]In [3]: stats.mean(grades)Out[3]: 80.6

The numpy module is typically imported with import numpy as npy

Which of the following statements is false? 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. 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.

Which of the following statements is false. Variables for totaling and counting normally are initialized to zero before they're used. Once a correct algorithm has been specified, creating a working Python program from the algorithm is typically straightforward. Experience has shown that the most challenging part of solving a problem on a computer is developing an algorithm for the solution. A requirements statement describes how a program should operate but not what the program is supposed to do.

A requirements statement describes how a program should operate but not what the program is supposed to do.

Which of the following statements is false? Grades on a quiz are typically nonnegative integers between 0 and 100, so the value —1 is an acceptable sentinel value for grades data. Sentinel-controlled iteration is often called indefinite iteration because the number of iterations is not known before the loop begins executing. A sentinel value must match one acceptable input value. A sentinel value indicates end of data entry."

A sentinel value must match one acceptable input value.

Which of the following statements is false? To avoid using \' and \" inside strings, you can enclose such strings in triple quotes. 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.

A string delimited by double quotes may not include double quotes.

Which of the following statements a), b) or c) is false? You form each Python program by combining as many control statements of each type as you need for the algorithm the program implements. All of the above statements are true. You can construct any Python program from only six different forms of control (sequential execution, and the if, if...else, if...elif...else, while and for statements). You combine these in only two ways (control-statement stacking and control-statement nesting). This is the essence of simplicity. With Single-entry/single-exit (one way in/one way out) control statements, the exit point of one connects to the entry point of the next. This is similar to the way a child stacks building blocks-hence, the term control-statement stacking.

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 = 70In [3]: if gender == 'Female' and age >= 65: ​...: print('Senior female') ​...: Senior female The combined condition can be made clearer by adding redundant (unnecessary) parentheses(gender == 'Female') and (age >= 65) All of the above statements are true. 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.

All of the above statements are true.

Which of the following statements is false? Strings containing characters are True and empty strings ('', "" or """""") are False. All of the above statements are true. A condition which evaluates to a nonzero value is considered to be True, and a condition which evaluates to a value of zero is considered to be False. Any expression may be evaluated as True or False.

All of the above statements are true.

Which of the following Python concepts are demonstrated directly or indirectly by the following code: In [1]: x = 7 Out[1]: int In [2]: type(x) Out[2]: int In [3]: x = 4.1 In [4]: type(x) Out[4]: float In [5]: x = 'dog' In [6]: type(x) Out[6]: str Python uses dynamic typing-it determines the type of the object a variable refers to while executing your code. All of the above. Over its lifetime a variable can be bound to different objects, even objects of different types. Python creates objects in memory and removes them from memory as necessary. This removal process-called garbage collection-helps ensure that memory is available for new objects you create.

All of the above.

Which of the following statements a), b) or c) is false?

Almost any verb can be reasonably represented as a software object in terms of attributes (e.g., name, color and size) and behaviors (e.g., calculating, moving and communicating).

Which of the following statements a), b) or c) is false? When a backslash (\) appears in a string, it's known as the escape character. All of the above statements are true Placing two backslashes back-to-back tells print to display a blank line. . The backslash and the character immediately following it form an escape sequence. For example, \n represents the newline character escape sequence, which tells print to move the output cursor to the next line.

Placing two backslashes back-to-back tells print to display a blank line.

Which of the following statements is false? The argument of each of the statistics module's mean, median and mode functions must be an iterable. If a list's number of values is even, median returns the mode of the two middle values. 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] The mode function causes a Statistics Error 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. If an expression contains several exponentiation operations, Python applies them from left to right. 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.

Which of the following statements is false? Programs that are not uniformly indented are hard to read. If you have more than one statement in a suite, those statements do not need to have the same indentation. Indenting a suite is required; otherwise, an IndentationError syntax error occurs. Sometimes error messages may not be clear. The fact that Python calls attention to the line is often enough for you to figure out what's wrong.

If you have more than one statement in a suite, those statements do not need to have the same indentation.

Which of the following statements is false? In operator expressions that use the and operator, make the condition that's more likely to be True the leftmost condition-in or operator expressions, make the condition that's more likely to be False the leftmost condition-each of these tactics can reduce a program's execution time. The following condition stops evaluating immediately if semester_average is greater than or equal to 90 because the entire expression must be True:semester_average >= 90 or final_exam >= 90 The following condition stops evaluating immediately if gender is not equal to 'Female' because the entire expression must be False. If gender is equal to 'Female', execution continues, because the entire expression will be True if the age is greater than or equal to 65:gender == 'Female' and age >= 65 Python stops evaluating an and-expression as soon as it knows whether the entire condition is False. Python stops evaluating an or-expression as soon as it knows whether the entire condition is True.

In operator expressions that use the and operator, make the condition that's more likely to be True the leftmost condition-in or operator expressions, make the condition that's more likely to be False the leftmost condition-each of these tactics can reduce a program's execution time.

Which of the following statements is false? When we say that Python applies certain operators from left to right, we are referring to the operators' grouping. All Python operators of the same precedence group left-to-right except for the exponentiation operator (**), which groups right-to-left. In the following expression, the addition operators (+) group as if we parenthesized the expression as a+(b+c). You can use redundant parentheses to group subexpressions to make expressions clearer. For example, the second-degree polynomialy = a * x ** 2 + b * x + ccan be parenthesized, for clarity, asy = (a * (x ** 2)) + (b * x) + c

In the following expression, the addition operators (+) group as if we parenthesized the expression as a+(b+c).

Which of the following statements is false? In the following session, snippets [2] and [5] produce the same results purely by coincidence:In [1]: import randomIn [2]: random.seed(32)In [3]: for roll in range(10): ​...: print(random.randrange(1, 7), end=' ') ​...: 1 2 2 3 6 2 4 1 6 1In [4] for roll in range(10): ​...: print(random.randrange(1, 7), end=' ') ​...: 1 3 5 3 1 5 6 4 3 5In [5] random.seed(32)In [6]: for roll in range(10): ​...: print(random.randrange(1, 7), end=' ') ​...: 1 2 2 3 6 2 4 1 6 1 When you're debugging logic errors in programs that use randomly generated data, it can be helpful to use the same sequence of random numbers until you've eliminated the logic errors, before testing the program with other values. Function randrange actually generates pseudorandom numbers, based on an internal calculation that begins with a numeric value known as a seed. You can use the random module's seed function to seed the random-number generator yourself-this forces randrange to begin calculating its pseudorandom number sequence from the seed you specify. Choosing the same seed will cause the random number generator to generate the same sequence of random numbers.

In the following session, snippets [2] and [5] produce the same results purely by coincidence:In [1]: import randomIn [2]: random.seed(32)In [3]: for roll in range(10): ​...: print(random.randrange(1, 7), end=' ') ​...: 1 2 2 3 6 2 4 1 6 1In [4] for roll in range(10): ​...: print(random.randrange(1, 7), end=' ') ​...: 1 3 5 3 1 5 6 4 3 5In [5] random.seed(32)In [6]: for roll in range(10): ​...: print(random.randrange(1, 7), end=' ') ​...: 1 2 2 3 6 2 4 1 6 1

Which of the following statements is false? In the top-down, stepwise refinement process for developing algorithms, each refinement represents another portion of the algorithm. In top-down, stepwise refinement, the top is a single statement that conveys the program's overall function but rarely conveys enough detail from which to write a program. The top specifies what should be done, but not how to implement it. In the refinement process, we decompose the top into a sequence of smaller tasks-a process sometimes called divide and conquer.

In the top-down, stepwise refinement process for developing algorithms, each refinement represents another portion of the algorithm.

Which of the following statements is false? Many scripts can be decomposed into initialization, processing and termination phases. The Style Guide for Python Code recommends placing a blank line above and below each control statement. Iteration is called definite iteration if the number of iterations is first known after the loop finishes executing. The following statement creates the variable grades and initializes it with a list of 10 integer grades.grades = [98, 76, 71, 87, 83, 90, 57, 79, 82, 94]

Iteration is called definite iteration if the number of iterations is first known after the loop finishes executing.

Which of the following statements about descriptive statistics is false? The range is the values starting with the minimum and ending with the maximum. The count is the number of values in a collection. Measures of dispersion (also called measures of variability), such as count, help determine how spread out values are. The minimum is the smallest value in a collection of values.

Measures of dispersion (also called measures of variability), such as count, help determine how spread out values are.

Which of the following statements is false? The placeholder {average} converts the variable average's value to a string representation, then replaces {average} with that replacement text. The following f-string inserts the value of average into a string:f'Class average is {average}' Replacement-text expressions in placeholders may contain values, variables or other expressions, such as calculations, but may not contain function calls. You specify where to insert values in an f-string by using placeholders delimited by curly braces ({ and }).

Replacement-text expressions in placeholders may contain values, variables or other expressions, such as calculations, but may not contain function calls.

Which of the following statements is false? A key programming goal is to avoid "reinventing the wheel." A package groups related modules. Every Python source-code (.py) file you create is a module. They're typically used to organize a large library's functionality into smaller subsets that are easier to maintain and can be imported separately for convenience. The Python Standard Library module money provides arithmetic capabilities for performing monetary calculations. A module is a file that groups related functions, data and classes.

The Python Standard Library module money provides arithmetic capabilities for performing monetary calculations.

Which of the following statements is false? Floor division (//) divides a numerator by a denominator, yielding the highest integer that's not greater than the result. The expression -13 // 4 evaluates to -3. The expression -13 / 4 evaluates to -3.25. True division (/) divides a numerator by a denominator and yields a floating-point number with a decimal point.

The expression -13 // 4 evaluates to -3.

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? 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=' ') 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 10 8 6 4 2 0.for number in range(10, 0, -2): ​print(number, end=' ')

Which of the following statements is false? After the following snippet's assignment, the variable x refers to the integer object containing 7.x = 7 The following statement changes x's value:x + 10 The following statement changes x's value:x = x + 10 Assigning an object to a variable binds that variable's name to the object. You can then use the variable in your code to access the object's value.

The following statement changes x's value:x + 10

With regard to 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 + 1which of the following statements is true? The if statement follows the for statement in sequence. The for statement is nested in the if statement. None of the above. Correct! The if statement is nested in the for statement.

The if statement is nested in the for statement.

Which of the following statements is false? Python provides three types of selection statements that execute code based on a condition-any expression that evaluates to either True or False. The if...elif...else statement is called a double-selection statement because it selects one of two different actions (or groups of actions). The if...else statement performs an action if a condition is True or performs a different action if the condition is False. Anywhere a single action can be placed, a group of actions can be placed.

The if...elif...else statement is called a double-selection statement because it selects one of two different actions (or groups of actions).

Which of the following statements is false? The indented lines after the colon (:) are the function's suite, which consists of an optional docstring followed by the statements that perform the function's task. Like variable identifiers, by convention function names should begin with a lowercase letter and in multiword names underscores should separate each word. The required parentheses in a function definition 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 colon (:).

The indented lines after the colon (:) are the function's suite, which consists of an optional docstring followed by the statements that perform the function's task.

Which of the following statements is false? Sometimes the suites in an if...else statement assign different values to a variable, based on a condition, as in:grade = 87if grade >= 60:result = 'Passed'else:result = 'Failed' Correct Answer The parentheses in a conditional expression are required; otherwise, a syntax error occurs. You can replace if...else statements like the one above using a concise conditional expression:result = ('Passed' if grade >= 60 else 'Failed') All of the above statements are true.

The parentheses in a conditional expression are required; otherwise, a syntax error occurs.

Which of the following statements a), b) or c) is false? The following code calculates the population standard deviation with the statistics module's pstdev function:statistics.pstdev([1, 3, 4, 2, 6, 5, 3, 4, 5, 2]) The standard deviation is the square root of the variance, which tones down the effect of the outliers. All of the above statements are true. The smaller the variance and standard deviation are, the further the data values are from the mean and the greater overall dispersion (that is, spread) there is between the values and the mean.

The smaller the variance and standard deviation are, the further the data values are from the mean and the greater overall dispersion (that is, spread) there is between the values and the mean.

Which of the following statements a), b) or c) is false? The following code re-implements the for statement in Part (a) 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 statementf *= 3. All of the above statements are true. 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 statement f = f ** 3 may be replaced by the more concise augmented assignment statementf *= 3.

Which of the following statements is false? 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 by default. print does not display a string's quotes, though there is a way to display quotes in strings. When you evaluate expressions in interactive mode, the text that print displays is preceded by Out[] with a snippet number in the square brackets.

When you evaluate expressions in interactive mode, the text that print displays is preceded by Out[] with a snippet number in the square brackets.

Which of the following statements a), b) or c) is false? For a fatal logic error in a script, an exception occurs (such as a ZeroDivisionError from an attempt to divide by 0), so Python displays a traceback, then terminates the script. With a logic error, an IPython interactive session terminates. All of the above statements are true. A fatal error in interactive mode terminates only the current snippet. Then IPython waits for your next input.

With a logic error, an IPython interactive session terminates.

Which of the following statements is false? The if statementif not grade == -1: ​print('The next grade is', grade) also can be written as follows:if grade != -1: ​print('The next grade is', grade) You place the not operator before a condition to choose a path of execution if the original condition (without the not operator) is True. The Boolean not operator reverses the meaning of a condition-True becomes False and False becomes True. The not operator is a unary operator-it has only one operand.

You place the not operator before a condition to choose a path of execution if the original condition (without the not operator) is True.

With ________ software development, individuals and companies contribute their efforts in developing, maintaining and evolving software in exchange for the right to use that software for their own purposes, typically at no charge.

open-source

________ is by far the world's most widely used desktop operating system.

windows


Related study sets

Female reproductive system Part 2

View Set

STATS FINAL SEM TWO MAJOR STUDY SET

View Set

Chapter 2, 6, 11-16, 27, 32- TEST TWO

View Set

Hello, Universe By Erin Entrada Kelly

View Set