Computer Programming Final Exam

Ace your homework & exams now with Quizwiz!

What will be displayed by the following code? count = 0 while count < 5: print("Hello", end = " ") count +=1

Hello Hello Hello Hello Hello

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

What does type(3.55) return?

float

Which of the following is a Python function?

print ()

Choose the statement that will print the letter "d", given the variable declaration word = "windows"

print(word[3])

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

"

Which choice best represents the output of the following code? student_name = "iteration" count = 0 for 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"

Choose the correct print output for the following code: name = "Alton" print(name[::2])

"Atn"

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!"

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"

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

"Start the week!"

Which statements evaluate True and without errors? (Choose all that apply.)

"The Title".istitle() "upper".islower()

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""

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"

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"

Which print output is the result of the following code? word = "windows" print(word[-1])

"s"

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"

If book_title = "The Xylophone Case" which code will return True?

"x" in book_title

Which of the following is a valid Python comment structure?

# comment

Which is a valid Python code comment?

# use comments to describe the function of code.

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

What is the order of precedence (from first to last) of the math operators?

*, /, +, -

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

+

Which code will result in the ltr_cnt = 2 for counting the letter "c" found in the following test_string? test_string = 'Mexico City'

-

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

. .

Which string method returns an index of first character or substring matches?

.find()

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

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

0

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

0 False

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

024

Which contains only integers? (ignore the commas)

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

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

1. No answer text provided. It is a required argument Its position depends on the command

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

1.0

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

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

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

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

246

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?

>=

Which of the following statements about tuples is true?

A tuple can contain list elements.

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

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

BaseException

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

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

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

False

Escape sequences start with a backslash (\).

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

In the for loop below, the variable "word" is an arbitrary variable name. Any valid variable name can be used since its value is assigned only within this loop. for letter in word: print(letter)

False

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

False

The .count() string method returns the number of times a for/in loop iterates.

False

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

False

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

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

False

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

Hour Second

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

It's time to code

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 version of Python does this course cover?

Python 3

Which string defines a heterogeneous tuple?

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

Given that the file school_names contains the following text with 3 school names: City Elementary Maths High School Early 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

What is "print" used for?

To display output

"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

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

True

In Python, range(0,5) is equivalent to the list [0, 1, 2, 3, 4].

True

The first item in a Python List is located at index 0 (zero).

True

The following code will print "act". word = "characteristics" print(word[4:7])

True

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

True

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

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

True.

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

Unpack the tuple

Choose the correct statement.

Variables in Python can be initialized using the equals sign (=). Variable values in Python can change type, from integer to string

What does the input() function return?

a string value

Choose the item that best completes the sentence: "A Python list..."

can add items to the end of the list using the .append() method.

Choose the item that best completes the following sentence: "A Python list..."

can contain both strings and numbers together as list items.

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

days.insert(1, "Wednesday")

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 clause should you use for code that you want to execute regardless of whether an exception is raised?

finally

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

float int string

Which code is the best use of Python to iterate through the list "numbers"? numbers = [7, 1, 5, 8, 0]

for number in numbers:

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

for word in letter:

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)

What does type(1024) return?

int

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 ( )

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

nested

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

not is 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

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

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

print("Hello\nWorld!")

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 is valid Python code that will print "Green", given the following code? colors = ["Red", "Blue", "Green", "Yellow"]

print(colors[2])

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))

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

print(word[::-1])

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

random.randrange(2, 101, 2)

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.

Which is a valid way to initialize a Python list?

scores = [11, 8, 0, 24, 31, 12, 19]

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

scores.reverse()

Which statement best describes a String in Python/Computer Science?

sequence of characters

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 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".

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.

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

while

Which is not a possible "infinity/infinite" loop?

while 0 > 1:

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

with open(file_path, mode) as file:

Which choice will return -1, given the following variable assignment below? word = "Python"

word.find("Z")

For the code x >= y which x and y values evaluate True?

x = "a", y = "A"

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

Which choice is a valid Python code to store the length of the given string variable 'word' below in 'x'? word = "Python"

x = len(word)

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}

Which operator can be used to combine two strings?

+

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

12

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

13.0

1. 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

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

What is the value of x after the following code is run? x = 2 y = 1 x += y + 1

4

Which of the following statements is true?

Python variables are case sensitive

What is the output of the following code? print("She said, \"Who's there?\"")

She said, "Who's there?"

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

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

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

answer = input("enter your answer: ")

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 a Python method of getting numeric input that can be used in math?

num1 = int(input("enter a number"))

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

num_1 + int(num_2)

What is the output of the following code? name = 123 if name.startswith("a"): print("welcome") else: print("please wait")

please wait

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

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

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("\\\\\\\\")

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

True

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

TypeError

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

TypeError

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)

name = "skye homsi" name_1 = name.title() name_2 = name_1.swapcase() print(name_2) What is the output from the above code?

"sKYE hOMSI"

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"

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

NameError

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"

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?

A. No answer text provided.

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

D. .upper()

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

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 code print("I am", 17, "years old") will output: I am17years old

False

The first character in a string is at index 1.

False

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

False

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

False

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

Falsenew_string = "Hello " + "World!"

Analyze the following code and choose the most correct statement: even = False if even = True: print("It is even!")

The program has a SyntaxError in line 2: if even = True:

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

True

Jupyter Notebooks have code cells and markdown cells.

True

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 double equal sign (==) is used to compare values.

True

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

True

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

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

name = "SKYE HOMSI" print("y" in name.lower()) What is the output from the above code?

True

What are the advantages of creating and using functions in code? (Choose all that apply.)

code reuse easier testing

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

ef add_numbers(num_1, num_2):

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

forever loop

Given the following string: s = "Welcome" which code results in an error?

print(s + 1)

Given the code below and entering "Colette" for user_name input: python total_cost = 22.95 user_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")

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

Which statement sets the variable s to a value of "Chapter1"?

s = "Chapter" + str(1)

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

showname()

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

str

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

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

x<3


Related study sets

Transporters, Pumps and Channels

View Set

NURS 306 Final exam sample Q's from discussion board

View Set

ATI Fundamentals Practice Exam A

View Set

Parts of Speech: Gerunds, Participles, and Infinitives

View Set

FERPA and ISSRA: Confidentiality of Student Records

View Set