COSC 1306 SET 4 REVIEW, Set 3 Zybooks COSC 1306, Set 2 Zybook COSC 1306, Set 1 Zybook COSC 1306
Used to reference an object in an imported module.
dot notation
What character is in index 2 of the string "America"?
e
Determine the output of the following code snippets. If an error would occur, type "error". print('{hour}:{minute}'.format(hour=9, 43=minute))
error
In the example above, the first value gotten from input was 2. That caused the loop body to be _____.
executed
The output of print(sorted([-5, 5, 2])) is [2, -5, 5].
false
the size of a list is determined when the list is created and can not change
false
Which assigns a string read from input to first_name?
first_name = input('Type your name:')
A person's height in centimeters. float or int
float
The current temperature in Celsius. float or int
float
{'Medusa', 'Bert', 'Tom'} monsters.symmetric_difference()
horde
Loop iterates 10 times. i = 1 while : # Loop body statements go here i = i + 1
i <= 10
Given the following program, select the namespace that each name would belong to. number local global built-in
local
Write an expression that finds the minimum value in the list prices.
min(prices)
A file containing Python code that is imported by a script, module, or the interactive interpreter
module
Fill in the code, using the dict methods items(), keys(), or values() where appropriate. Change all negative values in my_dict to 0. for key, value in ____: if value < 0: my_dict[key] = 0
my_dict.items()
Print each key in the dictionary my_dict. for key in _____: print(key)
my_dict.keys()
Complete the statement to read up to 500 bytes from "readme.txt" into the contents variable. my_file = open('readme.txt') contents = ___ # ...
my_file.read(500)
Write a statement that creates a list called my_list with the elements -100 and the string 'lists are fun'
my_list = [-100, 'lists are fun']
Which statement adds 'pears' to the following dictionary? prices = {'apples': 1.99, 'oranges': 1.49, 'kiwi': 0.79}
prices['pears'] = 1.79
Type a statement that prints: Hello
print ('Hello')
Write the simplest range() function that generates the appropriate sequence of integers. Every integer from 10 to 20
range(10, 21)
What is the value of my_str after the following statements are evaluated: my_str = 'http://reddit.com/r/python' protocol = 'http://' my_str = my_str[len(protocol):]
reddit.com/r/python
the statement my_list1 + my_list2 produces a new list
true
Choose the container that best fits the described data. The final number of As, Bs, Cs, Ds, and Fs in the class
tuple
max What should expression (A) be?
val > max
The value of num as a hexadecimal (base 16) integer: 1f num = 31 print('{: }'.format(num))
x
Select the expression whose parentheses match the evaluation order of the original expression. x + 1 * y/2
x + ((1 * y) / 2)
Write the simplest expression that captures the desired comparison. The variables x and y are unique objects.
x is not y or y is not x
Provide an expression using x.sort that sorts the list x accordingly. Sort the elements of x such that the greatest element is in position 0.
x.sort(reverse=True)
Sort the elements of x such that the greatest element is in position 0.
x.sort(reverse=True)
After the first loop, was the baby awake?
y
When the parents first checked, was the baby awake?
y
How many times will the loop body execute? Assume user would enter 'n', then 'n', then 'y'. # Get character from user here while user_char != 'n': # Do something # Get character from user here
0
What is the final value of employee_bonus for each given value of num_sales? if num_sales == 0: employee_bonus = 0 elif num_sales == 1: employee_bonus = 2 elif num_sales == 2: employee_bonus = 5 else: employee_bonus = 10 num_sales is 0
0
With what value was sum initialized?
0
Consider the following program: nums = [10, 20, 30, 40, 50] for pos, value in enumerate(nums): tmp = value / 2 if (tmp % 2) == 0: nums[pos] = tmp 1) What's the final value of nums[1]?
10.0
What is the decimal encoding of the '{' character?
123
Determine the final value of z. x x = 2.3 z = math.floor(x)
2
Given the following program, and the definition of print_face() above: print_pizza_area() print_pizza_area() How many function calls to print_pizza_area() exist?
2
How many loops around the block did the parents make?
2
How many times will the loop body execute? Assume user would enter 'a', then 'b', then 'n'. # Get character from user here while user_char != 'n': # Do something # Get character from user here
2
5.0 // 2
2.0
Determine the final value of z. z = 4 z = math.factorial(z)
24
2) How many elements does scores contain? (The result of len(scores))
3
Assume the following list has been created scores = [ [75, 100, 82, 76], [85, 98, 89, 99], [75, 82, 85, 5] ] How many elements does scores contain? (The result of len(scores))
3
What does ebay_fee() return if its argument is 100.0 (show your answer in the form #.#)?
9.5
Given the list nums = [[10, 20, 30], [98, 99]], what does nums[1][1] evaluate to?
99
Human-readable processor instructions
Assembly Language
weight = Get next input If weight < 150: Put "Can ride." to output Else: Put "Can't ride." to output What is output when the input is 200? A. Can ride. Done. B. Can't ride. Done.
B. Can't ride. Done.
Given the following code: nums = [0, 25, 50, 75, 100] The result of evaluating nums[0:5:2] is [25, 75]. A. True B. False
B. False
Given: for i in range(5): if i < 10: continue print(i) The loop will iterate only once. A. True B. False
B. False
Given: for i in range(5): if i < 10: continue print(i) The loop will print at least some output. A. True B. False
B. False
Mixing spaces and tabs when indenting is considered an acceptable programming style. A. True B. False
B. False
Given the description of a race, choose the condition that should be checked before each loop around the track. Loop while the car's fuel tank is at least 20% full. A. Fuel tank is at 20%. B. Fuel tank is at 20% or more. C. Fuel tank is less than 20%.
B. Fuel tank is at 20% or more.
w and x == y and z evaluates as (w and x) == (y and z)? A. Yes B. No
B. No
Consider the if-else if-else structure below: If x equals -1 Put "Disagrees" to output Else If x equals 0 Put "Neutral" to output Else If x equals 1 Put "Agrees" to output Else Put "Invalid entry" to output In the code above, suppose a programmer removed the Else part entirely. If x is 2, which is correct? A. The last branch, meaning the Else If x equals 1 branch, will execute. B. No branch will execute. C. The program is not legal.
B. No branch will execute.
How are most Python programs developed? A. Writing code in the interactive interpreter. B. Writing code in files.
B. Writing code in files.
100 % (1 // 2)
Error
100 / 0
Error
Find the syntax errors. Assume variable num_dogs exists. print(num_dogs). Error or No Error
Error
What is the final value of num_items? Write "Error" if the code results in an error. num_items = 3 if num_items = 10: num_items = num_items + 1
Error
'1 2 3 4 5'.isdigit() True or False
False
'HTTPS://google.com'.isalnum() True or False
False
4) What value is returned by all(my_list)?
False
A dictionary entry is accessed by placing a key in curly braces { }. True or False
False
A function may return multiple objects. True or False
False
A key reason for creating functions is to help the program run faster True or False
False
print('Hi {{{0}}}!'.format('Bilbo'))
Hi {Bilbo}!
day_of_the_week = Friday
NameError
Match minimum field width term with the definition
Optional component that determines the number of characters a conversion specifier must insert
'\n \n'.isspace() True or False
True
A memory stores bits. True or False
True
Given the list nums = [[10, 20, 30], [98, 99]], what does nums[0] evaluate to?
[10, 20, 30]
Twice the value of each element in the list variable x
[i*2 for i in x]
Fill in the missing Boolean operators. days is greater than 30 and less than 90. if (days > 30) ____ (days < 90):
and
The value of num as a binary (base 2) integer: 11111 num = 31 print('{: }'.format(num))
b
Complete the loop expressions, using a single operator in your expression. Use the most straightforward translation of English to a expression. Iterate while c equals 'g'. while ____ : # Loop body statements go here
c == 'g'
Adding an element to a dictionary argument in a function might affect variables outside the function that reference the same dictionary object. True or False
True
After the following executes, the value of address is '500 Floral Avenue'. street_num = '500' street = 'Floral Avenue' address = street_num + ' ' + street True or False
True
Assume that my_list is [0, 5, 10, 15]. What value is returned by any(my_list)?
True
Assuming the launch angle is less than 90 degrees, each iteration of the loop will see x_loc increase. True or False
True
Copying-and-pasting code can lead to common errors if all necessary changes are not made to the pasted code. True or False
True
Dictionary entries can be modified in-place - a new dictionary does not need to be created every time an element is added, changed, or removed.
True
Executing the following statements adds a new entry to the dictionary: prices = {'apples': 1.99, 'oranges': 1.49, 'kiwi': 0.79} prices['oranges'] = '1.29' True or False
True
Executing the statements: address = '900 University Ave' address = '620 University Ave' is a valid way to change address to '620 University Ave'. True or False
True
Forgetting to return a value from a function is a common error. True or False
True
Functions are compiled into bytecode when the function definition is evaluated by the interpreter. True or False
True
Given: def square_root(x): return math.sqrt(x) def print_val(x): print(x) return print_val(9.0) True or False
True
Given: def square_root(x): return math.sqrt(x) def print_val(x): print(x) return square_root(9.0) True or False
True
Given: def square_root(x): return math.sqrt(x) def print_val(x): print(x) return y = 1.0 + square_root(144.0) True or False
True
Given: def square_root(x): return math.sqrt(x) def print_val(x): print(x) return y = print_val(9.0) True or False
True
Given: def square_root(x): return math.sqrt(x) def print_val(x): print(x) return y=square_root(square_root(16.0)) True or False
True
Given: def square_root(x): return math.sqrt(x) def print_val(x): print(x) return which of the following are valid statements? y = square_root(49.0) True or False
True
If a function creates a local variable that has the same name as a parameter of that function, the name will refer to the local variable. True or False
True
Incremental development may involve more frequent testing, but ultimately leads to faster development of a program. True or False
True
Indicate whether the expression evaluates to true or false. x is 5, y is 7. x != y
True
Indicate whether the expression evaluates to true or false. x is 5, y is 7. x <= 7
True
Indicate whether the expression evaluates to true or false. x is 5, y is 7. x == 5
True
Indicate whether the expression evaluates to true or false. x is 5, y is 7. y != 99
True
Indicate whether the expression evaluates to true or false. x is 5, y is 7. y >= 7
True
Polymorphism refers to how an operation depends on the involved object types. True or False
True
Python code can be written in a simple text editor, such as Notepad (Windows). True or False
True
Returning the incorrect variable from a function is common error. True or False
True
Static-typed languages require that the type of every variable is defined in the source code. True or False
True
The code 20 * 40 is an expression. True or False
True
The computer inside a modern smartphone would have been huge 30 years ago. True or False
True
The flush() method (and perhaps os.fsync() as well) forces the output buffer to write to disk.
True
The statement f.write(10.0) always produces an error.
True
The statement return a, b, [c, d] is valid. True or False
True
When using a with statement to open a file, the file is automatically closed when the statements in the block finish executing.
True
Whenever a function is called, a local namespace is created for that function. True or False
True
as_constant = 8.3144621 # Joules / (mol*Kelvin) def convert_to_temp(pressure, volume, mols): """Convert pressure, volume, and moles to a temperature""" return (pressure * volume) / (mols * gas_constant) press = float(input('Enter pressure (in Pascals): ')) vol = float(input('Enter volume (in cubic meters): ')) mols = float(input('Enter number of moles: ')) print('Temperature = %02f K' % convert_to_temp(press, vol, mols)) Function convert_to_temp uses a rewritten form of PV = nRT to solve for T, namely T = PV/nR. True or False
True
gas_constant = 8.3144621 # Joules / (mol*Kelvin) def convert_to_temp(pressure, volume, mols): """Convert pressure, volume, and moles to a temperature""" return (pressure * volume) / (mols * gas_constant) press = float(input('Enter pressure (in Pascals): ')) vol = float(input('Enter volume (in cubic meters): ')) mols = float(input('Enter number of moles: ')) print('Temperature = %02f K' % convert_to_temp(press, vol, mols)) Function convert_to_temp uses a global variable for the gas constant R. True or False
True
trajectory() cannot return two values (for x and y), so instead returns a single tuple containing both x and y. True or False
True
lyric = 99 + " bottles of pop on the wall"
Type Error
Indicate which are valid expressions. x and y are variables. 2 Valid or Not valid
Valid
Indicate which are valid expressions. x and y are variables. x Valid or Not valid
Valid
Indicate which are valid expressions. x and y are variables. x + 1 Valid or Not valid
Valid
Indicate which assignment statements are valid. x = 1 Valid or Invalid
Valid
Which of the following are valid names? ___numcars2 Valid or Invalid
Valid
Which of the following are valid names? _num_cars Valid or Invalid
Valid
Which of the following are valid names? numCars Valid or Invalid
Valid
Which of the following are valid names? num_cars1 Valid or Invalid
Valid
Which of the following are valid names? output Valid or Invalid
Valid
Which of the following are valid names? print_copy Valid or Invalid
Valid
Which of the following are valid names? third_place_ Valid or Invalid
Valid
int("Thursday")
ValueError
Indicate which items are string literals. '674'
Yes
Indicate which items are string literals. 'Hey there.'
Yes
Is the following an error? num_years = 1,999,999,999
Yes
Would removing the parentheses as below have yielded the same result? down_payment + payment_per_month * num_months
Yes
Would using two assignment statements as below have yielded the same result? total_monthly = payment_per_month * num_months total_cost = down_payment + total_monthly
Yes
Assume variable age = 22, pet = "dog", and pet_name = "Gerald". What is the output of print('You are', age, 'years old.')
You are 22 years old.
Only negative odd values from the list x
[(i) for i in x if ((i < 0) and (i % 2 == 1))]
Write a list comprehension that contains elements with the desired values. Use the name 'i' as the loop variable. Use parentheses around the expression or condition as necessary. Only negative values from the list x
[(i) for i in x if ((i < 0) and (i % 2 == 1))]
Assume that the following code has been evaluated: nums = [1, 1, 2, 3, 5, 8, 13] 1)What is the result of nums[1:5]?
[1, 2, 3, 5]
Assume that the following code has been evaluated: nums = [1, 1, 2, 3, 5, 8, 13] What is the result of nums[1:5]?
[1, 2, 3, 5]
What's the output of the list comprehension program in row 4 of the table above if my_list is [[5, 10], [1]]?
[15, 1]
3) What is the result of nums [3:-1]?
[3, 5, 8]
Assume that the following code has been evaluated: nums = [1, 1, 2, 3, 5, 8, 13] What is the result of nums [3:-1]?
[3, 5, 8]
What's the output of the list comprehension program from row 3 in the table above if the user enters "4 6 100"?
[4, 6, 100]
What's the output of the list comprehension program in row 1 in the table above if my_list is [-5, -4, -3]?
[5, 6, 7]
2) What is the result of nums[5:10]?
[8, 13]
Assume that the following code has been evaluated: nums = [1, 1, 2, 3, 5, 8, 13] What is the result of nums[5:10]?
[8, 13]
The absolute value of each element in x. Use the abs() function to find the absolute value of a number.
[abs(i) for i in x]
Write a list comprehension that contains elements with the desired values. Use the name 'i' as the loop variable. The absolute value of each element in x. Use the abs() function to find the absolute value of a number.
[abs(i) for i in x]
Only negative values from the list x
[i for i in x if i < 0]
Write a list comprehension that contains elements with the desired values. Use the name 'i' as the loop variable. Twice the value of each element in the list variable x.
[i*2 for i in x] or [2*i for i in x]
What is the output of print('\\c\\users\\juan')
\c\users\juan
Which instruction completes the program to compute the average of three numbers? x = Get next input y = Get next input z = Get next input _____ Put a to output
a = (x+y+z) / 3
What is the output of the following code? c1 = 'a' while c1 < 'b': c2 = 'a' while c2 <= 'c': print('%s%s' % (c1, c2), end=' ') c2 = chr(ord(c2) + 1) c1 = chr(ord(c1) + 1)
aa ab ac
Fill in the missing Boolean operators. num_dogs is 3 or more and num_cats is 3 or more. if (num_dogs >= 3) ____ :
and (num_cats >= 3) or and (num_cats > 2) or and num_cats >= 3 or and num_cats > 2
Complete the function definition requiring two arguments arg1 and arg2, and an arbitrary argument list args. def f(_____________): # ...
arg1, arg2, *args or arg2, arg1, *args
Assign x to a bytes object containing three bytes with hexadecimal values 0x05, 0x15, and 0xf2. Use a bytes literal.
b'\x05\x15\xf2'
Assign x to a bytes object with a single byte whose hexadecimal value is 0x1a. Use a bytes literal. x =
b'\x1a'
Given the following program, select the namespace that each name would belong to. str local global built-in
built-in
Complete the missing parts of the code. Loop iterates over the odd integers from 1 to 9 (inclusive). i = 1 while i <= 9: # Loop body statements go here
i = i + 2
Complete the missing parts of the code. Loop iterates over the odd integers from 211 down to 31 (inclusive). i = 211 while i >= 31: # Loop body statements go here
i = i - 2 or i -= 2
Write an expression that gives the identity of the variable num.
id(num)
If num_players is greater than 11, execute team_size = 11. Otherwise, execute team_size = num_players. Then, no matter the value of num_players, execute team_size = 2 * team_size.
if num_players > 11: team_size = 11 else: team_size = num_players team_size = 2 * team_size
If user_age is greater than 62, assign item_discount with 15. Else, assign item_discount with 0.
if user_age > 62: item_discount = 15 else: item_discount = 0
Executes the contents of a file containing Python code and makes the definitions from that file available.
import
The number of cars in a parking lot. float or int
int
The number of hairs on a person's head. float or int
int
{'Gorgon'} monsters.(horde)
intersection
Whitespace _____ important in program output.
is
Write an expression that concatenates the list feb_temps to the end of jan_temps.
jan_temps + feb_temps
Get the number of elements in the set elves.
len(elves)
Complete the program by echoing the second line of "readme.txt" my_file = open('readme.txt') lines = my_file.readlines() print( ___ ) # ...
lines[1]
Choose the container that best fits the described data. Student test scores that may later be adjusted, ordered from best to worst.
list
What should statement (B) be?max
max = val
The largest square root of any element in x. Use math.sqrt() to calculate the square root.
max([math.sqrt(i) for i in x])
Before the loop, the first input value is gotten. If that input was negative (unlike the data in the example above), the loop's body would _____.
not be executed
Fill in the missing code to perform the desired calculation. Compute the average number of kids. # Each list item is the number of kids in a family. num_kids = [1, 1, 2, 2, 1, 4, 3, 1] total = 0 for num in num_kids: total += ____ average = total / len(num_kids)
num
) Add a return statement to the function that returns the result of adding num1 and num2. def sum(num1, num2): return _________
num1 + num2
Fill in the missing code to perform the desired calculation. Assign num_neg to the number of below-freezing Celsius temperatures in the list. temperatures = [30, 20, 2, -5, -15, -8, -1, 0, 5, 35] num_neg = 0 for temp in temperatures: if temp < 0: ________
num_neg += 1
Fill in the missing Boolean operators. num_stores is between 10 and 20, inclusive. if (num_stores >= 10) and ( ____ ):
num_stores <= 20 or num_stores < 21
Complete the for loop statement by giving the loop variable and container. Iterate the string '911' using a variable called number. for ____ : # Loop body statements
number in '911'
Create a nested list nums whose only element is the list [21, 22, 23].
nums = [[21, 22, 23]]
Call a function named print_age, passing the value 21 as an argument.
print_age(21)
Write a function call using print_sum() to print the sum of x and 400 (providing the arguments in that order).
print_sum(x, 400)
Write the simplest range() function that generates the appropriate sequence of integers. Every 2nd integer from 10 to 20
range(10, 21, 2)
Write the simplest range() function that generates the appropriate sequence of integers. Every integer from 5 down to -5
range(5, -6, -1)
Write the simplest range() function that generates the appropriate sequence of integers. Every integer from 0 to 500.
range(501)
Add a return statement to the function that returns the cube of the argument (num*num*num). def cubed(num): __________________________
return num*num*num
Fill in the missing code to perform the desired calculation. Print scores in order from highest to lowest. Note: list is pre-sorted from lowest to highest. scores = [75, 77, 80, 85, 90, 95, 99] for scr in ____: print(scr, end=' ')
reversed(scores)
Type the operator to complete the desired expression. numDogs is either less than or greater than numCats numDogs ____ numCats
!=
The programmer on the right did not end the first sentence with a newline. What effect did that omission have?
"Join meeting" appears on the same line
What is returned by os.path.join('sounds', 'cars', 'honk.mp3') on Mac OS X? Use quotes in the answer.
"sounds/cars/honk.mp3"
What is returned by os.path.join('sounds', 'cars', 'honk.mp3') on Windows? Use quotes in the answer.
"sounds\\cars\\honk.mp3"
Complete the code using formatting specifiers to generate the described output. Assume price is 150. I saved $150! print('I saved $___________!' % price)
%d
Complete the code using formatting specifiers to generate the described output. Assume percent is 40. Buy now! Save 40%! print('Buy now! Save ___________!' % percent)
%d%%
What is the output of the following program? import os p = 'C:\\Programs\\Microsoft\\msword.exe' print(os.path.split(p))
('C:\\Programs\\Microsoft','msword.exe')
Which correctly passes two integer arguments for the function call calc_val(...)?
(99, 44+5)
Given a function definition: def calc_val(a, b, c): and given variables i, j, and k, which are valid arguments in the call calc_val(...)?
(k, i + j, 99)
Fill in the missing Boolean operators. Either wage is greater than 10 or age is less than 18. Use "or". Use > and < (not >= and <=). Use parentheses around sub-expressions. if ____ :
(wage > 10) or (age < 18)
Given a non-negative number x, which yields a number in the range -10 to 10?
(x % 21) - 10
Given a non-negative number x, which yields a number in the range 5 - 10?
(x % 6) + 5
Select the expression whose parentheses match the evaluation order of the original expression. x * y * z
(x * y) * z
Which get the tens digit of x. Ex: If x = 693, which yields 9?
(x / / 10) % 10
Select the expression whose parentheses match the evaluation order of the original expression. x / 2 + y / 2
(x / 2) + (y / 2)
Which correctly defines two parameters x and y for a function definition: def calc_val(...):?
(x, y)
Select the expression whose parentheses match the evaluation order of the original expression. z / 2-x
(z / 2 ) - x
For inputs 5 10 7 20 8 0, with what values should max be assigned?
-1,5,10,20
x is a non-negative number less than 100. if: ________ # evaluated to true else: # evaluated to false
0 <= x < 100
Use the following code to answer the questions below: for index, value in enumerate(my_list): print(index, value) If my_list = ['Greek', 'Nordic', 'Mayan'], what is the output of the program?
0 Greek 1 Nordic 2 Mayan
Type 1.0e-4 as a floating-point literal but not using scientific notation, with a single digit before and four digits after the decimal point.
0.0001
Type 7.2e-4 as a floating-point literal but not using scientific notation, with a single digit before and five digits after the decimal point.
0.00072
Given the following program, and the definition of print_face() above: print_face() print_face() How many print statements would execute in total?
6
Type 623.596 as a floating-point literal using scientific notation with a single digit before and five digits after the decimal point.
6.23596e2
What is the result of each expression? float("7.99")
7.99
What is the output of the following program? temps = [65, 67, 72, 75] temps.append(77) print(temps[-1])
77
What is the output of the following program? temps = [65, 67, 72, 75] temps.append(77) print(temps[-1])
77
How many times is the letter F (any case) in the following? If Fred is from a part of France, then of course Fred's French is good.
8
Suppose a new instruction were inserted as follows: ... z = x + y Add 1 more to z (new instruction) Put z to output (x=2, y=5, z=7) What would the last instruction then output to the screen?
8
Provide an expression using x.sort that sorts the list x accordingly. Arrange the elements of x from lowest to highest, comparing the upper-case variant of each element in the list.
x.sort(key=str.upper)
Select the expression whose parentheses match the evaluation order of the original expression. y + 2 * z
y + (2 * z)
Complete this statement to increment y: y = _____
y + 1
Convert each if-else statement to a single assignment statement using a conditional expression, using parentheses around the condition. Enter "Not possible" if appropriate. if x < 100: y = 0 else: y = x
y = 0 if (x < 100) else x or y = 0 if x < 100 else x
Write a relational expression using operator chaining. x is less than y but greater than z
z < x < y
Create a dictionary using braces that maps two names 'Bob' and 'Frank' to their ages, 27 and 75, respectively. For this exercise, make 'Bob' the first entry in the dict.
{'Bob': 27, 'Frank': 75}
Use braces to create a dictionary called ages that maps the names 'Bob' and 'Frank' to their ages, 27 and 75, respectively. For this exercise, make 'Bob' the first entry in the dict. ages =
{'Bob': 27, 'Frank': 75}
Executing the statements: address = '900 University Ave' address[0] = '6' address[1] = '2' is a valid way to change address to '620 University Ave'. True or False
False
Experienced programmers write an entire program before running and testing the code. True or False
False
Given the following code: nums = [0, 25, 50, 75, 100] 1) The result of evaluating nums[0:5:2] is [25, 75].
False
Given: def square_root(x): return math.sqrt(x) def print_val(x): print(x) return y = 1 + print_val(9.0) True or False
False
Given: def square_root(x): return math.sqrt(x) def print_val(x): print(x) return y = square_root() True or False
False
Given: def square_root(x): return math.sqrt(x) def print_val(x): print(x) return which of the following are valid statements? square_root(49.0) = z True or False
False
If a function's internal statements are revised, all function calls will have to be modified too. True or False
False
If a programmer defines a function called list(), the program will crash because there is already a built-in function with the same name. True or False
False
If my_func1() and my_func2() are defined functions, then the expression my_func1 + my_func2 returns a valid value. True or False
False
Indicate whether the expression evaluates to true or false. x is 5, y is 7. x == y
False
Indicate whether the expression evaluates to true or false. x is 5, y is 7. y != 7
False
Python comes pre-installed on Windows machines. True or False
False
Python is a high-level language that excels at creating exceptionally fast-executing programs. True or False
False
Python string objects are mutable, meaning that individual characters can be changed. True or False
False
Python was first implemented in 1960. True or False
False
Switches have gotten larger over the years. True or False
False
The expression my_func1(my_func2()) passes the my_func2 function object as an argument to my_func1. True or False
False
The list ['a', 'b', 3] is invalid because the list contains a mix of strings and integers. True or False
False
The main advantage of function stubs is that they ultimately lead to faster-running programs. True or False
False
The program could replace float() by int() without causing much change in computed values. True or False
False
The same name can not be in multiple namespaces. True or False
False
The variable my_dict created with the following code contains two keys, 'Bob' and 'A+'. my_dict = dict(name='Bob', grade='A+')
False
The write() method immediately writes data to a file.
False
When a function is called, copies of all the argument objects are made. True or False
False
Write a list comprehension that contains elements with the desired values. Use the name 'i' as the loop variable. Use parentheses around the expression or condition as necessary. Only negative values from the list x
[i for i in x if i < 0]
Type the operator to complete the desired expression. numDogs and numCats differ numDogs ____ numCats
!=
Write the simplest expression that captures the desired comparison. The character 'G' exists in the string my_str
'G' in my_str
What is the value of sys.argv[1] given the following command-line input (include quotes in your answer): python prog.py 'Tricia Miller' 26
'Tricia Miller'
What is the value of my_str after the following statements are evaluated: my_str = 'http://reddit.com/r/python' my_str = my_str[17:]
/r/python
5) What value is returned by min(my_list)?
0
50 % 2
0
A password must start with a letter, be at least 6 characters long, include a number, and include a special symbol. How many of the following passwords are valid? hello goodbye Maker1 dog!three Oops_again 1augh#3
0
Assume that my_list is [0, 5, 10, 15]. What value is returned by min(my_list)?
0
Count how many odd numbers (cnt_odd) there are. cnt_odd = for i in num: if i % 2 == 1: cnt_odd += 1
0
Fill in the missing field to complete the program. Count how many odd numbers (cnt_odd) there are. cnt_odd = ____ for i in num: if i % 2 == 1: cnt_odd += 1
0
What is the output of each print? print('%05d' % 150)
00150
Determine the final value of sale_bonus given the initial values specified below. if sales_type == 2: if sales_bonus < 5: sales_bonus = 10 else: sales_bonus = sales_bonus + 2 else: sales_bonus = sales_bonus + 1 sale_type = 1; sale_bonus = 0
1
What is the final value of num_items? bonus_val = 0 num_items = 1 if bonus_val > 10: num_items = num_items + 3
1
What is the final value of num_items? bonus_val = 5 if bonus_val < 12: num_items = 100 else: num_items = 200
100
With an initial savings of $10000 and interest rate of 0.05, what's the amount of savings at the beginning of year 4? Ignore cents and do not include the dollar sign ($).
11576
Indicate the value of x after the statements execute. x = 5 x = x + 7 x = ?
12
What is the final value of bonus_val? bonus_val = 11 if bonus_val < 12: bonus_val = bonus_val + 2 else: bonus_val = bonus_val + 10
13
What is the output of the following code? i1 = 1 while i1 < 19: i2 = 3 while i2 <= 9: print('%d%d' % (i1,i2), end=' ') i2 = i2 + 3 i1 = i1 + 10
13 16 19 113 116 119
Convert the binary number 10001000 to a decimal number.
136
num_atoms is initially 7. What is num_atoms after: num_atoms *= 2?
14
2) What value is returned by max(my_list)?
15
Assume that my_list is [0, 5, 10, 15]. What value is returned by max(my_list)?
15
Convert the binary number 00001111 to a decimal number.
15
If interest_rate is 3% and initial_savings are $5000, savings > $7500 after how many loop iterations?
15
Use input values of num_a = 15 and num_b = 10 in the above GCD program. Try to answer the questions by mentally executing the statements. If stuck, consider adding additional print statements to the program. What is the value of num_a before the first loop iteration?
15
What is the output of the following code? (Use "IL" for infinite loops.) x = 5 y = 18 while y >= x: print(y, end=' ') y = y - x
18 13 8
Determine the final value of numBoxes. num_boxes = 0 num_apples = 9 if num_apples < 10: if num_apples < 5: num_boxes = 1 else: num_boxes = 2 else if num_apples < 20: num_boxes = num_boxes + 1
2
Use input values of num_a = 15 and num_b = 10 in the above GCD program. Try to answer the questions by mentally executing the statements. If stuck, consider adding additional print statements to the program. How many loop iterations will the algorithm execute?
2
Determine the final value of z. x = 2.3 z = math.ceil(x)
3
What was variable num's value after the loop was done iterating?
3
12 / 4
3.0
Determine the output of each code segment. If the code produces an error, type None. Assume that my_dict has the following entries: my_dict = dict(bananas=1.59, fries=2.39, burger=3.50, sandwich=2.99) 1) my_dict.update(dict(soda=1.49, burger=3.69)) burger_price = my_dict.get('burger', 0) print(burger_price)
3.69
Determine the output of each code segment. If the code produces an error, type None. Assume that my_dict has the following entries: my_dict = dict(bananas=1.59, fries=2.39, burger=3.50, sandwich=2.99) my_dict.update(dict(soda=1.49, burger=3.69)) burger_price = my_dict.get('burger', 0) print(burger_price)
3.69
Consider the instruction: z = x + y. If x is 10 and y is 20, then z is assigned with _____.
30
Indicate the value of x after the statements execute. y = 30 x = y + 2 x = x + 1 x = ?
33
What is the final value of bonus_val? bonus_val = 11 if bonus_val < 12: bonus_val = bonus_val + 2 bonus_val = 3 * bonus_val else: bonus_val = bonus_val + 10
39
What is the length of the string "Santa"?
5
78 % 10
8
Type the operator to complete the desired expression. numDogs and numCats are the same numDogs ____ numCats
==
Type the operator to complete the desired expression. numDogs is 0 numDogs ____ 0
==
Type the operator to complete the desired expression. userChar is the character 'x'. userChar ____ 'x'
==
Type the operator to complete the desired expression. numDogs is greater than 10 numDogs ____ 10
>
Type the operator to complete the desired expression. numCars is 5 or greater numCars ____ 5
>=
Type the operator to complete the desired expression. numCars is greater than or equal to 5 numCars ____ 5
>=
Match conversion specifier term with the definition
A placeholder for a value in a string
What's the result of set(['A', 'Z'])?
A set that contains 'A' and 'Z'
What's the result of set([100, 200, 100, 200, 300])?
A set that contains 100,200,and 300.
Click the expression that is False. A. 'FRIDAY' == 'friday' B. '1' < '2' C. 'a' != 'b' < 'c'
A. 'FRIDAY' == 'friday'
Which illustrates the actual order of evaluation via parentheses? (num1 == 9) or (num2 == 0) and (num3 == 0) A. (num1 == 9) or ((num2 == 0) and (num3 == 0)) B. ((num1 == 9) or (num2 == 0)) and (num3 == 0) C. (num1 ==9) or (num2 == (0 and num3) == 0)
A. (num1 == 9) or ((num2 == 0) and (num3 == 0))
price = 155 age = Get next input If age > 60: price = price - 20 Put "Cost: " to output Put price to output If the input is 80, the output is Cost: _____ . A. 135 B. 155
A. 135
price = 155 age = Get next input If age > 60: price = price - 20 Put "Cost: " to output Put price to output If the input is 25, the output is Cost: _____ . A. 135 B. 155
A. 155
Given the description of a race, choose the condition that should be checked before each loop around the track. Loop as long as it is sunny. A. It is sunny. B. It is not sunny.
A. It is sunny.
Which comparison will compile AND consistently yield expected results? Variables have types denoted by their names. my_int == 42 A. OK B. Not OK
A. OK
Which comparison will compile AND consistently yield expected results? Variables have types denoted by their names. my_string == 'Hello' A. OK B. Not OK
A. OK
What is the purpose of variables? A. Store values for later use. B. Instruct the processor to execute an action. C. Automatically color text in the editor.
A. Store values for later use.
Dictionary entries can be modified in-place - a new dictionary does not need to be created every time an element is added, changed, or removed. A. True B. False
A. True
FIXME comments provide a way for a programmer to remember what needs to be added. A. True B. False
A. True
Given num_people = 10, num_cars = 2, user_key = 'q'. (num_people >= 20) or (num_cars > 1) A. True B. False
A. True
Given num_people = 10, num_cars = 2, user_key = 'q'. (user_key == 'x') or ((num_people > 5) and (num_cars > 1)) A. True B. False
A. True
Given num_people = 10, num_cars = 2, user_key = 'q'. not (user_key == 'a') A. True B. False
A. True
Given num_people = 10, num_cars = 2, user_key = 'q'. num_people >= 10 A. True B. False
A. True
Given num_people = 10, num_cars = 2, user_key = 'q'. user_key != 'a' A. True B. False
A. True
Given the following code: nums = [0, 25, 50, 75, 100] The result of evaluating nums[0:-1:3] is [0, 75]. A. True B. False
A. True
Incremental programming may help reduce the number of errors in a program. A. True B. False
A. True
Iterating over a list and deleting elements from the original list might cause a logic program error. A. True B. False
A. True
Nested dictionaries are a flexible way to organize data A. True B. False
A. True
The expression {'D1': {'D2': 'x'}} is valid. A. True B. False
A. True
The sort() method modifies a list in-place. A. True B. False
A. True
The standard number of spaces to use for indentation is 4. A. True B. False
A. True
Another word for program.
Application
date = 'April {}, {}' print(date.format(22, 2020))
April 22, 2020
print('April {}, {}'.format(22, 2020))
April 22, 2020
date = 'April {}, {}' print(date.format(22, 2020)) print(date.format(23, 2024))
April 22, 2020 April 23, 2024
Assume the variable my_str is 'Agt2t3afc2kjMhagrds!'. What is the result of the expression my_str[::2]
AttackMars
Which pair of statements print output on the same line? A. print('Halt!') print('No access!') B. print('Halt!', end=' ') print('No access!') C. print(Halt!, end=' ') print(No Access!, end=' ')
B. print('Halt!', end=' ') print('No access!')
Which illustrates the actual order of evaluation via parentheses? not (bats < birds) or (birds < insects) A. not ((bats < birds) or (birds < insects) B. (not (bats < birds)) or (birds < insects) C. ((not bats) < birds) or (birds < insects)
B. (not (bats < birds)) or (birds < insects)
Dictionaries can contain up to three levels of nesting. A. True B. False
B. False
Consider the if-else if-else structure below: If x equals -1 Put "Disagrees" to output Else If x equals 0 Put "Neutral" to output Else If x equals 1 Put "Agrees" to output Else Put "Invalid entry" to output Could the programmer have written the three branches in the order x equals 1, x equals 0, and x equals -1, and achieved the same results? A. No B. Yes
B. Yes
If party of 1: counter Else if party of 2: a small table Else: a large table A party of 2 is sat at _____ . A. the counter B. a small table
B. a small table
Indicate whether a while loop or for loop should be used in the following scenarios: Iterate 1500 times A. while B. for
B. for
Which illustrates the actual order of evaluation via parentheses? not green == red A. (not green) == red B. not (green == red) C. (not green =)= red
B. not (green == red)
Consider the if-else if-else structure below: If x equals -1 Put "Disagrees" to output Else If x equals 0 Put "Neutral" to output Else If x equals 1 Put "Agrees" to output Else Put "Invalid entry" to output If x is 1, what is output? A. Disagrees B. Neutral C. Agrees D. Invalid entry
C. Agrees
Consider the if-else if-else structure below: If x equals -1 Put "Disagrees" to output Else If x equals 0 Put "Neutral" to output Else If x equals 1 Put "Agrees" to output Else Put "Invalid entry" to output In the code above, suppose a programmer, after the third branch (x equals 1), inserts a new branch: Else If x equals -1 ... When might that new branch execute? A. When x is -1 B. When x is 1 C. Never
C. Never
weight = Get next input If weight < 150: Put "Can ride." to output Else: Put "Can't ride." to output What value causes "Done." to NOT be output? A. 130 B. 160 C. No such value
C. No such value
Which expression checks if the value 10 exists in the dictionary my_dict? A. 10 in my_dict['key'] B. 10 in my_dict C. None of the above
C. None of the above
Translates a high-level language program into low-level machine instructions.
Compiler
To teach precedence rules, these questions intentionally omit parentheses; good style would use parentheses to make order of evaluation explicit. Which operator is evaluated first? w + 3 > x - y * z A. + B. - C. > D. *
D. *
weight = Get next input If weight < 150: Put "Can ride." to output Else: Put "Can't ride." to output What input value causes both the if branch to execute (outputting "Can ride") and the else branch to execute (outputting "Can't ride")? A. 149 B. 150 C. 151 D. No such value
D. No such value
Match Conversion type with the definition
Determines how to display a value assigned to a conversion specifier
Assume the function below is defined: def split_check(amount, num_people, tax_rate, tip_rate): # ... What value is passed as the num_people argument in the statement split_check(60.52, tax_rate=.07, 2, tip_rate=0.18)? Answer ERROR if an error occurs.
ERROR
What's the result of set(10, 20, 25)?
ERROR SYNTAX
Find the syntax errors. Assume variable num_dogs exists. print(Woof!) Error or No Error
Error
Assume variable age = 22, pet = "dog", and pet_name = "Gerald". What is the output of print(pet_name, 'the', pet, 'is', age)
Gerald the dog is 22
What is the output of each print? print('%4s %08d' % ('ID:', 860552))
ID: 00860552
What is the output of the following code? (Use "IL" for infinite loops.) x = 10 while x != 3: print(x, end=' ') x = x / 2
IL
print("Friday, Friday")
IndentationError
Indicate which assignment statements are valid. x + 1 = 3 Valid or Invalid
Invalid
Indicate which assignment statements are valid. x + y = y + x Valid or Invalid
Invalid
Which of the following are valid names? 3rd_place Valid or Invalid
Invalid
Which of the following are valid names? num cars Valid or Invalid
Invalid
Which of the following are valid names? third_place! Valid or Invalid
Invalid
A series of 0s and 1s, stored in memory, that tells a processor to carry out a particular operation like a multiplication.
Machine Instruction
Which instruction completes the program to compute a triangle's area? base = Get next input height = Get next input Assign x with base * height _____ Put x to output
Multiply x by 1/2
What is the output of print('My name is \'Tator Tot\'.')
My name is 'Tator Tot'.
Indicate whether the expression evaluates to true or false. x is 5, y is 7. Is x =< y a valid expression?
No
Indicate which items are string literals. 674
No
Match Precision term with the definition
Optional component that determines the number of digits to include to the right of a floating point value
print('Today is Monday")
SyntaxError
Determine the output of the following code snippets. If an error would occur, type "error". month = 'April' day = 22 print('Today is {month} {0}'.format(day, month=month))
Today is April 22
month = 'April' day = 22 print('Today is {month} {0}'.format(day, month=month))
Today is April 22
Where was the decision point for whether to loop: At the top of the street or bottom?
Top
'HTTPS://google.com'.startswith('HTTP') True or False
True
'LINCOLN, ABRAHAM'.isupper() True or False
True
2) The result of evaluating nums[0: -1 :3] is [0, 75].
True
3) What value is returned by any(my_list)?
True
A bit can only have the value of 0 or 1. True or False
True
Executing the following statements produces a KeyError: prices = {'apples': 1.99, 'oranges': 1.49, 'kiwi': 0.79} del prices['limes'] True or False
True
Indicate which are valid expressions. x and y are variables. 2 * (x - y) Valid or Not valid
Valid
Indicate which assignment statements are valid. x = y Valid or Invalid
Valid
Indicate which assignment statements are valid. x = y + 2 Valid or Invalid
Valid
Does the expression correctly capture the intended behavior? 6 plus num_items: 6 + num_items Yes or No
Yes
Does the expression correctly capture the intended behavior? The negative of user_val: -user_val Yes or No
Yes
Does the expression correctly capture the intended behavior? total_days divided by 12: total_days / 12 Yes or No
Yes
Indicate which items are string literals. "a"
Yes
Indicate which items are string literals. "ok"
Yes
Fill in the missing Boolean operators. max_cars is between 0 and 100. if (max_cars > 0) ____ (max_cars < 100):
and
Fill in the missing Boolean operators. num is a 3-digit positive integer, such as 100, 989, or 523, but not 55, 1000, or -4. For most direct readability, your expression should compare directly with the smallest and largest 3-digit number. if (num >= 100) ____ :
and (num <= 999) or and (num < 1000) or and num <= 999 or and num < 1000
Write a statement that assigns the average of the elements of prices to the variable avg_price.
avg_price = sum(prices)/len(prices)
Write a statement that creates an empty list called class_grades.
class_grades = []
Count how many negative numbers (cnt_neg) there are. cnt_neg = 0 for i in num: if i < 0:
cnt_neg += 1
Fill in the missing field to complete the program. Count how many negative numbers (cnt_neg) there are. cnt_neg = 0 for i in num: if i < 0:
cnt_neg += 1
What should statement (B) be?
count = count+1
Complete the statement to create a csv module reader object to read myfile.csv. import csv with open('myfile.csv', 'r') as myfile: csv_reader =
csv.reader(myfile)
For a program run as "python scriptname data.txt", what is sys.argv[1]? Do not use quotes in the answer.
data.txt
Choose the container that best fits the described data. Student names and their current grades
dict
The output of the following is [13, 7, 5]: primes = [5, 13, 7] primes.sort() print(primes)
false
Use of a with statement is not recommended most of the time when opening files
false
What does the call os.path.isfile('C:\\Program Files\\') return?
false
all elements of a list must have the same type
false
dictionaries can contain up to three levels of nesting
false
Loop iterates 2 times. i = 1 while : # Loop body statements go here i = i + 1
i <= 2
If num_people is greater than 10, execute group_size = 2 * group_size. Otherwise, execute group_size = 3 * group_size and num_people = num_people - 1.
if num_people > 10: group_size = 2 * group_size else: group_size = 3 * group_size num_people = num_people - 1
Open "myfile.txt" as read-only in binary mode. f =
open('myfile.txt', 'rb')
Complete the statement to open the file "readme.txt" for reading. my_file = _____
open('readme.txt')
Create a new variable "point" that is a tuple containing the strings 'X' and 'Y'.
point = ('X', 'Y')
Complete the for loop statement by giving the loop variable and container. Iterate over the list my_prices using a variable called price. for ____ : # Loop body statements
price in my_prices
Which prints the value of the first_name variable?
print(first_name)
Print the length of the string variable first_name.
print(len(first_name))
Write a statement that prints the value of the variable num_people.
print(num_people)
Use a raw string literal to assign "C:\file.doc" to my_str. my_str = ____________
r'C:\file.doc' or r"C:\file.doc"
Write an expression using the random.randint() that returns a number between 0 and 5
random.randint(0, 5)
Write an expression using the random.randint() that returns a number between 0 and 5.
random.randint(0, 5)
Complete the statement such that the program prints the destination of each flight in myfile.csv. import csv with open('myfile.csv', 'r') as myfile: csv_reader = csv.reader(myfile) for row in csv_reader: print( )
row[1]
Assume the following list has been created scores = [ [75, 100, 82, 76], [85, 98, 89, 99], [75, 82, 85, 5] ] Write an indexing expression that gets the element from scores whose value is 100.
scores[0][1]
What should expression (A) be?
val<0
Complete the loop expressions, using a single operator in your expression. Use the most straightforward translation of English to a expression. Iterate while x is greater-than-or-equal to 0. while ____ : # Loop body statements go here
x >= 0
Write the simplest expression that captures the desired comparison. x is a key in the dict my_dict
x in my_dict
A pass statement should be used in a function stub when the programmer wants the stub to stop program execution when called. True or False
False
A programmer can pass only string arguments to a user-defined function. True or False
False
Assignments to a parameter name inside a function affect the code outside the function. True or False
False
Assume that my_list is [0, 5, 10, 15]. What value is returned by all(my_list)?
False
Avoiding redundancy means to avoid calling a function from multiple places in a program. True or False
False
Comments are required in a program. True or False
False
Dictionary entries are ordered by position. True or False
False
Each iteration of the loop will see y_loc increase. True or False
False
A sorted collection of integers might best be contained in a list. True or False
True
Which if-else branch will execute if the user types "Goodbye"? Valid answers are branch 0, 1, 2 or none.
none
Arrange the elements of x from lowest to highest, comparing the upper-case variant of each element in the list.
x.sort(key=str.upper)
Complete the code using formatting specifiers to generate the described output. Use the indicated variables. Assume item is 'backpack' and weight is 5.2. The backpack is 5.200000 pounds. print('The %s is ____________ pounds.' % (item, weight))
%f
Complete the code using formatting specifiers to generate the described output. Use the indicated variables. Assume item is 'burrito' and price is 5. The burrito is $5 print('The _______________ is $%d' % (item, price))
%s
Write a statement that joins all the elements of my_list together, without any separator character between elements
''.join(my_list)
Determine the output of the following code: my_str = 'The cat in the hat' print(my_str[3:7])
''cat '' means there is a space there
Write a statement that uses the join() method to set my_str to 'images.google.com', using the list x = ['images', 'google', 'com'] my_str = _______________
'.'.join(x)
What is the result of each expression? str(99)
'99'
Assume that variable my_bytes is b"\x00\x04\xff\x00". Complete the statement to assign my_num to the 4-byte integer obtained by unpacking my_bytes. Use the byte ordering given by ">" my_num = struct.unpack( )
'>I', my_bytes
Complete the statement to pack an integer variable "my_num" into a 2-byte sequence assigned to my_bytes. Use the byte ordering given by ">" my_bytes = struct.pack( )
'>h', my_num
Complete the function call so that the output of the program is John is: age: 10 gender: m def stats(name, **info): print(name, 'is:') for key, value in info.items(): print('%s: %s' % (key, value)) stats(_____________________)
'John', age=10, gender='m' or 'John', age='10', gender='m' or 'John', gender='m', age=10 or 'John', gender='m', age='10'
What is the value of sys.argv[1] given the following command-line input (include quotes in your answer): python prog.py Tricia Miller 26
'Tricia'
Complete the code to output \\ print(_________)
'\\\\' or r'\\'
Data will be appended to the end of existing contents. f = open('myfile.txt', ___)
'a'
Existing contents will be read, and new data will be appended. f = open('myfile.txt', ____ )
'a+'
Open "data.txt" as read-only in binary mode. f = open('data.txt', ____)
'rb'
Fill in the arguments to os.path.join to assign file_path as "subdir\\output.txt" (on Windows). file_path = os.path.join(_____)
'subdir', 'output.txt'
Data will be written to a new file. f = open('myfile.txt', ____ )
'w'
Assume the function below is defined: def split_check(amount, num_people, tax_rate, tip_rate): # ... What value is passed as the tax_rate argument in the statement split_check(60.52, 5, .07, tip_rate=0.18)? Answer ERROR if an error occurs.
0.07
Assume the function below is defined: def split_check(amount=10, num_people=2, tax_rate=0.095, tip_rate=0.18): # ... When entering answers, use the same number of significant digits as the default parameter values in the split_check() definition. What will the parameter tax_rate be assigned for the following call? Type ERROR if the call is invalid. split_check(amount=49.50, num_people=3)
0.095
The following function is defined: def split_check(amount, num_people, tax_rate=0.095, tip_rate=0.15) # ... What will the parameter tax_rate be assigned for the following call? Type ERROR if the call is invalid. split_check(65.50, 3)
0.095
The following function is defined: def split_check(amount, num_people, tax_rate=0.095, tip_rate=0.15) # ... What will the parameter tax_rate be assigned for the following call? Type ERROR if the call is invalid. split_check(65.50, 3, 0.125)
0.125
5 / 10
0.5
What does ebay_fee() return if its argument is 0.0 (show your answer in the form #.#)?
0.5
Convert the decimal number 17 to an 8-bit binary number.
00010001
What is the output of each print? print('%05d' % 75.55)
00075
Convert the decimal number 51 to an 8-bit binary number.
00110011
What is the output of each print? print('%05.1f' % 75.55)
075.5
51 % 2
1
Given the following program, and the definition of print_face() above: print_face() print_face() How many function definitions of print_face are there?
1
Given the following while loop, what is the value assigned to variable z for the given values of variables a, b and c? mult = 0 while a < 10: mult = b * a if mult > c: break a = a + 1 z = a a = 1, b = 1, c = 0
1
How many differences are in these two lines? Printing A linE is done using printInPrinting A linE is done using print1n
1
What is the result of each expression? int(1.55)
1
Given: def print_sum(num1, num2): print(num1, '+', num2, 'is', (num1 + num2)) What will be printed for the following function call? print_sum(1, 2)
1 + 2 is 3
What is the output of the following code? (Use "IL" for infinite loops.) x = 1 y = 3 z = 5 while not (y < x < z): print(x, end=' ') x = x + 1
1 2 3
Type 0.000001 as a floating-point literal using scientific notation with a single digit before and after the decimal point.
1.0e-6
Determine the final value of sale_bonus given the initial values specified below. if sales_type == 2: if sales_bonus < 5: sales_bonus = 10 else: sales_bonus = sales_bonus + 2 else: sales_bonus = sales_bonus + 1 sale_type = 2; sale_bonus = 4
10
Given the following code, how many times will the print statement execute? for i in range(5): for j in range(10, 12): print('%d%d' % (i1, i2))
10
Given the list nums = [[10, 20, 30], [98, 99]], what does nums[0][0] evaluate to?
10
Type the value held in the variable after the assignment statement, given: num_items = 5 item_weight = 0.5 For any floating-point answer, type answer to tenths. Ex: 8.0, 6.5, or 0.1 num_items + num_items.
10
What is the final value of employee_bonus for each given value of num_sales? if num_sales == 0: employee_bonus = 0 elif num_sales == 1: employee_bonus = 2 elif num_sales == 2: employee_bonus = 5 else: employee_bonus = 10 num_sales is 7
10
x = 9 y = x + 1 What is y?
10
x = 9 y = x + 1 x = 5 What is y?
10
What is the output of print('10...\n9...')
10... 9...
Consider the following program: nums = [10, 20, 30, 40, 50] for pos, value in enumerate(nums): tmp = value / 2 if (tmp % 2) == 0: nums[pos] = tmp What's the final value of nums[1]?
10.0
num_atoms is initially 7. What is num_atoms after: num_atoms += 5?
12
weight = Get next input If weight < 150: Put "Can ride." to output Else: Put "Can't ride." to output What is output when the input is 150? A. Can ride. Done. Can't ride. Done. B. Can ride. Can't ride. Done. C. Can't ride. Done.
150 < 150 is false, so the branch executes.
Determine the final value of z. z = 4.5 z = math.pow(math.floor(z), 2.0)
16.0
Indicate the value of x after the statements execute. x = 2 y = 3 x = x * y x = x * y x = ?
18
Type the value held in the variable after the assignment statement, given: num_items = 5 item_weight = 0.5 For any floating-point answer, type answer to tenths. Ex: 8.0, 6.5, or 0.1 item_weight * num_items.
2.5
Given the following code, how many times will the inner loop body execute? for i in range(2): for j in range(3): # Inner loop body
6
Determine the output of each code segment. If the code produces an error, type None. Assume that my_dict has the following entries: my_dict = dict(bananas=1.59, fries=2.39, burger=3.50, sandwich=2.99) my_dict['burger'] = my_dict['sandwich'] val = my_dict.pop('sandwich') print(my_dict['burger'])
2.99
my_dict['burger'] = my_dict['sandwich'] val = my_dict.pop('sandwich') print(my_dict['burger'])
2.99
What is the final value of num_items? bonus_val = 12 if bonus_val < 12: num_items = 100 else: num_items = 200
200
Determine the final value of numBoxes. num_boxes = 0 num_apples = 9 if num_apples < 10: num_boxes = 2 if num_apples < 20: num_boxes = num_boxes + 1
3
Given the following program, and the definition of print_face() above: print_face() print_face() How many print statements exist in the program code?
3
How many times will the loop body execute? x = 3 while x >= 1: # Do something x = x - 1
3
How many typos are in the following? Keep calmn and cary one.
3
If I and E are adjacent, I should come before E, except after C (where E should come before I). How many violations are in the following? BEIL CEIL ZIEL YIEIK TREIL
3
What is the final value of num_items? Write "Error" if the code results in an error. num_items = 3 if num_items > 10: num_items = num_items + 1
3
Assume that my_list is [0, 5, 10, 15]. 1) What value is returned by sum(my_list)?
30
Assume that my_list is [0, 5, 10, 15]. What value is returned by sum(my_list)?
30
For a single execution of the program, how many user-defined method calls execute?
4
For the given input sequence, what is the final value of num_values?
4
How many actual (non-sentinel) values are given in the first input sequence?
4
What is the final value of num_items? bonus_val = 19 num_items = 1 if bonus_val > 10: num_items = num_items + 3
4
What is the final value of num_items? Write "Error" if the code results in an error. num_items = 3 if num_items == 3: num_items = num_items + 1
4
x = Get next input y = Get next input z = x + y Put z to output The program has _____ instructions.
4
Determine the final value of z. z = 15.75 z = math.sqrt(math.ceil(z))
4.0
Select the expression whose parentheses match the evaluation order of the original expression. What is total_count after executing the following? num_items = 5 total_count = 1 + (2 * num_items) * 4
41
Assume a function def print_num(user_num): simply prints the value of user_num without any space or newline. What will the following output? print_num(43) print_num(21)
4321
For any call to ebay_fee(), how many assignment statements will execute?
5
Given the following while loop, what is the value assigned to variable z for the given values of variables a, b and c? mult = 0 while a < 10: mult = b * a if mult > c: break a = a + 1 z = a a = 4, b = 5, c = 20
5
Use input values of num_a = 15 and num_b = 10 in the above GCD program. Try to answer the questions by mentally executing the statements. If stuck, consider adding additional print statements to the program. What is num_a after the first and before the second iteration?
5
Use input values of num_a = 15 and num_b = 10 in the above GCD program. Try to answer the questions by mentally executing the statements. If stuck, consider adding additional print statements to the program. What is num_b after the second and before the third iteration?
5
What is the final value of employee_bonus for each given value of num_sales? if num_sales == 0: employee_bonus = 0 elif num_sales == 1: employee_bonus = 2 elif num_sales == 2: employee_bonus = 5 else: employee_bonus = 10 num_sales is 2
5
Complete the code so that new_var is equal to the entered number plus 5. my_var = int(input()) new_var =_________________
5 + my_var
Type the value held in the variable after the assignment statement, given: num_items = 5 item_weight = 0.5 For any floating-point answer, type answer to tenths. Ex: 8.0, 6.5, or 0.1 (num_items + num_items) * item_weight
5.0
Type 540,000,000 as a floating-point literal using scientific notation with a single digit before and after the decimal point.
5.4e8
What is the final value of num_items? bonus_val = 15 num_items = 44 if bonus_val < 12: num_items = num_items + 3 else: num_items = num_items + 6 num_items = num_items + 1
51
Given a function definition: def calc_val(a, b, c): what value is assigned to b during this function call: calc_val(42, 55, 77)
55
596 % 10
6
Determine the final value of sale_bonus given the initial values specified below. if sales_type == 2: if sales_bonus < 5: sales_bonus = 10 else: sales_bonus = sales_bonus + 2 else: sales_bonus = sales_bonus + 1 sale_type = 2; sale_bonus = 7
9
x = 9 y = x + 1 What is x?
9
print('{0}:{1}'.format(9, 43))
9:43
print('{0}:{0}'.format(9, 43))
9:9
Type the operator to complete the desired expression. centsLost is a negative number centsLost ____ 0
<
What sequence is generated by range(2, 5)? A. 2 3 4 B. 2 3 4 5 C. 0 1 2 3 4
A. 2 3 4
weight = Get next input If weight < 150: Put "Can ride." to output Else: Put "Can't ride." to output What is output when the input is 90? A. Can ride. Done. B. Can't ride. Done.
A. Can ride. Done.
x = Get next input y = Get next input If x > y: max = x Else: max = y When the input is -3 0, which branch executes? A. If B. Else
A. Else
x = Get next input y = Get next input If x > y: max = x Else: max = y When the input is 99 98, which branch executes? A. If B. Else
A. If
A program can modify the elements of an existing list. A. True B. False
A. True
A programmer can iterate over a copy of a list to safely make changes to that list. A. True B. False
A. True
The statement my_list1 + my_list2 produces a new list. A. True B. False
A. True
not x == 3 evaluates as not (x == 3)? A. Yes B. No
A. Yes
val = Get next input If val < 0: val = -val If the input is -6, does the branch execute? A. Yes B. No
A. Yes
w + x == y + z evaluates as (w + x) == (y + z)? A. Yes B. No
A. Yes
Assume that the variable song has the value: song = "I scream; you scream; we all scream, for ice cream.\n" What is the result of song.split('scream')? A. ['I ', '; you ', '; we all ', ', for ice cream.\n'] B. ['I scream; you scream; we all scream, for ice cream.\n'] C. ['I', 'you', 'we all', 'for ice cream.\n']
A. ['I ', '; you ', '; we all ', ', for ice cream.\n']
Assume that the variable song has the value: song = "I scream; you scream; we all scream, for ice cream.\n" What is the result of song.split('\n')? A. ['I scream; you scream; we all scream, for ice cream.', ''] B. ['I scream; you scream;\n', 'we all scream,\n', 'for ice cream.\n'] C. ['I scream; you scream; we all scream, for ice cream']
A. ['I scream; you scream; we all scream, for ice cream.', '']
If party of 1: counter Else if party of 2: a small table Else: a large table A party of 5 is sat at _____ . A. a large table B. nowhere
A. a large table
Given the variable num_cars = 9, which statement prints 9? A. print(num_cars) B. print("num_cars")
A. print(num_cars)
If party of 1: counter Else if party of 2: a small table Else: a large table A party of 1 is sat at _____ . A. the counter B. a small table
A. the counter
Indicate whether a while loop or for loop should be used in the following scenarios: Iterate as long as the user-entered string c is not q. A. while B. for
A. while
Indicate whether a while loop or for loop should be used in the following scenarios: Iterate until the values of x and y are equal, where x and y are changed in the loop body. A. while B. for
A. while
x = 0 y = 5 z = ? while x < y: if x == z: print('x == z') break x += 1 else: print('x == y') What is the output of the code if z is 3? A. x == z B. x == y
A. x == z
Assume the variable my_str is 'Agt2t3afc2kjMhagrds!'. What is the result of the expression my_str[0:5:1]?
Agt2t
Click the expression that is True. A. {'Henrik': '$25'} == {'Daniel': '$25'} B. (1, 2, 3) > (0, 2, 3) C. [1, 2, 3] >= ['1', '2', '3']
B. (1, 2, 3) > (0, 2, 3)
Which expression checks whether the list my_list contains the value 15? A. 15 in my_list[0] B. 15 in my_list C. my_list['15'] != 0
B. 15 in my_list
A programmer can start new code blocks at any point in the code, as long as the indentation for each line in the block is consistent. A. True B. False
B. False
All elements of a list must have the same type. A. True B. False
B. False
Given num_people = 10, num_cars = 2, user_key = 'q'. (num_people >= 10) and (num_cars > 2) A. True B. False
B. False
Given num_people = 10, num_cars = 2, user_key = 'q'. not ((num_people >= 10) and (num_cars > 2)) A. True B. False
B. False
Given num_people = 10, num_cars = 2, user_key = 'q'. not (num_cars < 5) A. True B. False
B. False
Once a program is complete, one would expect to see several FIXME comments. A. True B. False
B. False
The output of print(sorted([-5, 5, 2])) is [2, -5, 5]. A. True B. False
B. False
The output of the following is [13, 7, 5]: primes = [5, 13, 7] primes.sort() print(primes) A. True B. False
B. False
The size of a list is determined when the list is created and can not change. A. True B. False
B. False
The statement del my_list[2] produces a new list without the element in position 2. A. True B. False
B. False
The variable my_dict created with the following code contains two keys, 'Bob' and 'A+'. my_dict = dict(name='Bob', grade='A+') A. True B. False
B. False
To teach precedence rules, these questions intentionally omit parentheses; good style would use parentheses to make order of evaluation explicit. To what does this expression evaluate, given x = 4, y = 7. x == 3 or x + 1 > y A. True B. False
B. False
Consider the if-else if-else structure below: If x equals -1 Put "Disagrees" to output Else If x equals 0 Put "Neutral" to output Else If x equals 1 Put "Agrees" to output Else Put "Invalid entry" to output If x is -2, what is output? A. Disagrees B. Invalid entry C. (Nothing is output)
B. Invalid entry
Given the description of a race, choose the condition that should be checked before each loop around the track. Loop as long as it is not raining. A. It is raining. B. It is not raining.
B. It is not raining.
price = 155 age = Get next input If age > 60: price = price - 20 Put "Cost: " to output Put price to output If the input is 60, will the branch be taken? A. Yes B. No
B. No
val = Get next input If val < 0: val = -val If the input is 0, does the branch execute? A. Yes B. No
B. No
Which comparison will compile AND consistently yield expected results? Variables have types denoted by their names. my_double == 3.25 A. OK B. Not OK
B. Not OK
Given the description of a race, choose the condition that should be checked before each loop around the track. Loop 10 times. A. Number of completed laps is 0 or greater. B. Number of completed laps is less than 10. C. Number of completed laps equals 10.
B. Number of completed laps is less than 10.
To teach precedence rules, these questions intentionally omit parentheses; good style would use parentheses to make order of evaluation explicit. Which operator is evaluated first? not y and x A. and B. not
B. not
x = 0 y = 5 z = ? while x < y: if x == z: print('x == z') break x += 1 else: print('x == y') What is the output of the code if z is 10? A. x == z B. x == y
B. x == y
x = Get next input y = Get next input If x > y: max = x Else: max = y If the inputs are 5 5, does max get assigned with x or y? A. x B. y
B. y
x = Get next input y = Get next input If x > y: max = x Else: max = y The if branch assigns max = x. The else branch assigns max = ? A. x B. y
B. y
On the right, why did the "Reminder..." text appear on the same line as the separator text "------"?
Because the programmer didn't end the output with a newline
What is the output of the following code? (Use "IL" for infinite loops.) x = 0 while x > 0: print(x, end=' ') x = x - 1 print('Bye')
Bye
Click the expression that is False. A. 5 <= 5.0 B. 10 != 9.999999 C. (4 + 1) != 5.0
C. (4 + 1) != 5.0
Which illustrates the actual order of evaluation via parentheses? bats < birds or birds < insects A. ((bats < birds) or birds) < insects B. bats < (birds or birds) < insects C. (bats < birds) or (birds < insects)
C. (bats < birds) or (birds < insects)
To teach precedence rules, these questions intentionally omit parentheses; good style would use parentheses to make order of evaluation explicit. In what order are the operators evaluated? w + 3 != y - 1 and x A. +, !=, -, and B. +, -, and, != C. +, -, !=, and
C. +, -, !=, and
What sequence is generated by range(7)? A. 0 1 2 3 4 5 6 7 B. 1 2 3 4 5 6 C. 0 1 2 3 4 5 6
C. 0 1 2 3 4 5 6
Assume that the variable song has the value: song = "I scream; you scream; we all scream, for ice cream.\n" What is the result of song.split()? A. ['I scream; you scream; we all scream, for ice cream.\n'] B. ['I scream; you scream;', 'we all scream,', 'for ice cream.\n'] C. ['I', 'scream;', 'you', 'scream;', 'we', 'all', 'scream,' 'for', 'ice', 'cream.']
C. ['I', 'scream;', 'you', 'scream;', 'we', 'all', 'scream,' 'for', 'ice', 'cream.']
Which statement reads a user-entered string into variable num_cars? A. num_cars = "input()" B. input() = num_cars C. num_cars = input()
C. num_cars = input()
Which statement prints: Welcome!? A. print(Welcome!) B. print('Welcome!") C. print('Welcome!')
C. print('Welcome!')
The following function is defined: def split_check(amount, num_people, tax_rate=0.095, tip_rate=0.15) # ... What will the parameter num_people be assigned for the following call? Type ERROR if the call is invalid. split_check(12.50, tip_rate=0.18)
ERROR
The following function is defined: def split_check(amount, num_people, tax_rate=0.095, tip_rate=0.15) # ... What will the parameter num_people be assigned for the following call? Type ERROR if the call is invalid. split_check(tip_rate=0.18, 12.50, 4)
ERROR
# Gravitational constants for various planets earth_g = 9.81 # m/s^2 mars_g = 3.71 if __name__ == '__main__': print('Earth constant:', earth_g) print('Mars constant:', mars_g) What is the output when running the following commands? $ python constants.py
Earth constant: 9.81 Mars constant: 3.71
Find the syntax errors. Assume variable num_dogs exists. print("Dogs: " num_dogs) Error or No Error
Error
Find the syntax errors. Assume variable num_dogs exists. print('Woof!") Error or No Error
Error
A global statement must be used whenever a global variable is to be read or written in a function. True or False
False
A global variable's scope extends from a function definition's ending colon ":" to the end of the function
False
A local variable's scope extends from a function definition's ending colon ":" to the end of the function True or False
False
A major drawback of Python is that Python code is more difficult to read than code in most other programming languages. True or False
False
as_constant = 8.3144621 # Joules / (mol*Kelvin) def convert_to_temp(pressure, volume, mols): """Convert pressure, volume, and moles to a temperature""" return (pressure * volume) / (mols * gas_constant) press = float(input('Enter pressure (in Pascals): ')) vol = float(input('Enter volume (in cubic meters): ')) mols = float(input('Enter number of moles: ')) print('Temperature = %02f K' % convert_to_temp(press, vol, mols)) Function convert_to_pres() would likely return (temp * volume) / (mols * gas_constant). True or False
False
he output of the following program is 'meow': def cat(): print('meow') def pig(): print('oink') cat = pig cat()
False
int and float types can hold the exact same values. True or False
False
import constants import math height = int(input('Height in meters: ')) # Meters from planet if __name__ == '__main__': print('Earth:', math.sqrt(2 * height / constants.earth_g), 'seconds') print('Mars:', math.sqrt(2 * height / constants.mars_g), 'seconds') What is the output when running the following commands? $ python fall_time.pyv
Height in meters: Earth: 0.7820618870057751 seconds Mars: 1.271711710197892 seconds
Determine the output of the following code snippets. If an error would occur, type "error". print('Hi {{{0}}}!'.format('Bilbo'))
Hi {Bilbo}!
Does the expression correctly capture the intended behavior? 5 times i: 5i Yes or No
No
Does the expression correctly capture the intended behavior? 6 times num_items: 6 x num_items Yes or No
No
Does the expression correctly capture the intended behavior? n factorial n! Yes or No
No
Does the final value of max depend on the order of inputs? In particular, would max be different for inputs 22 5 99 3 0 versus inputs 99 3 5 22 0?
No
If the input value is 0, does the loop body execute?
No
Indicate whether the expression evaluates to true or false. x is 5, y is 7. Is x <> y a valid expression?
No
Suppose the first input was 0. Would values_sum / num_values be 0?
No
Find the syntax errors. Assume variable num_dogs exists. print("Hello + friend!") Error or No Error
No Error
Convert each if-else statement to a single assignment statement using a conditional expression, using parentheses around the condition. Enter "Not possible" if appropriate. if x < 1: y = x else: z = x
Not possible
Rewrite the statement using a compound operator, or type: Not possible num_items = box_count + 1
Not possible
Indicate which are valid expressions. x and y are variables. 2 + (xy) Valid or Not valid
Not valid
Indicate which are valid expressions. x and y are variables. 2x Valid or Not valid
Not valid
Indicate which are valid expressions. x and y are variables. y = x + 1 Valid or Not valid
Not valid
Match '0' conversion flag term with the definition
Optional component that indicates numeric conversion specifiers should add leading 0s if the minimum field width is also specified
The programmer on the left neatly formatted the link, the "Phone:" text, and phone numbers. What did the programmer on the right do?
Output those items without neatly formatting
What would happen if the following list was input: 10 1 6 3 -1?
Output would be 5
What is the output of the following program? actors = ['Pitt', 'Damon'] actors.insert(1, 'Affleck') print(actors[0], actors[1], actors[2])
Pitt Affleck Damon
What is the output of the following program? actors = ['Pitt', 'Damon'] actors.insert(1, 'Affleck') print(actors[0], actors[1], actors[2])
Pitt Affleck Damon
Kia Smith is inviting you to a video meeting. Join meeting: http://www.zoomskype.us/5592 Phone: 1-669-555-2634 (San Jose) 1-929-555-4000 (New York) Meeting ID: 5592 ------------------------- Reminder: 10 min before Kia Smith is inviting you to a video meeting. Join meeting: http://www.zoomskype.us/5592 Phone: 1-669-555-2634 (San Jose) 1-929-555-4000 (New York) Meeting ID: 5592 ------------------------- Reminder: 10 min before The programmer on the left intentionally inserted a newline in the first sentence, namely "Kia Smith ... video meeting". Why?
So the text appears less jagged
Determine the output of the following code: my_str = 'The cat in the hat' print(my_str[0:3])
The
A dynamic-typed language like Python checks that an operation is valid when that operation is executed by the interpreter. If the operation is invalid, a run-time error occurs. True or False
True
A function definition must be evaluated by the interpreter before the function can be called. True or False
True
A local variable is defined inside a function, while a global variable is defined outside any function. True or False
True
A namespace is how the Python interpreter restricts variables to a specific scope. True or False
True
A processor executes instructions like, Add 200, #9, 201, represented as 0s and 1s. True or False
True
A programmer can protect mutable arguments from unwanted changes by passing a copy of the object to a function. True or False
True
Complete the loop expressions, using a single operator in your expression. Use the most straightforward translation of English to a expression. Iterate until c equals 'z'. while ____ : # Loop body statements go here
c != 'z'
Rewrite the statement using a compound operator, or type: Not possible car_count = car_count / 2
car_count /= 2
Each time through the loop, the sum variable is increased by _____.
current input value
The value of num as a decimal (base 10) integer: 31 num = 31 print('{: }'.format(num))
d
Complete the code using formatting specifiers to generate the described output. Use the indicated variables. Assume city is 'Boston' and distance is 2100. We are 2100 miles from Boston. print('We are %d miles from %s.' % (_________________))
distance, city
the statement del my_list[2] produces a new list without the element in position 2
false
Which answer assigns an empty string to first_name?
first_name = ''
Which creates a string variable first_name with a value 'Daniel'?
first_name = 'Daniel'
Alter the list comprehension from row 2 in the table above to convert each number to a float instead of a string. my_list = [5, 20, 50] my_list = [ ____ for i in my_list] print(my_list)
flaot(i)
The average number of kids per household. float or int
float
Alter the list comprehension from row 2 in the table above to convert each number to a float instead of a string. my_list = [5, 20, 50] my_list = [ ____ ] for i in my_list] print(my_list)
float(i)
Given the following program, select the namespace that each name would belong to. player_name local global built-in
global
Given the following program, select the namespace that each name would belong to. roll local global built-in
global
Write a statement that performs the desired action. Assume the list house_prices = ['$140,000', '$550,000', '$480,000'] exists. Add a price to the end of the list with a value of '$1,000,000'.
house_prices.append('$1,000,000')
Write a statement that performs the desired action. Assume the list house_prices = ['$140,000', '$550,000', '$480,000'] exists. Remove the 1st element from house_prices, using the pop() method.
house_prices.pop(0)
Write a statement that performs the desired action. Assume the list house_prices = ['$140,000', '$550,000', '$480,000'] exists. Remove '$140,000' from house_prices, using the remove() method.
house_prices.remove('$140,000')
Write a statement that performs the desired action. Assume the list house_prices = ['$140,000', '$550,000', '$480,000'] exists. Update the price of the second item in house_prices to '$175,000'.
house_prices[1] = '$175,000'
Determine the number of elements in the list that are divisible by 10. (Hint: the number x is divisible by 10 if x % 10 is 0.) div_ten = 0 for i in num: if ( ): div_ten += 1
i % 10 == 0
Fill in the missing field to complete the program. Determine the number of elements in the list that are divisible by 10. (Hint: the number x is divisible by 10 if x % 10 is 0.) div_ten = 0 for i in num: if ____ : div_ten += 1
i % 10 == 0
Use <= in each answer. Loop iterates 10 times. i = 1 while ____ : # Loop body statements go here i = i + 1
i <= 10
Complete the missing parts of the code. i = 0 while ____ : # Loop body statements go here i = i + 5
i <= 1000
Use <= in each answer. Loop iterates 2 times. i = 1 while ____ : # Loop body statements go here i = i + 1
i <= 2
Loop iterates 99 times. i = 1 while
i <= 99
Use <= in each answer. Loop iterates 99 times. i = 1 while ____ : # Loop body statements go here i = i + 1
i <= 99
Complete the missing parts of the code. Loop iterates from -100 to 65 ________ while i <= 65: # Loop body statements go here i = i + 1
i = -100
Write a list comprehension that contains elements with the desired values. Use the name 'i' as the loop variable. The largest square root of any element in x. Use math.sqrt() to calculate the square root.
max([math.sqrt(i) for i in x])
Add all of the elements of set goblins into set monsters.
monsters.update(goblins)
Write an expression that accesses the first character of the string my_country.
my_country[0]
Change all negative values in my_dict to 0. for key, value in ____: if value < 0: my_dict[key] = 0
my_dict.items()
Fill in the code, using the dict methods items(), keys(), or values() where appropriate. Print each key in the dictionary my_dict. for key in ____: print(key)
my_dict.keys() or my_dict
Fill in the code, using the dict methods items(), keys(), or values() where appropriate. Print twice the value of every value in my_dict. for v in ____ : print(2 * v)
my_dict.values()
Print twice the value of every value in my_dict. for v in ___: print(2 * v)
my_dict.values()
Write a function call using the ebay_fee() function to determine the fee for a selling price of 15.23, storing the result in a variable named my_fee.
my_fee = ebay_fee(15.23)
Write a statement that counts the number of elements of my_list that have the value 15.
my_list.count(15)
Write the simplest two statements that first sort my_list, then remove the largest value element from the list, using list methods.
my_list.sort() my_list.pop()
Write a statement that creates a list called my_nums, containing the elements 5, 10, and 20.
my_nums = [5, 10, 20]
Complete the for loop statement by giving the loop variable and container. Iterate over the given list using a variable called my_pet. for ____ in ['Scooter', 'Kobe', 'Bella']: # Loop body statements
my_pet
Write a statement that uses the join() method to set my_str to 'NewYork', using the list x = ['New', 'York']
my_str = ''.join(x)
Write the simplest expression that captures the desired comparison. my_str is not the third element in the list my_list
my_str is not my_list[2]
Write a statement that assigns the 2nd element of my_towns with 'Detroit'.
my_towns[1] = 'Detroit'
Answer each question using the operators of the form +=, *=, /=, -=, etc. Write a statement using *= that doubles the value of a variable my_var.
my_var *= 2
Answer each question using the operators of the form +=, *=, /=, -=, etc. Write a statement using += that is equivalent to my_var = my_var + my_var / 2
my_var += my_var / 2
Type a statement that reads a user-entered string into variable my_var.
my_var = input()
Type a statement that converts the string '15' to an integer, and assigns the result to my_var.
my_var = int('15')
Write a statement that assigns my_var with the 3rd element of my_list.
my_var = my_list[2]
Assign my_var with the last character in my_str. Use a negative index.
my_var = my_str[-1]
A script "myscript.py" has two command line arguments, one for an input file and a second for an output file. Type a command to run the program with input file "infile.txt" and output file "out". > python
myscript.py infile.txt out
After the second loop, was the baby awake?
n
Add the literal 'Ryder' to the set names.
names.add('Ryder)
At the end of the loop body, the _____.
next input is gotten
Assume the following list has been created scores = [ [75, 100, 82, 76], [85, 98, 89, 99], [75, 82, 85, 5] ] 1) Write an indexing expression that gets the element from scores whose value is 100.
scores[0][1]
A file containing Python code that is passed as input to the interpreter
script
Assume the function below is defined: def split_check(amount=10, num_people=2, tax_rate=0.095, tip_rate=0.18): # ... When entering answers, use the same number of significant digits as the default parameter values in the split_check() definition. Write a statement that splits a $25 check amongst 3 people, and leaves a 25% tip. Use the default tax rate.
split_check(amount=25.0, num_people=3, tip_rate=0.25)
Assume the function below is defined: def split_check(amount=10, num_people=2, tax_rate=0.095, tip_rate=0.18): # ... When entering answers, use the same number of significant digits as the default parameter values in the split_check() definition. Write a statement that splits a $50 check amongst 4 people. Use the default tax rate and tip amount.
split_check(amount=50, num_people=4)
Assign sub_lyric with "cow" by slicing rhyme_lyric from start_index to end_index
start_index:end_index
Write a statement that assigns str2 with a copy of str1.
str2 = str1[:]
Alter the list comprehension from row 5 in the table above to calculate the sum of every number contained by my_list. my_list = [[5, 10, 15], [2, 3, 16], [100]] min_row = ____ ([sum(row) for row in my_list]) print(min_row)
sum
Alter the list comprehension from row 5 in the table above to calculate the sum of every number contained by my_list. my_list = [[5, 10, 15], [2, 3, 16], [100]] min_row = _____([sum(row) for row in my_list]) print(min_row)
sum
What does os.path.getsize(path_str) return?
the size in bytes of the file at path_str
Remove all of the elements from the trolls set.
trolls.clear()
a program can modify the elements of an existing list
true
a programmer can iterate over a copy of a list to safely make changes to that list.
true
iterating over a list and deleting elements from the original list might cause a logic program error.
true
nested dictionaries are a flexible way to organize data
true
the expression {'D1': {'D2': 'x'}} is valid.
true
the sort() method modifies a list in-place
true
Which built-in function finds the type of an object?
type or type()
monsters = {'Gorgon', 'Medusa'} trolls = {'William', 'Bert', 'Tom'} horde = {'Gorgon', 'Bert', 'Tom'} {'Gorgon', 'Bert', 'Tom', 'Medusa', 'William'} monsters.(trolls)
union
How many times does the loop iterate in the program?
unknown
Complete the function beginning to have a parameter named user_age. def print_age(__________):
user_age
Given a 16-digit credit card number stored in x, which gets the last (rightmost) four digits? (Assume the fourth digit from the right is non-zero).
x % 10000
Complete the loop expressions, using a single operator in your expression. Use the most straightforward translation of English to a expression. Iterate while x is less-than 100. while ____ : # Loop body statements go here
x < 100
Convert each if-else statement to a single assignment statement using a conditional expression, using parentheses around the condition. Enter "Not possible" if appropriate. if x < 0: x = -x else: x = x
x = -x if (x < 0) else x or x = -x if x < 0 else x