Python Final Review

¡Supera tus tareas y exámenes ahora con Quizwiz!

When using Python, which mathematic operation returns a value of 2?

42 % 4

When using Python, what is the result of the mathematic operation 1 ** (2 * 3) / 4 + 5?

5.25

You are comparing two numerical values in the following operation: In [1]: 9 ___ 9 Out[1]: True Which operator correctly completes the operation?

>=

answer = input("enter your answer: ") print("You entered " + answer) If user input is 38, what is the output of the above code?

You entered 38

Which choice best represents the output of the following code? student_name = "iteration" new_word = "" for letter in student_name[:3]: new_word += letter print(new_word)

"ite"

What is the result of the following code? D = {'Name':'Daniel', 'Age':15, 'GPA':3.67} print(D.pop('Age')) print(D)

15 {'Name': 'Daniel', 'GPA': 3.67}

Which element stores Python script command-line arguments and options?

argv

Given that the file school_names contains the following text: *City*Elementary* *Maths*High*School* *Early*Learner*PreSchool* Which answer best describes the output of the following code? schools = open("school_names.txt", "r") name = schools.readline().strip('*\n') while name: if name.startswith("M"): print(name) else: pass name = schools.readline().strip('*\n')

"Maths*High*School"

When using printf-style string formatting, which conversion flag outputs a single character?

%c

When using printf-style string formatting, which conversion flag outputs a signed integer decimal?

%d

Which operator has the highest precedence? (Choose one.)

+

In an os function, which syntax can you use to move up one folder in the current directory structure?

. .

To move the pointer in an open file to the first character, what should you use?

.seek(0)

To move the pointer 5 characters past the current pointer location, what should you use?

.seek(5,1)

Which function displays a date object in the form Monday, January 01, 2018?

.strftime("%A, %B %d, %Y")

Which answer best describes what .strip() does in the following code sample? poem_line = poem1.readline().strip()

.strip() removes leading and trailing whitespace, including the '\n' formatting character

x = 3 y = 3 calculation = x/y print(calculation) What is the best estimate for the output of the above code?

1.0

calculation = 5 + 15 / 5 + 3 * 2 - 1 print(calculation) What is the best estimate for the output of the above code?

13.0

def add_num(num_1 = 10):print(num_1 + num_1) Choose the correct output of calling the above function using the following code: add_num()

20

You perform the following Boolean comparison operation: (x >= 10) not (x < 20) and (x % 2 == 0) For which two numbers is the comparison operation True? (Choose two.)

20 50

To read each line of a file as an item in a list, use .listread().

False

True or False: An infinite loop is a loop that runs until the value returned by the loop condition is False.

False

True or False: When handling exceptions, Python code can include an else clause or a finally clause, but not both.

False

True or False: You can use the remove function to delete a specific file directory.

False

You are performing the following operation: In [1]: 10 == 20 Out[1]: _____ What is the result of the operation?

False

name = "Tobias" print(name == "Alton") What is the output from running the above code?

False

Which attributes can you define for a time object? (Choose all that apply.)

Hour, second

Which two statements about a positional argument are true? (Choose two.)

Its position depends on the command It is a required argument

Which two statements about key:value pairs are correct? (Choose two.)

Keys are unique A value can be associated with multiple keys

In which two ways is a tuple like a list? (Choose two.)

Lists and tuples are data structures that can store a sequence of elements. Lists and tuples can contain int, float, list, and string elements.

Which of the following correctly creates a tuple with one element?

T = (25)

Given that the file school_names contains the following text with 3 school names: City ElementaryMaths High SchoolEarly Learner PreSchool if we run the following code: schools = open("school_names.txt", "w+") Which item is Not True?

The file school_names will contain the original 3 school names.

What is the result of not setting the value of the year attribute of a date object?

The object is invalid.

Which two statements are true for two objects that contain the same information and are saved in different memory locations? Example: ```python x = [1,2,3,a,b] y = [1,2,3,a,b] ``` (Choose two.)

They are equal They are not identical

"Hello".isalpha() What is the output of the above code?

True

"w+" mode opens a file for write plus read, such as in the following Python code: schools = open("school_names.txt", "w+")

True

.readline() is used to read one line, as a string, from an open text file.

True

A file opened in read mode cannot be changed (we cannot write to the file).

True

Escape sequences start with a backslash (\).

True

For the code: x = 3 + 9 * 2, the value of x is 21 when applying order of operations.

True

Function names cannot begin with a number as the first character.

True

Jupyter Notebooks have code cells and markdown cells.

True

True or False: A datetime.timedelta object stores only days, seconds, and microseconds.

True

Which process can you use to assign the values of a tuple to multiple variables?

Unpack the tuple

Choose the correct statement.

Variable values in Python can change type, from integer to string

You run a Python script named my_script.py directly from a terminal window. In the script environment, what is the value of the `__name__` variable?

`__main__`

Which information should you include in a multi-line docstring for a function?

arguments, return values, and exceptions

Which code is the best use of Python that deletes the "5" in the following numbers list? numbers = [7, 1, 5, 8, 0]

del numbers[2]

Which of the following can have multiple instances in the try/except?

except:

What type of loop should you use to iterate over the elements of a simple table (two-dimensional list)?

nested

num_1 = 3num_2 = "8" What is the minimum code to mathematically add num_1 to num_2?

num_1 + int(num_2)

In what format does a dictionary store information?

{key:value}

When using the format() method, which placeholder outputs the variable x as a three-digit integer with two digits before and one digit after the decimal point (for example, 12.3)?

{x:3.1f}

Exception type raised by accessing an unspecified (undefined) variable.

NameError

PriNt("Hello World!") will not output the message "Hello World!". What will it result in?

NameError

What exception will occur if "afile" does not exist given the following code? file_path = "parent/afile.txt" os.remove(file_path)

NameError

What is the best choice to complete the following sentence? Using .readlines() to read an open file results in...

reading each line in the file as an item in a list.

The input() function in Python returns user input as a string.

True

When using the str.format() method, which flag places a - (negative sign) in front of negative numbers?

"

Which is an example of a valid one-line docstring?

"""Return the path of the current working directory."""

True or False: In Python, using the `raise` statement allows the programmer to define and raise their own exception.

True

True or False: Python code can include a script that returns the operating system platform your code is running on with the .sys

True

True or False: The containment operators in and not in return a True/False result.

True

while 3 < 5: is a forever loop just like while True: is.

True

What does the Python code: score = 3 + "45" result in?

TypeError

What is the result of the following code? T = (13, 5, 92) T[0] = 5

TypeError

answer = input("enter your answer: ") print(10 + answer) If user input is 38, what is the output of the above code?

TypeError

Which clause should you use for code that you want to execute regardless of whether an exception is raised?

finally

What does type(3.55) return?

float

Which three data types can you use for dictionary keys? (Choose three.)

float, int, string

Which is not a start to a string iteration loop, given the following string variable assignment? word = "health"

for word in letter:

count = 1 while count >= 1: print("loop") count +=1 What is the output from running the above code most like?

forever loop

Which element should come first in a multi-line docstring for a function?

A summary line that describes the function as a command

Which of the following statements about tuples is true?

A tuple can contain list elements.

Which code should you use to import a function named abc from a Python module named xyz?

from xyz import abc

Which process does Python use to optimize dictionary search capabilities?

hashing

Which expression defines an object named hiredate with a value of July 1, 2018?

hiredate = datetime.date(year = 2018, month = 7, day = 1)

Which expression defines an object named hiredate with a value of Jan 15, 2019?

hiredate = datetime.datetime(year = 2019, month = 1, day = 15)

What does type(1024) return?

int

Which Boolean operator has the highest precedence? (Choose one.)

is not

Which statement correctly casts the string to a list?

letterList = list("This one")

Which statement about the datetime.datetime data type is true?

All date variables are required.

Which best describes the valid Python use of the following days List?

All of the above: days.append("Wednesday") days.append(14) print(days[-1])

What is the result of the following code? (Name, Grade) = ("Anne", 95)print(Name, Grade)

Anne 95

1. 2. score = add_score(190) 3. 4. print(name, "your score is", score) 5. At which line above should the following add_score() function definition be inserted so the program runs without error? def add_score(current): return current + 10

line 1

1. greet(name) 2. name = input("enter your name: ") 3. greet(name) 4. def greet(person): u 5. print("Hi,", person) 6. greet(name) Which line or lines need to be removed from the above code so the program prints a greeting without error?

lines 1 and 3

Which is the best choice to complete the following sentence? Opening a file in Python using read mode ('r')...

makes file contents available for Python to read from the file.

Which function from the math module can you use to round up the number 12.34 to 13?

math.cell ( )

You run a Python script named my_script.py by importing it as a module into a script named second_script.py. In the script environment, what is the value of the `__name__` variable?

my_script

Which Boolean operator has the highest precedence? (Choose one.)

not

Which best describes the result of the following code? numbers = [2, 3, 2] total = 0 while numbers: total += numbers.pop()

numbers is an empty list and total is 7

In Python, what is the base class for all built-in exceptions?

BaseException

Which code places another "2" integer to the end of the following list? numbers = [1, 1, 2]

numbers.append(2)

Which code overwrites (replaces) the "0" with a "5" in the following numbers list? numbers = [1, 1, 0]

numbers[2] = 5

Which function can you use to list the contents of the current working directory?

os.listdir()

Which function can you use to test whether an absolute or relative path to a folder is valid?

os.path.exists(path)

Which two functions can you use to determine whether a path leads to either a file or a directory? (Choose two.)

os.path.isdir(path) os.path.isfile(path)

Which two os module functions can you use to delete a specific file? (Choose two.)

os.remove os.unlink

Which function can you use to delete an empty folder?

os.rmdir()

Which type of statement should you use as a placeholder for future function code?

pass

HelloWorld! What is the best choice of code to create the output shown above?

print("Hello\nWorld!")

It'sPython Time! Choose the code that will not create the output shown above.

print("It's" + "Python Time!")

Which block of statements creates the following output? Which*code*is*it?

print("Which", end = '*') print("code", end = '*') print("is", end = '*') print("it?")

Given the following code, which choice is best to represent the first line in the text file books.txt in Title format, where every word is capitalized? books = open('books.txt', 'r')

print(books.readline().title())

Which Python code results in output of a sorted scores list with changing the original scores list below to be in a sort order? scores = [ 0, 5, 2, 11, 1, 9, 7]

print(scores.sort())

Which Python code results in output of a sorted scores list without changing the original scores list below? scores = [ 0, 5, 2, 11, 1, 9, 7]

print(sorted(scores))

Given the code below and entering "Colette" for user_name input: python total_cost = 22.95user_name = input("Enter your name: ") Choose the print statement that will output: Colette - the total is $ 22.95 for today's purchase

print(user_name, "- the total is $", total_cost, "for today's purchase")

tip = "Do or do not. There is not try. Jedi Master Yoda" tip_words = tip.split(". ") for word in tip_words: print(word)

Do or do not. There is not try. Jedi Master Yoda

Which command should you use to generate HTML documentation for a Python module named py?

pydoc -w program

Which command should you use to generate text documentation for a Python module named py?

pydoc program

Which code formats the string "Green" to "GREEN"?

D. .upper()

Which function returns only whole, even numbers from within the range from 1 to 100?

random.randrange(2, 101, 2)

tip = "Do or do not. There is not try. Jedi Master Yoda" tip_words = tip.split() for word in tip_words: print(word)

Do or do not. There is not try. Jedi Master Yoda

// This means

Integer Division

Which two statements about the pydoc module are true?

It generates documentation from the docstrings in a module. It imports a module and then generates documentation for the module.

Which two statements about a positional argument are true? (Choose two.)

It is a required argument Its position depends on the command

Which best describes the result of the following code? days = [12, 9, "Monday", 1] days.remove("Friday")

Error, because "Friday" was not found and can't be removed

Which version of Python does this course cover?

Python 3

Which string defines a heterogeneous tuple?

T = ("Tobias", 23, 25.3, [])

** This means what

exponent

Which Python code results in reversing the order of the scores list? scores = [ 0, 5, 2, 11, 1, 9, 7]

scores.reverse()

Which of the following are valid expressions for the datetime.timedelta objects t1, t2, and t3? (Choose all that apply.)

t1 = t2 - t3 t1 = 6 % t2

Given the following starting code: test1 = open('test1.txt', 'r') We can read 10 string characters from a file into memory by using which Python code?

ten_char = test1.read(10)

After we open a file (first_test) using: test1 = open('test1.txt', 'r') we can write the file into memory with which Python code?

test1.write()

After we open a file (first_test) using: test1 = open('test1.txt', 'r') we can read the file into memory with which Python code?

test_data = test1.read()

The .close method conserves system memory because...

the file .close() method removes the reference created from file open() function.

When using .readlines(), it is common to remove the last character of each string in the generated list, because...

the last character is typically a whitespace newline character, "\n".

Which set of statements created the following output? Notebooks can be exported as .pdf

tip_words = ['Notebooks', 'can', 'be', 'exported', 'as', '.pdf']print(" ".join(tip_words))

What type of loop should you use to repeat a code process as long as a condition resolves as `True`?

while

Which statement ensures that a file will be closed even when an exception is raised?

with open(file_path, mode) as file:

Choose the correct statement.

Variables in Python can be initialized using the equals sign (=).

def ignore_case(name): answer = "" while answer.isalpha() == False: answer = input("enter last name: ") return answer.lower() == name.lower() When will the ignore_case function exit the while loop?

When only letters are entered at the input prompt

if x < 0: print("-") else: if y >= 0: print("+/+") else: print("+/-") Which values for x and y result in the output "+/-"? (Choose the best answer.)

x = 0 and y = -1

day = "monday" if day.capitalize() == "Monday": print("Start the week!") else: pass What is the output from running the above code?

"Start the week!"

if x < 0: print("-") else: if y >= 0: print("+/+") else: print("+/-") The nested conditional code is sure to be run if ___. (Choose the best answer.)

x = 1

vehicle_type = "Truck" if vehicle_type.upper().startswith("P"): print(vehicle_type, 'starts with "P"') else: print(vehicle_type, 'does not start with "P"') What is the output from running the above code?

"Truck does not start with "P""

Given x = 9, which line of code will evaluate False?

x<3

x = 0 while x < 5: x += 1 print('loop') What is the output from running the above code most like?

"loop" (5 times)

def low_case(words_in):return words_in.lower() Choose the correct output of calling the function above using the following code: words_lower = low_case("Return THIS lower")print(words_lower)

"return this lower"

x = 0 while True: if x < 10: print('run forever') x += 1 else: break What is the output from running the above code most like?

"run forever" (10 times)

Which print output is the result of the following code? word = "Programming rocks!" print(word[-2])

"s"

name = "skye homsi" name_1 = name.title() name_2 = name_1.swapcase() print(name_2)

"sKYE hOMSI"

Choose the best representation of the output expected for the following code. cities = ["New York", "Shanghai", "Munich", "Tokyo", "Dubai", "Mexico City", "São Paulo", "Hyderabad"] for city in cities: if city.startswith("P"): print(city) elif city.startswith("D"): print(city)

Dubai

A new list is initialized, made of 2 lists, when the .extend() list method is used.

False

Function calls should be placed at the beginning of a code page, and functions should be placed later and toward the end of the code.

False

In Python string comparisons, lower case "a" is less than upper case "A".

False

In Python, strings can contain only letters a-z and A-Z.

False

In Python, we can use the "+" operator to add numbers, but not to add strings.

False

In the following for loop code, the variable name is "student" because it can only be called "student" and cannot be replaced with another valid variable name such as "pupil". students = ["Alton", "Hiroto", "Skye", "Tobias"] for student in students: print("Hello", student)

False

Nested Conditional code always runs all sub-conditions that are indented under if statements.

False

Python Function return values must be stored in variables.

False

Python cannot display quotes in strings using print().

False

The .append() method adds an item to the beginning of a list.

False

The .insert() method overwrites (replaces) the list item at the selected index.

False

The code print("I am", 17, "years old") will output: I am17years old

False

The string method .swapcase() converts from string to integer.

False

size_num = "8 9 10" size = "8" # user input if size.isdigit() == False: print("Invalid: size should only use digits") elif int(size) < 8: print("size is too low") elif size in size_num: print("size is recorded") else: print("size is too high") What is the output from running the above code?

"size is recorded"

The type() function is used to change from one data type to another.

False

time = 3 while True: print('time is', time) if time == 3: time = 4 else: break What is the output from running the above code most like?

"time is 3" & "time is 4"

Which is a valid Python code comment?

# use comments to describe the function of code.

Choose the best representation of the output expected for the following code. numbers = "" for x in range(7): numbers += str(x) print(numbers)

0123456

Which contains only integers? (ignore the commas)

1, 2, 0, -3, 2, -5

while True: will loop forever but can be interrupted using the Python keyword "end" inside the loop.

False

def add_numbers(num_1, num_2 = 10):return num_1 + num_2 Choose the correct output of calling the function above using the following code: print(add_numbers(100))

110

x = 3 y = 4 calculation = x*y print(calculation) What is the best estimate for the output of the above code?

12

def add_num(num_1 = 10):return num_1 + num_1 Choose the correct output of calling the function above using the following code: print(add_num(100))

200

name = input("enter your name") 2. print(name, "your score is", score) 3. score = 199 Order the above numbered code lines into the proper sequence.

3,1,2

Which is an example of Python string addition that will run without error?

Falsenew_string = "Hello " + "World!"

num_1 = "" num_temp = "" num_final = "" while True: num_1 = input("Enter an integer: ") if num_1.isdigit(): num_final = num_temp + num_1 num_temp = num_final else: print(num_final) break What is the output from running the above code using the following input at the Enter an integer: prompt? 1st input: 3 2nd input: 4 3rd input: five 4th input: 6

34

hot_plate = True if hot_plate: print("Be careful, hot plate!") else:print("The plate is ready.") What is the output from running the above code?

"Be careful, hot plate!"

name = "Jin Xu" if type(name) == type("Hello"): print(name, "is a string entry") else: print(name, "is not a string entry") What is the output from running the above line of code?

"Jin Xu is a string entry"

name = "SKYE HOMSI" print("y" in name.lower())

True #saying if name was lower, y would we in that

student_name = "iteration"count = 0for letter in student_name: if letter.lower() == "e": print(count) count += 1

"2"

year = "2001" if year.isdigit(): print(year, "is all digits") else: pass What is the output from running the above code?

"2001 is all digits"

id = 3556 if id > 2999: print(id, "is a new student") else: print(id, "is an existing student") What is the output of the above line of code?

"3556 is a new student"

if True: if False: print("Banana") else: print("Apple") else: if True: print("Dates") else: print("Corn") What is the output of the above code?

"Apple"

print("It's time to code") What is the output of the above code?

It's time to code

Which is not a way to run a code cell in a Jupyter Notebook?

Shift + R

assignment = 25 if assignment = 25: print('use "=" to assign values') else: pass What is the output of the above code?

SyntaxError

Like else, the elif can execute only when the previous if conditional evaluates False (shown in the below code sample). if response == 3: return "Correct" elif response <= 0: return "Correct" else: return "Incorrect"

True

The .pop() method both returns and deletes an item from a list.

True

The double equal sign (==) is used to compare values.

True

True and False are Boolean keywords in Python.

True

Using comma separation, we can combine strings and numbers (int & float) in a single Python print() function without a TypeError.

True

length = "33"length.isalnum() What is the output of the above code?

True

Which is an example of the proper use of the Python input() function?

answer = input("enter your answer: ")

Which best describes a valid Python use of the following days List?

days.insert(1, "Wednesday")

A function with 2 integer parameters could start with which definition?

def add_numbers(num_1, num_2):

Which is a properly formatted Python print() function example?

print("Welcome the", 3, "New students!")

\\\\ What is the best choice of code to create the output shown above?

print("\\\\\\\\")

Which choice will print the word "tac", given the following variable declaration? word = "cat"

print(word[::-1])

x = 3 y = "3" # get_diff takes an int and a str def get_diff(xint, ystr): # <function code needed here> if y.isdigit() == False: print('"y" is not an integer string') elif get_diff(x,y) == 0: print('x equal to y') else: print('x is NOT equal to y') To make this program work, printing "x equal to y", choose the best code to replace the above comment "# <function code needed here> " in the get_diff function.

return int(ystr) - xint

def show_name():print("Tobias Ledford") Which code calls the function in the above code

show_name()

What does type("Hello World!") return?

str

Choose the item that best completes the following sentence: "After using an insert on a Python list..."

the length of the list increases by 1.


Conjuntos de estudio relacionados

Data Analysis with R Programming - Weekly challenge 2

View Set

Chapter 15-19 final exam mkgt3175

View Set

World Geography I test Earth Spheres

View Set

L2 Biologie - Génétique 2 - QG

View Set

MKT 3411 Ch.8 Attitudes and Persuasion, MKT 3411 Ch.9 Group and Situational Effects on Consumer Behavior

View Set