Programming 1 Final

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

What should you place in the blank in the Python code below if you want to display the price for the cat figurine? figurinePrices = {"dog": 3.55, "cat": 4.15, "dolphin": 5:65, "turtle": 4.25} print(_____)

"The cat costs", figurinePrices["cat"]

Suppose you create a Python list containing the elements "J" , "A" , "W" , "S" , and 3 , in that order. What are the index values of the first and last elements of this list?

0 and 4

Given the following program code, what is the output value? numbers = [1024, 1167, 956, 690, 1307, 1672, 1102] print(numbers[6])

1102

Which statement best describes the DRY principle?

Achieve efficient code through efficient use and reuse of functions, classes, and methods.

How can the following Python code be modified so that it produces the desired output? beverage1 = "Cocoa" def change_beverage(): beverage1 = "Russian tea" beverage2 = "Apple cider" print(beverage1) print(beverage2) change_beverage() print(beverage1) Desired Output: Russian tea Apple cider Russian tea

Add the statement global beverage1 after the function declaration.

Which phrase represents a principle for secure coding?

Aim for an economy of mechanism in your code.

What happens when the code within a try block fails?

An exception is thrown and the program flow moves to the except block.

What types of data can a list hold?

Booleans, integers, floating-point numbers, or strings

How can you retrieve a list of all the keys present in the Python dictionary, without their associated values?

Call the keys() method on the variable holding the dictionary.

_____ can be easily understood by both the programmer who wrote the code and other programmers who might test the modules or modify them in the future.

Clean code

Which statement is true concerning the following two Python code blocks? Code block A: listOfInts = [i for i in range(5, 26, 5)] Code block B: listOfInts = [] for i in range(5, 26, 5): listOfInts.append(i)

Code blocks A and B result in the same data being stored in listOfInts .

Which statement about Python lists is correct?

Each element in a two-dimensional list is a variable, and each variable can be a list.

Which statement best describes the single responsibility principle?

Ensure that each function or class has only one responsibility and one reason to change.

What is an advantage of exception handling?

Exceptions allow future users of your code libraries better control over how their program behaves.

Why are exceptions used in programming?

Exceptions allow you to "bail out" of a piece of code that reaches a situation where it cannot complete execution.

What is the argument in the function call in the following code? def weather(sunny_today): if sunny_today: print("Blue skies and sunshine!") print("You should take a walk.") else: print("Time for indoor fun.") weather(False)

False

What statement describes the purpose of function parameters in a function declaration?

Function parameters specify a template for data that a function can accept.

Which statement about the following Python code is true? def multiplyByFive(number): if number < 1 or number > 100: raise ValueError("Number must be in the range of 1-100.") print("Five times your number is " + (number * 5) + "!") userNumber = int(input("Time for number fun! Enter a number between 1 and 100: ")) try: multiplyByFive(userNumber) except Exception as e: errorMessage = str(e) print(errorMessage)

If the user enters a 0 in response to the prompt, the program will display an error message.

_____ testing verifies that all of the units or modules work together.

Integration

Filtering a list is a way of retaining only those elements that meet a specific condition. This can be accomplished by using a for-loop that contains an if-statement or by using a for-loop within square brackets. For example, the statement evens = [i for i in range(100) if i % 2 == 0] is a list comprehension that stores a list of all the even numbers between 0 and 99 in the evens variable.

Only code block A relies on a conditional expression to filter items.

Imagine that you would like to write Python code for a tic-tac-toe game and decide to use a two-dimensional list to represent the game board. How would you allow users to add an X or O to the board?

Prompt the user for input to indicate the row and column numbers in which to place the X or O, then modify the list by reassigning an element, using the inputs as the two indexes to access the element to modify.

_____ testing is performed to ensure that recent code modifications do not have adverse effects.

Regression

Examine the following code outline. What is the first change you should make to include a function description? Line 1: Greet the user. Line 2: Allow the user to choose to enter a number pair or exit. Line 3: If the user chooses to exit, terminate the program. Line 4: If the user chooses to enter two numbers, ask the user to enter two numbers. Line 5: Multiply the numbers. Line 6: Display a message that includes the product. Line 7: Allow the user to choose to enter another number pair or exit. Line 8: If the user chooses to exit, terminate the program. Line 9: If the user chooses to enter two more numbers, ask the user to enter two numbers. Line 10: Multiply the numbers. Line 11: Display a message that includes the product. Line 12: Allow the user to choose to enter another number pair or exit. ... [continues in a similar manner]

Rewrite lines 5 and 6 as a single line, "Apply multiplication and display behavior to the numbers."

When traversing a two-dimensional list, why is a nested loop typically required?

The outer loop has to control the iteration through each row, while the inner, nested loop has to control the iterations through the columns.

Which statement about the following code is correct? def receipt(x, y, z): print("Your order:") print(str(x) + "-inch " + y + " hoagie.") print("Total ${:0.2f}".format(z)) print("Thank you for your business!") type = "Italian" receipt(12, type, 9.99)

The string "Italian" is passed to the y function parameter.

The code to detect an exception uses a logical control structure similar to a(n) __________ block of code.

if-else

Which action is not appropriately used for error handling when catching an exception?

immediately returning to the try block to attempt to execute the code again

Nested modules _____.

are modules stored within other modules

What Python statement should you place in the blank in the following code to display the output shown? paintBox = [["Red", "Orange", "Yellow"], ["Green", "Blue", "Indigo"], ["Violet", "White", "Pink"]] _____ Output: Red | Orange | Yellow Green | Blue | Indigo Violet | White | Pink

print("\n".join([" | ".join(row) for row in paintBox]))

In the waterfall model, the _____ phase is where a programming team develops algorithms and data structures that specify how the requirements should be implemented.

design

A string enclosed in triple quotation marks that provides help information within a program is called a(n) _____.

docstring

In programming, a(n) _____ is an unexpected, triggered event that interrupts normal program flow.

exception

What Python code belongs in the blank to obtain the output shown by traversing gameOutcomes ? gameOutcomes = ["Win", "Loss", "Loss", "Win", "Win"] _____ Output: Win Loss Loss Win

for element in gameOutcomes: print(element)

What should you place in the blank in the following Python code to achieve the output shown? weekendSpecials = {"Friday": "salmon", "Saturday": "grouper", "Sunday": "cod"} _____ Output: The special on Friday is salmon The special on Saturday is grouper The special on Sunday is cod

for key in weekendSpecials.keys(): print("The special on", key + " is", weekendSpecials[key])

In the following Python function, changing all_caps to all_caps=False in the function declaration would _____. def affirmation(input_number, all_caps): if input_number < 6: message = "You are so awesome!" else: message = "You are just marvelous!" if all_caps == True: print(message.upper()) else: print(message)

provide a default value for the second parameter so that the function can be called with only one argument

Modules are organized by _____.

purpose

Which statement should you use to uninstall a Python module you previously installed called pandas?

python -m pip uninstall pandas

Which Python module can you use to rearrange the elements in a list in a meaningless order?

random

Suppose you have a Python list containing the names of famous cities and you want your program to select any three of them to incorporate into a statement that will be displayed to the user. Which function should you use for this task?

random.sample()

Which statement will add a new key, "Unit 5" , and its associated value, "Josip" , to the Python dictionary called residents ? residents = {"Unit 1": "Marley", "Unit 2": "Bruce", "Unit 3": "Ramesh", "Unit 4": "Ivy"}

residents["Unit 5"] = "Josip"

What should you place in the blank in the following Python code to return two values to the main program at the same time? def get_discount_percentage(customer_type): if customer_type == "Subscription": discount_percentage = 0.2 elif customer_type == "Senior": discount_percentage = 0.1 else: discount_percentage = 0 veteran_discount_percentage = discount_percentage + 0.1 _____

return discount_percentage, veteran_discount_percentage

Suppose you want to create a one-dimensional Python list that contains seven elements representing the inches of snowfall for each day of the week: 1, 2, 5, 11, 7, 3, and 2. You should _____.

store all seven integers in the correct order in a variable called dailySnowfall

What Python code should you place in the blank to collect the return value of winner in a variable in order to increase the value of tally by one when the user reports winning the match? def winner(match_winner): if match_winner: print("Congratulations!") print("Adding 1 point to your tally.") return 1 else: print("Okay. Maybe next time.") return 0 tally = 0 outcome = input("Did you win this match? Y or N") _____

tally += winner(outcome == "Y")

If the value of the __name__ hidden variable in a Python program is "__main__" , this means that _____.

the main program's code is currently being executed

A software development project is well suited for the waterfall model when _____.

the requirements are clear at the beginning of the project

What is the purpose of a function's return value?

to Return data from a function back to the calling function or main program

You can place Python modules in folders ____.

to organize them like files on a computer

Given the following Python code, what should you place in the blank to sum the total snowfall for the week? daily_inches_of_snow = [1, 2, 5, 11, 7, 3, 12] _____ print("The total snowfall for the week is: " + total + "inches.")

total = sum(daily_inches_of_snow)

Suppose you have a Python module folder called flowers with some subfolders and module source code files in it, as follows. flowers contains: |__ roses folder, which contains sevenSisters.py and popup.py |__ hyacinth folder, which contains roseOfSharon.py |__ echinacea.py |__ gardenia.py Given this module structure, which statement would you use to import the water() function from the module popup.py into the module roseOfSharon.py?

from ..roses.popup import water

Which Python code correctly uses importing to work with a function from an external module?

from math import pow print(pow(2, 2))

You can modify every element in a one-dimensional Python list by _____.

using an index-based loop to reassign the value of each element

Which statement should you include in your Python program if you want to use three functions from the math module—the power of, square root, and cosine functions—and want to reference them as pow() , sqrt() , and cos() ?

from math import pow, sqrt, cos

Which statement should you use to import all functions from the os.path nested module into your Python program if you want to avoid having to reference either the os or os.path module when calling the imported functions?

from os.path import *

The __________ uniquely defines a function for the interpreter.

function signature

A(n) ____ variable is accessible to an entire program whereas a(n) ____ variable is limited to a specific part of a program.

global, local

Leonard, a data scientist, would like to use the Python matplotlibmodule to generate graphs. He is unaware, however, that thematplotlibmodule relies on a second module calledNumPyto work properly. If Leonard uses thepipcommand to installmatplotlib, imports it into a .py file, and then begins writing code using this module, _____.

he can successfully call any function from matplotlib in his code

What belongs in the blank in the following Python code if your goal is to use both mapping and filtering together to create doubleTrouble ? doubleTrouble = [_____ if i % 2 == 0]

i * 2 for i in range(20)

Suppose you are given the following list, which represents a tic-tac-toe board for a game written in Python after several moves have been made. board = [["O", "O", "O"], ["O", "X", "X"], [" ", "X", "X"]] Which logical expression will identify the winning move by player O on the top row by evaluating to True?

if board[0][0] != " " and board[0][0] == board[0][1] and board[0][1] == board[0][2]

When accessing external code from a Python program, using the wildcard character _____.

with the from and import keywords imports all items from a module

Because the functions and methods available in Python are organized into modules, _____.

you can bring only those that you need into each program you write

When you want your Python program to collect elements for a list at runtime, _____.

you can use a KNOWN length or a sentinel value to signal completion of the list input

When creating a Python dictionary, _____.

you provide keys that are used to look up associated values

What is the purpose of a function call?

A function call allows the flow of execution to jump to the named function.

Which statement describes the flow of a function call?

A function call transfers execution to the specified function. The instructions in the function are executed and flow returns to the previous execution path when the function is completed.

Which statement accurately compares the naming conventions for functions with those of variables?

A function name ends with parentheses and uses the same naming conventions as a variable.

Which of the following software development projects is least suited for the agile development methodology?

A project where the scope and delivery date of the project are strictly defined.

What is the key characteristic of a void function?

It performs a task without communicating with the main program.

Which statement describes three key characteristics of an array?

Lists are heterogeneous, ordered, and infinite.

Which statement is not a rule or best practice related to global and local variables?

Local variables are defined at the beginning of a program, before functions and before the main code of the program.

Which statement describes a disadvantage of agile development?

Measuring progress is difficult.

Mel has written three Python source files containing some useful functions he wants to be able to import and use in his programs. Mel creates a folder called utilities , places the three source code files inside it, and then adds an empty __init__.py file to this folder. Next, he creates a subfolder inside utilities called financial and moves one source file into it. He wants to be able to import just this part of his module as utilities.finan cial . What is true about Mel's module at this point?

Mel must add an __init__.py file to the financial folder.

Suppose you have written a program called gardenSimulator.py. You would like to place theplantFlower()andwaterFlower()functions from this program in a flower module that you will then import intogardenSimulator.py. What should you do?

Move the functions into a new file called flower.py and save it in the same directory where gardenSimulator.py is located.

Which development methodology is not an agile development method?

Object-Oriented Programming (OOP)

Which statement describes the general methodology of the waterfall development model?

The waterfall development model divides software development into a series of cascading tasks that are performed one after the other.

Which statement describes a disadvantage of using the waterfall model?

The waterfall model lacks flexibility.

Which statement describes a characteristic of a specific exception type?

They tell programmers the type of problem that happened.

Which statement is not an advantage of using programmer-defined functions?

This spreads out code to simplify debugging.

If the user executes the following Python code and enters "Mexico" at the console, the value "Mexico" is passed to the function check_answer for the parameter guess and the value of 1 is returned to the main program. def check_answer(guess, correct): if guess == correct: print("Correct!") return 1 else: print("That is not correct.") return 0 answer = input("Lake Chapala is the largest freshwater lake in which country? ") score = 0 points = check_answer(answer, "Mexico") score = score + points

True

Imagine your Python program saves data to a variable that is used as the argument to call a square_root() function, which returns the square root of that argument. What specific exception will your program raise if the variable's value is the word "four" instead of the integer 4?

TypeError

Given the following program code, what is the output? daily_high_scores = [1024, 1167, 956, 690, 1307, 1672, 1102] daily_high_scores[3] = 745 print(daily_high_scores)

[1024, 1167, 956, 745, 1307, 1672, 1102]

Which phrase describes a use case for a programmer-defined function?

a function to check the answers to trivia questions for a game

Code tries to achieve something by _____.

attempting to proceed as if nothing is wrong

Which Python statement should you use to declare an empty list named bucket in Python?

bucket = []

What category of functions is provided by a programming language, without the need to import modules?

built-in functions

The following Python code creates a dictionary called marbles and then _____. marbles = {"Red": 10, "Tiger eye": 3, "Blue": 8, "Green": 5} marbles["Green"] = 6

changes the value associated with the key "Green" to 6

What are the key tasks that take place during the software development life cycle?

conception, design, implementation, verification, maintenance, and retirement

List comprehension is a Python technique that you can use to concisely _____.

create lists

A list is a ____ classified as a ____ data type.

data structure; composite

A one-dimensional array ____.

is linear

Which Python statement should be used to declare and initialize a one-dimensional numeric list?

kites_sold = [8, 15, 12, 7, 3, 5, 5]

In the following Python code, ____ contains the function declaration and ____ represents the body of the function. 1 def howdy(): 2 print("Hello, world!") 3 howdy() 4 print()

line 1, line 2

Which line of the following Python code contains the function call? 1 def timesTwo(integer): 2 print("Twice your number is", (integer*2)) 3 number = int(input("Enter a number: ")) 4 timesTwo(number) 5 print()

line 4

In Python, a code block beginning with the statement except: used to catch exceptions _____.

makes any exception in the try block jump to the except block

Chloe writes some Python code that iterates over the elements in a list. With each iteration, a function is called on the targeted list element and the returned value is appended to a second list. Chloe's code is an example of _____.

mapping

Which Python statement should you place in the blank if you want to remove the entry with the key "Orange" from the marbles data structure? marbles = {"Red": 10, "Tiger eye": 3, "Blue": 8, "Orange": 4, "Green": 5} _____

marbles.pop("Orange")

Which Python module's purpose is to provide access to a wealth of functions related to complex mathematical operations?

math

Which Python function can you use to calculate the multiplicative sum of a number?

math.factorial()

Which variable represents a Python dictionary?

name: favoritePie , data: "John": "apple", "Laura": "blackberry"

When you want to incorporate code from a Python module into your programs, you can have Python attempt to install the module for you using the _____.

pip command

Which Python statement correctly initializes a dictionary data structure?

positions = {"Chad": "1st base", "Cindy": "2nd base", "Tim": "Outfield"}


Set pelajaran terkait

Chronic Obstructive Pulmonary Disease (COPD)

View Set

NUR 301 | Chapter 23: Nursing Management: Patients With Gastric and Duodenal Disorders PrepU

View Set

很重要SAUNDERS OB ANTEPARTUM (3)

View Set

Pearson VUE: Property Insurance Practice Exam

View Set

NJVS Personal Financial Literacy - Unit 4.7 Fraud & Consumer Protection

View Set