Python Final

Ace your homework & exams now with Quizwiz!

What is the output of the following code snippet? i = 1 while i <= 10 : print("Inside the while loop") i = i + 10

"Inside the while loop" will be displayed only once.

Which of the following is considered a string in Python?

"Today is Wednesday"

What symbol is used to begin a comment in a Python program?

#

Which output format string correctly allows for 5 positions before and two digits after the decimal point?

%8.2f

What is the output of the code snippet given below? n = 0 while n * n < 100 : print(n * n, end = " ") n = n + 1

0 1 4 9 16 25 36 49 64 81

What is the output if the function call is testMyVal(6) in the following code snippet? def testMyVal(a) : if a > 0 : testMyVal(a - 2) print(a, end = " ")

0 2 4 6

What is the output of the code snippet given below? i = 0 while i != 11 : print(" ", i) i = i + 2

0 2 4 6 8 ... (infinite loop)

Consider the following code segment: c = 2 b = 1 if b == 0 : c = c + 1 else : c = c - 1 print(c) What value is printed by this code segment?

1

Consider the following code segment: numPizzas = 1 numPeople = 4 if numPeople == 5 : numPizzas = 2 After this code segment executes, what value is in the variable numPizzas?

1

Given the following code snippet, what is the value of the variable indexValue? states = ["Alaska", "Hawaii", "Florida", "Maine", "Ohio", "Florida"] indexValue = states.index("Hawaii")

1

What is the output from the following Python program? def myFun(perfect) : perfect = 0 return ((perfect - 1) * (perfect - 1)) def main() : for i in range(4) : print(myFun(i), end = " ") main()

1 1 1 1

What is the output of the following code snippet? i = 1 while i < 20 : print(i , " ") i = i + 2 if i == 15 : i = 19

1 3 5 7 9 11 13 19

What is the value of j at the end of the following code segment? j = 0 for i in range(1, 10) : if j < 10 : j = j + i

10

What will be printed by the statements below? for ctr in range(10, 5, -1) : print(ctr, end = " ")

10 9 8 7 6

How many times does the following code snippet display "Loop Execution"? for i in range(0, 10) : print("Loop Execution")

10 times

What is the output of this loop?counter = 1for i in range(1, 100) : counter = counter + 1print(counter)

100

How many times does the following loop execute? i = 0 found = False while i < 100 and found != True : i = i + 1 print(i, end = " ") j = i * i if i * i * i % j == j : found = True

100 times

What is printed by the following code snippet? print(25 + 84)

109

What is the output of the following code snippet? num1 = 100 if num1 < 100 : if num1 < 50 : num1 = num1 - 5 else : num1 = num1 - 10 else : if num1 > 150 : num1 = num1 + 5 else : num1 = num1 + 10 print(num1)

110

What is the output of the code snippet given below? s = "12345" i = 0 while i < 5 : print(s[i]) i = i + 1

12345

How many times does the code snippet below display "Hello"? i = 0 while i != 15 : print("Hello") i = i + 1

15 times

What will be printed by the following code snippet? name = "Dino the Dinosaur" counter = name.count("Di") print(counter)

2

Consider the following code segment: if a == 0 : print("a is 0") elif a < 0 : print("a is less than 0") else : print("a is greater than 0") What is the minimum number of test cases needed to test every line of code in this segment?

3

What is the output of this code snippet? str = "ABCabc" i = 0 while i < len(str) : ch = str[i] if ch.islower() : print(i , " ") else : i = i + 1

3 3 3 3 3 ... (infinite loop)

Consider the following code segment: if count > 0 : x = x + 1 print(x) If count is initialized to -1 and x is initialized to 4 then the value displayed by this code segment is:

4

Consider the following function call ceil(3.14159) what is the return value?

4.0

Consider the following function: def mystery(a, b) : result = (a - b) * (a + b) return result What is the result of calling mystery(3, 2)?

5

How many times does the while loop execute? s = "abcdEfghI" found = False count = 0 while found == False : if s[count].isupper() : print(letter) found = True count = count + 1

5 times

What is the value of j at the end of the following code segment? j = 0 for i in range(0, 4) : j = j + i

6

What is printed by the following code snippet? num = int("45") * float("1.5") print(num)

67.5

What is wrong with the following code snippet? num = 78A

78A is not a valid value in a Python program

Consider the following function: def squareArea(sideLength) : return sideLength ** 2 What is the value of squareArea(3)?

9

What is the last output line of the code snippet given below? i = 0 j = 0 while i < 10 : num = 1 j = i while j > 1 : print(j, end = " ") num = num * 2 j = j - 1 print("***") i = i + 1

9 8 7 6 5 4 3 2 ***

How many times will the output line be printed in the following code snippet? for num2 in range(1, 4) : for num1 in range(0, 3) : print(num2, " ", num1)

9 times

Consider the following functions: def printIt(x) : print(x) def incrementIt(x) : return x + 1 def decrementIt(x) : return x - 1 def doubleIt(x) : return x * 2 Which of the following function calls is not a reasonable thing to do?

print(printIt(5))

Which of the following statements correctly prints the result of simulating the toss of a pair of coins to get 0 (heads) or 1 (tails) for each coin?

print(randint(0, 1), randint(0, 1))

Assuming that the user provides 303 as input, what is the output of the following code snippet? y = int(input("Please enter a number: ")) if y > 300 : x = y else : x = 0 print("x:", x)

x: 303

How many return statements can be included in a function?

zero or more

What is the value of x after the following code segment executes? x = {1, 2, 3} x.add(1)

{1, 2, 3}

What is the index value of the letter 'h' in the string below ? message = "hello"

0

What is the last output line of the code snippet given below? for i in range(3) : for j in range(5) : if i % 2 == j % 2 : print("*", end="") else : print(" ", end="") print()

* * *

What value is displayed by the following code segment? s = "Computer Science" x = s.find("TER") print(x)

-1

What value is printed by the following code snippet? name = "John R. Johnson" firstName = "Joe" location = name.find(firstName) print(location)

-1

How many copies of the letter B are printed by the following loop? i = 0 while i == 5 : print("B") i = i + 1

0

What are the two parts of an if statement?

A condition and a body

What is stored in contents when a sound file is read by the scipy library using the following statement? contents = scipy.io.wavfile.read("meow.wav")

A tuple containing the sample rate and a NumPy array

When hand-tracing a portion of code, which statement about Boolean conditions is true?

They are crucial to evaluate since they determine if-statement conditions and looping.

A loop inside another loop is called:

a nested loop

Which of the following items is NOT considered hardware:

a program

What is the purpose of the following pseudocode: i = 0 j = length / 2 While i < length / 2 # Swap elements at positions i and j temp = a[i] a[i] = a[j] a[j] = temp i = i + 1 j = j + 1

flip the first half of a list with the second half

When testing code for correctness, it always makes sense to

Aim for complete coverage of all decision points

Consider the follow code segment. It is supposed to convert numeric marks to letter grades. However, it may contain a bug. Examine the program, and identify what bug, if any, is present grade = "F" if mark >= 80 : grade = "A" if mark >= 70 : grade = "B" if mark >= 60 : grade = "C" if mark >= 50 : grade = "D"

All instances of if, except the first, need to be replaced with elif

Given a list values that contains the first ten prime numbers, which statement prints the index and value of each element in the list?

for i in range(10) : print(i, values[i])

Given the list values = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], which statement fills the list with these numbers: 1 2 3 4 5 6 7 8 9 10

for i in range(10) : values[i] = i + 1

Which of the following code segments will display all of the lines in the file object named infile, assuming that it has successfully been opened for reading?

for line in infile : print(line)

Review the code snippet below: name1 = "Betty joe" name2 = "Betty Jean" name3 = "Betty Jane" if name1 < name2 : if name1 < name3 : print(name1, "is first") else : print(name3, "is first") else : if name2 < name3 : print(name2, "is first") else : print(name3, "is first") what output is produced?

Betty Jane is first

Which line of code will generate a random floating-point number between 0 and 6, and store it in x? Assume that the random function has been imported from the random module.

x = random() * 6

A collection of programming instructions that carry out a particular task is called a:

function

A(n) _____________________ is a collection of programming instructions that carry out a particular task.

function

The operator >= stands for

greater than or equal to

What are the values of i and j after the following code fragment runs? i = 60 j = 50 count = 0 while count < 5 : i = i + i i = i + 1 j = j - 1 j = j - j count = count + 1 print("i =", i, ", j =", j)

i = 1951, j = 0

What are the values of i and j after the following code snippet executes? i = 20 j = 70 count = 0 while count < 5 : i = i + i i = i + 1 j = j - 1 j = j - j count = count + 1 print(i) print(j)

i = 671, j = 0

What portable file format is commonly used to export data from a spreadsheet so that it can be read and processed by a Python program?

Comma-Separated Values (CSV)

Which of the following checks to see if there is a comma anywhere in the string variable name?

if "," in name :

Which of the following activities can be simulated using a computer? I. Waiting time in a line at a restaurant II. Tossing a coin III. Shuffling cards for a card game

I, II, and III

Which of the following statements is the best choice to validate user input when entering a marital status as a single letter?

if (maritalStatus == "s" or maritalStatus == "m" or maritalStatus == "S" or maritalStatus == "M") :

Which of the following conditions is True only when the variables a, b, and c contain three different values?

if a != b and a != c and b != c :

Rewrite the following algebraic expression to an equivalent Python expression: 32 <= temp <= 100

if temp >= 32 and temp <= 100

What term is used to describe a loop where the number of times that the loop will execute is known before the body of the loop executes for the first time?

Definite

What is displayed by the following code segment? values = ["Q", "W", "E", "R", "T", "Y"] print(min(values))

E

What does the following code snippet display? for n in range(1, 11) : for x in range(1, 11) : print(n*x, end = " ") print()

It displays a multiplication table for numbers 1-10 times 1-10

What does the following code segment do? x = 0 for i in range(1, len(values)) : if values[i] > values[x] : x = i

It finds the position of the largest item in values and stores the position in x

In the code snippet below, if the file contains the following words: Monday! Tuesday. Wednesday? stored one per line, what would be the output? infile = open("input.txt", "r") for word in infile : word = word.lstrip(".!") print(word)

Monday! Tuesday. Wednesday?

Which of the following is an appropriate constant name to represent the number of pencils in a pack?

NUM_PENCILS_PER_PACK = 12

What is stored in pos when the following code segment executes? values = ["J", "Q", "X", "Z"] pos = values.find("Y")

No value is stored because a runtime exception occurs

Is the code snippet written below legal? s = "1234" for i in range (0, 4) : print(s[i], s[i + 1])

No; for i = 3, s[i + 1] will result in an string index out of range error.

Consider the following code snippet: age = int(input("Enter your age:")) if age < 10 : print("Child", end="") if age < 30 : print("Young Adult", end="") if age < 70 : print("Old", end="") if age < 100 : print("Impressively old", end="") Assuming that the user inputs 30 as the age, what is the output?

OldImpressively old

Which of the following statements is NOT correct?

Pseudocode should be properly formatted.

Consider the following code segment: title = "Python for Everyone" newTitle = title.replace("e", "*") After this code runs, the value stored in newTitle is:

Python for Ev*ryon*

What error will Python display when it attempts to execute the following if/else statement? if a == b : print("Equal") else : print("Not Equal") if a > b : print("a is larger") else : print("b is larger")

Python will display an error indicating that there is a problem with the indentation

What will happen when the following code segment is executed? values = [1.618, 2.71, 3.14] print(values[3])

Python will display an out-of-range error

The following pseudocode calculates the total purchase price for an item including sales tax, what is the missing last line? Start by setting the total cost to zero. Ask the user for the item cost. Ask the user for the tax rate. Set the item tax to item cost times tax rate. _________________________________

Set the total cost to the item cost plus the tax.

What is the output for the following code snippet: area = 25 print("The area is %05d" % area)

The area is 00025

The ceil function in the Python standard library math module takes a single value x and returns the smallest integer that is greater than or equal to x. Which of the following is true about ceil(56.75)?

The argument is 56.75, and the return value is 57

Based on the code snippet, which of the following statements is correct? def main() : reoccur(1) def reoccur(a) : print(a) reoccur(a + 1) main()

The code snippet executes and infinitely recurses, displaying 1, 2, 3, 4, and so on.

Imagine that you are planning to buy a new cell phone. After doing some research, you have determined that there are two different cell phones that will meet your needs. These cell phones have different purchase prices and each mobile service provider charges a different rate for each minute that the cell phone is used. In order to determine which cell phone is the better buy, you need to develop an algorithm to calculate the total cost of purchasing and using each cell phone. Which of the following options lists all the inputs needed for this algorithm?

The cost of each cell phone, the rate per minute for each cell phone, and the number of minutes you would use the cell phone

What is wrong with the following code snippet: file = open("lyrics.txt", "w") line = file.readline() words = line.split() print(words) file.close()

The file has only been opened for writing, not reading.

Assuming the user enters 15 as input, what is the output of the following code snippet? number = int(input("Please enter a number: ")) if number >= 20 : print("The numer is big") else : print("The number is small")

The number is small

What is printed by the following code segment? position = 0 str = input("Enter a string: ") while position < len(str) and str[position] != 'e' : position = position + 1 print(position)

The position of the first 'e' in the string or the length of the string if there is no 'e'

Which of the following statements about variables is true?

The same variable name can be used in two different methods.

Which statement about if statements is not correct?

The statements in a statement block must be indented 2 spaces more than the header.

What is the output of the following code fragment? i = 1 sum = 0 while i <= 11 : sum = sum + i i = i + 1 print("The value of sum is", sum)

The value of sum is 66

What is the purpose of the following algorithm, written in pseudocode? num = 0 Repeat the following steps 15 times Ask user for next number If userNum > num num = userNum Print num

To find the highest among 15 numbers

What is printed by the following code snippet if itemCount contains a value of 10 and cost contains 80: if itemCount > 5 : discount = 0.8 totalCost = cost * discount print("Total discounted price is:", totalCost)

Total discounted price is: 64.0

Consider the following code segment: if a == b : print("W") else : print("X") if b == c : print("Y") else : print("Z") If a, b and c are all 0 then the output generated by this code segment is:

W

Consider the following code segment: print("W", end="") try : inFile = open("test.txt", "r") line = inFile.readline() value = int(line) print("X", end="") except IOError : print("Y", end="") except ValueError : print("Z", end="") What output is generated when this program runs if test.txt is not opened successfully?

WY

Consider the following code segment: if a == b : print("W") else : print("X") if b == c : print("Y") else : print("Z") If a is 0, b is 1 and c is 1 then the output generated by this code segment is:

X followed by Y on the next line

Consider the following code segment: if a == b : print("W") else : print("X") if b == c : print("Y") else : print("Z") If a is 0, b is 1 and c is 0 then the output generated by this code segment is:

X followed by Z on the next line

Is the following code snippet legal? b = False while b != b : print("Do you think in Python?")

Yes, it is legal but does not print anything.

What is the output of the following code snippet if the cost contains 100: if cost > 150 : discount = 0.8 * cost else : discount = cost print("Your cost is:", discount)

Your cost is: 100

It is good programming practice to plan for possible exceptions and provide code to handle the exception. Which exception must be handled to prevent a divide by zero logic error?

ZeroDivisionError

What is in grades after the follow code segment executes? grades = ["A", "B+", "C", "C+", "C", "B-"] grades.remove("C")

["A", "B+", "C+", "C", "B-"]

What is output by the following code segment? values = ["Q", "W", "E", "R", "T", "Y"] print(values[2 : 4])

["E", "R"]

Given the following code snippet, what are the contents of the list fullNames? firstNames = ["Joe", "Jim", "Betsy", "Shelly"] lastNames = states = ["Jones", "Patel", "Hicks", "Fisher"] fullNames = firstNames + lastNames

["Joe", "Jim", "Betsy", "Shelly", "Jones", "Patel", "Hicks", "Fisher"]

What will be stored in substrings after the following code snippet has run? states = "Michigan,Maine,Minnesota,Montana,Mississippi" substrings = states.split(",")

["Michigan", "Maine", "Minnesota", "Montana", "Mississippi"]

What is the value of names after the following code segment has run? names = [] names.append("Amy") names.append("Bob") names.append("Peg") names[0] = "Cy" names.insert(0, "Ravi") names.insert(4, "Savannah")

['Ravi', 'Cy', 'Bob', 'Peg', 'Savannah']

What list is stored in x after this code segment has run? x = [] for i in range(3) : x.append([]) for j in range(i) : x[j].append(0)

[[0, 0], [0], []]

When reading a file in Python, you must specify two items:

a file name and mode

What is printed after executing the following code snippet? somelist = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"] for i in range(len(somelist)) : print(somelist[i], end = "")

abcdefghijklmnopqrstuvwxyz

Given the following code snippet, which statement correctly allows the function to update the global variable total? 1. total = 0 2. def main() : 3. avg = 0 4. for i in range(6) : 5. iSquared = i * i 6. total = total + iSquared 7. avg = total / i 8. print(total) 9. print(avg)

add the statement global total after line 2

What is it called when you describe the steps that are necessary for finding a solution to a problem in programming?

algorithm

A sequence of steps that is unambiguous, executable, and terminating is called:

an algorithm

Which operator has the lowest precedence?

and

In the code snippet below, if the file contains the following words: apple, pear, and banana stored one per line, what would be the output? infile = open("input.txt", "r") for word in infile : word = word.rstrip() print(word)

apple pear banana

What is supplied to a function when it is called?

arguments

Consider a function named avg, which accepts four numbers and returns their average. Which of the following is a correct call to the function avg?

average = avg(2, 3.14, 4, 5)

Which of the following variables is used to store a condition that can be either True or False?

boolean

The location where the debugger stops executing your program so that you can inspect the values of variables is called a(n):

breakpoint

The tool that allows you to follow the execution of a program and helps you locate errors is known as a(n):

debugger

You are writing a function that converts from Liters to Gallons. Which function header is the best?

def litersToGallons(liters) :

Given a text file quote.txt that contains this sentence: "Home computers are being called upon to perform many newfunctions, including the consumption of homework formerly eaten bythe dog. ~Doug Larson" What is the result of this code snippet: inputFile = open("quote.txt", "r") char = inputFile.read(1) while char != "" : print(char) char = inputFile.read(1) inputFile.close()

each character of the quote is printed on a separate line

Consider the following code segment: try : inputFile = open("lyrics.txt", "r") line = inputFile.readline() print(line) _____________________ print("Error") What should be placed in the blank so that the program will print Error instead of crashing if an exception occurs while opening or reading from the file?

except IOError :

Consider the following code segment. It is designed to identify the first location within a string, text where two adjacent characters are the same. i = 1 found = False while not found and i < len(text) : ____________________ : found = True else : i = i + 1 What line of code should be placed in the blank to achieve this goal?

if text[i] == text[i - 1] :

Which type of statement should be used to choose exactly one of several alternatives?

if-elif-else

How many copies of the letter C are printed by the following loop? i = 0 while i < 5 : print("C") i = i - 1

infinty

What function is used to read a value from the keyboard?

input

What is the output of the code fragment given below? i = 0 j = 0 while i < 27 : i = i + 2 j = j + 1 print("j =", j)

j = 14

Which statement finds the last letter of the string variable name?

last = name[len(name) - 1]

The following program opens test.txt and displays its contents. If nothing is placed in the blank, then the contents of the file is displayed double spaced. What should be placed on the blank so that the contents of the file is displayed without the extra blank lines? infile = open("test.txt", "r") line = infile.readline() while line != "" : ____________________ print(line) line = infile.readline() infile.close()

line = line.rstrip()

Given the following code snippet, what is printed? nums = [1, 2, 3, 4, 5] nums2 = [5, 4, 3, 2, 1] if nums == nums2 : print("lists are equal") else : print("lists are not equal")

lists are not equal

Which of the following hardware devices is NOT considered an output device?

microphone

Which of the following hardware devices is NOT considered an input device?

monitor

Assume that the following import statements appear at the beginning of your program: from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.image import MIMEImage from email.mime.application import MIMEApplication Which statement creates a new email message that can contain both text and images?

msg = MIMEMultipart()

Which statement evaluates to True when comparing the two strings: name1 = "Heather" name2 = "hanna"

name1 < name2

Suppose that b is False and x is 0. Which of the following expressions evaluates to True?

not b or x == 1

Consider the following code segment: if a > b : print("X") if a == b : print("Y") What is displayed if a is 1 and b is 2?

nothing

Consider the following code snippet. num1 = 0 num2 = 0 num3 = 0 num4 = 0 num5 = 0 num1 = int(input("Enter a number: ")) num2 = int(input("Enter a number: ")) if num1 < num2 : num3 = num1 else : num3 = num2 if num1 < num2 + 10 : num4 = num1 elif num1 < num2 + 20 : num5 = num1 print("num1 =", num1, "num2 =", num2, "num3 =", num3, "num4 =", num4, "num5 =", num5) Assuming that the user enters the numbers 20 and 12 as the two input values, what is the output of the code snippet?

num1 = 20 num2 = 12 num3 = 12 num4 = 20 num5 = 0

Which statement(s) allows us to initialize the list numbers with 10 elements all set to zero?

numbers = [0] * 10

Assuming that a user enters 25 for the price of an item, which of the following hand-trace tables is valid for the given code snippet? price = 0 status = "" price = float(input("Enter the price for your item: ")) if price >= 50 : status = "reasonable" if price >= 75 : status = "costly" else : status = "inexpensive" if price <= 25 : status = "cheap"

price: status: 0 "inexpensive" 25 "cheap"

Suppose an input file contains a grocery list. Each line contains the item name followed by its cost. The item name and cost are separated by a comma. Which statements extract this information correctly?

record = inputFile.readline() data = record.split(",") groceryItem = data[0].rstrip() cost = float(data[1])

Which of the following methods strips specified punctuation from the front or end of each string ( s)?

s.strip(".!?;:")

Which parts of the computer store program code?

secondary storage

What library needs to be imported to send a message after it has been created?

smtplib

Which line of code will generate a random integer from 1 up to and including 10, and store it in x? Assume that the randint function has been imported from the random module.

x = randint(1, 10)

A messy network of possible pathways through a program is referred to as:

spaghetti code

Which code snippet is the correct Python equivalent to the following Algebraic expression ? c = √(a2 + b2)

sqrt(a ** 2 + b ** 2)

Which debugging command allows you to quickly run an entire function instead of examining its body a line at a time?

step over

What is the data type of the value returned by the input function?

string

Which of the following conditions can be added to the code below so it will loop until the value of sum is greater than 100? sum = input("enter an integer") while # Put condition here : sum = sum + input("Enter an integer")

sum <= 100

What is another name for a compile-time error?

syntax error

To use or call a function, you need to specify:

the function name and its arguments

Which part of an email message includes information about the sender and the recipient?

the header

For the list: prices = [10.00, 15.50, 13.25, 20.15], what value is contained in prices?

the location of the list

Which of the following items would not be a good object to use while solving algorithms such as swapping the first half of a list with the second half:

toothpicks

Consider a function named calc. It accepts two integer arguments and returns their sum as an integer. Which of the following statements is a correct invocation of the calc function?

total = calc(2, 3)

Which of the following statements stores the numbers 1 through 5 into a list named values?

values = [1, 2, 3, 4, 5]

The following program is supposed to count how many even numbers are entered by the user. What line of code must be inserted in the blank so that the program will achieve this goal? evens = 0 inputStr = input("Enter a value: ") ____________________ value = int(inputStr) if value % 2 == 0: evens = evens + 1 inputStr = input("Enter a value: ")

while inputStr != "" :

The following code segment is supposed to read all of the lines from test.txt and save them in copy.txt. infile = open("test.txt", "r") outfile = open("copy.txt", "w") line = infile.readline() ____________________ outfile.write(line) line = infile.readline() infile.close() outfile.close() Which line of code should be placed in the blank to achieve this goal?

while line != "" :

Which of the following statements causes Python to report an error?

x = 17 + "18.4"

The line of code which reads a value from the user and stores it in a variable named x as a floating-point value is:

x = float(input("Enter the value of x: "))


Related study sets

Chapter 12.4: POLITICAL TACTICS AND HOW TO USE THEM

View Set

Anatomy // Chapter 8 Special Senses

View Set