Computer Science Final Exam
What would be printed to the screen when the following program is run? def return_number(x): return x + 3 print(return_number(2))
5
Which values entered into 'my_list' would print a value of '-1' after the program has run? my_list = [...] num = 0 for thing in my_list: num = num - thing print(num)
5, -10, 6
What will the value of sum be after the following code runs? sum = 0 for i in range (0, 6, 2): for j in range (2): sum = sum + 1
6
How many times would the phrase 'codeHS' be printed in the following pseudocode: repeat 2 times repeat 4 times print "codeHS"
8 times
Evaluate the mathematical expression: 10 - 6 x (4 - 2) / 2 + 5.
9
What is the output of this program? class Toothpaste: flavor = "Mint" # size -- the number of ounces in a tube def __init__(self, size=6.3): self.size = size def __repr__(self): return "A " + str(self.size) + " tube of " + self.flavor + " toothpaste" class ChildToothpaste(Toothpaste): flavor = "Bubble gum" # Main Program whitening = Toothpaste() clean = ChildToothpaste() print(whitening) print(clean)
A 6.3 tube of Mint toothpaste A 6.3 tube of Bubble gum toothpaste
What is the difference between a for loop and a while loop?
A for loop repeats commands a specific number of times and a while loop repeats until a condition becomes false.
What is the output of the following program? class NationalPark: nation = "Chile" def __init__(self, name, area, location, year_established): self.name = name self.area = area self.location = location self.established = year_established def __repr__(self): return self.name + " National Park in" + self.location def print_complete_info(self): print(self.name + " National Park, Est." + str(self.established)) print("Location: " + self.location) print("Area: " + str(self.area)) # Main program chaco = NationalPark("Chaco", 58, "Chaco Province", 1954) print(chaco.nation) print(NationalPark.nation) chaco.nation = "Argentina" print(chaco.nation) print(NationalPark.nation)
Chile Chile Argentina Chile
Here is a partial definition of a User class. class User: user_id = 0 def __init__(self, name, age = 0): self.name = name self.age = age self.user_id = User.user_id User.user_id = User.user_id + 1 def __repr__(self): print(self.age) return "Name: " + self.name + ", ID: " + str(self.user_id) What kind of variable is user_id?
Class variable
Which of the following inheritance chains is not a good use of inheritance?
Cup inherits from Cat
What kind of data structure is user_data in the following declaration? user_data = {"name": "TJ", "age":24, "user_name":"artLover123"}
Dictionary
Consider this partial class definition for a Cellphone class. Which of the following statements is true about Cellphone when an instance is first created? class Cellphone: def __init__(self, color, model, weight): self.color = color self.model = model self.weight = weight # other Cellphone methods
Every instance is guaranteed to have the attributes color, model, and weight
Who created the Python programming language?
Guido van Rossum
Use the following definitions of foods and groceries. foods = ["apples", "eel", "kale"] groceries = ["apples", "eel", "kale"] Which of the following statements would evaluate to True about foods and groceries? I. foods == groceries II. foods is groceries
I only
Which of the following describes a task effectively broken into smaller parts? I. Writing a book by brainstorming, making an outline, and drafting the first chapter II. Comparing two different cameras III. Using your phone's calculator
I only
What does "unpacking" refer to in Python?
Initializing multiple variables at a time using a collection of values
What does the __init__ method do in a class definition?
It is a method called when a new instance of a class is created. It sets up instance variables and performs any other set up that needs to be done for the class.
What does the __eq__ method do in a class definition?
It is a method called when the == operator is called on an instance. It checks if two objects are equal.
What does the __repr__ method do in a class definition?
It is a method called when the instance needs to be printed. It provides a useful, human-readable description of an object.
Eliza will wear a coat if it is raining or if it is less than 50° F outside. Otherwise, Eliza will leave her coat at home. In which of the following cases will Eliza leave her coat at home?
It is not raining and 50°F
What does "packing" refer to in Python?
Storing multiple variables' values by putting them in a collection, like a list or tuple
Python is extensively used by many large organizations.
TRUE
Why is the Python programming languaged named "Python?"
The creator was a big fan of Monty Python.
What does self refer to in a method?
The instance calling the method
What list is produced using the following list comprehension? word = "butterfly" [w for w in word]
['b', 'u', 't', 't', 'e', 'r', 'f', 'l', 'y']
What will be the output of the following program? my_list = [1, 2, 3, 4] num = 5 for index in range(len(my_list)): my_list.append(num + index) print(my_list)
[1, 2, 3, 4, 5, 6, 7, 8]
Given the following list, my_list = [ [0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11] ] what will be printed when the following line of code is called? print(my_list[3][1:])
[10, 11]
What does this program print? heights = [65, 56, 67, 48, 64] heights.sort() heights.extend([60, 61, 62]) heights.remove(67) print(heights)
[48, 56, 64, 65, 60, 61, 62]
What is the result of word[-3] if word = "chalkboard"?
a
Which of the following lines of code will cause an error? Use the following definition of ages: ages = (12, 5, 8)
ages[0] = 3
What does this code snippet print? fruit = ["b", "n", "n"] print("a".join(fruit))
banan
Which of the following code snippets will create this 2D list? [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]
board = [] board.append([1, 2, 3]) board.append([4, 5, 6]) board.append([7, 8, 9])
Which of the following assignment statements is equivalent to the following code snippet? coffee, tea, smoothie = ["kona", "mango", "raspberry"]
coffee = "kona" tea = "mango" smoothie = "raspberry"
What is the type of the variable x if x = 5?
int
A dictionary maps:
keys to values
Which of the following boolean expressions would make the while loop find the first animal in the list whose length is longer than 8? animals = ['snowy owl', 'salamander', 'bunny', 'octopus', 'squirrel', 'buffalo'] cur = 0 while ____________: cur +=1 print("First animal with length longer than 8 is " + animals[cur])
len(animals[cur]) <= 8
What is the output of this program? plants = { "tree" : "oak", "flower" : "daisy", "weed" : "bindweed" } for plant in plants: print(plants[plant])
oak daisy bindweed
Given the following list, my_list = [ [0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11] ] which line of code will print the following output? [[3, 4, 5], [6, 7, 8]]
print(my_list[1:3])
Given the following list, my_list = [ [0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11] ] Which line of code would print the number '5' to the screen?
print(my_list[1][2])
Which of the following assignment statements is equivalent to the following code snippet? red, blue, green = "BLUE", "GREEN", "RED"
red = "BLUE" blue = "GREEN" green = "RED"
Which of the following operations will cause an error?
ribbon_colors = ("blue", "red", "green") ribbon_colors[2] = "silver"
Which of the following snippets correctly defines the method get_value for the Gemstone class shown below? class Gemstone: def __init__(self, weight, cost_per_ounce): self.weight = weight self.cost_per_oz = cost_per_ounce
# returns how much the stone is worth def get_value(self): return self.weight * self.cost_per_oz
What is the value of num after this code runs? shapes = ["triangle", "square", "hexagon", "circle", "pentagon"] num = len(shapes)
5
Consider the following code: total = 0 for i in range(5): total += i print(total) What is the result of running this program code?
10
What is the output of this program? dimensions = [ [12, 3, 5], [45, 7, 8], [1, 2, 3] ] for row in dimensions: for num in row: print(num)
12 3 5 45 7 8 1 2 3
Here is a partial definition of a User class. class User: user_id = 0 def __init__(self, name, age = 0): self.name = name self.age = age self.user_id = User.user_id User.user_id = User.user_id + 1 def print_id(self): print(self.age) return "Name: " + self.name + ", ID: " + str(self.user_id) If an object were created as shown below, what would the print statement in print_id output if called on the object? sergei = User("Sergei", 15)
15
What year was Python released?
1991
Here is a partial definition of a User class. class User: user_id = 0 def __init__(self, name, age = 0): self.name = name self.age = age self.user_id = User.user_id User.user_id = User.user_id + 1 def __repr__(self): print(self.age) return "Name: " + self.name + ", ID: " + str(self.user_id) Given the following object declarations, what would the value of tomiko.user_id be? roxie = User("Roxie", 14) lyle = User("Lyle", 8) tomiko = User("Tomiko", 24)
2
What is the total forward distance moved when the code below is run? def move_forward(): for i in range (2): forward(50) move_forward() move_forward()
200
Given the following piece of code, what will be printed when the loop ends? class Animal: # Animal class implementation class Cat(Animal): # Cat class implementation # Main program pets = [Cat(), Animal(), Animal(), Cat(), Cat()] num_cats = 0 for elem in pets: if isinstance(elem, Cat): num_cats += 1 print(num_cats)
3
How many times does this program print That's a large class!? num_students = [23, 21, 33, 35, 24, 35] for num in num_students: if num > 23: print("That's a large class!")
4
Given the following piece of code, what will be printed when the loop ends? class Animal: # Animal class implementation class Cat(Animal): # Cat class implementation # Main program pets = [Cat(), Animal(), Animal(), Cat(), Cat()] num_cats = 0 for elem in pets: if isinstance(elem, Animal): num_cats += 1 print(num_cats)
5
What is wrong with the following function? def compute_total_pay(hourly_rate=10.5, overtime_rate=15, num_hours): if num_hours <= 40: return hourly_rate * num_hours return 40*hourly_rate + (num_hours - 40) * overtime_rate
Any parameters that don't have default values must come before any parameters that do have default values
Given the following code, which of the statements below is true about the relationship between these classes? class WaterBottle: # capacity -- the number of ounces the water bottle holds def __init__(self, capacity=24): self.capacity = capacity self.fullness = capacity # Take a drink # A drink takes 1 ounce away from the amount of liquid # actually held in the bottle def take_drink(self): if self.fullness > 0: self.fullness -= 1 def refill(self, num_ounces_added): if self.fullness + num_ounces_added <= self.capacity: self.fullness += num_ounces_added class AutomaticWaterBottle(WaterBottle): # temp -- the temperature at which to keep the liquid inside def __init__(self, capacity, temp): WaterBottle.__init__(self, capacity) self.temp = temp # more methods
AutomaticWaterBottle inherits from WaterBottle
What would the following program print to the screen when run? my_list = [7, 0, 0, "d", "n", "o", "B"] my_list.reverse() for thing in my_list: print(thing)
B o n d 0 0 7
What data type is returned from the __eq__ function?
Boolean
Which of the lines labeled below would print "Bubble gum"? class Toothpaste: flavor = "Mint" # size -- the number of ounces in a tube def __init__(self, size=6.3): self.size = size def __repr__(self): return "A " + str(self.size) + " tube of " + self.flavor + " toothpaste" class ChildToothpaste(Toothpaste): flavor = "Bubble gum" # Main Program whitening = Toothpaste() clean = ChildToothpaste() print(clean.flavor) # Line 1 print(whitening.flavor) # Line 2 print(Toothpaste.flavor) # Line 3 print(ChildToothpaste.flavor) # Line 4
Line 1 and Line 4
What kind of data structure is user_data in the following declaration? user_data = ["TJ", 24, "artLover123"]
List
What would be the output of the following code? text = "hello" if "a" in text: print("Yes") elif "ll" in text: print("Maybe") else:print("No")
Maybe
What does this program print? sentence = "My favorite animal is a dog or chipmunk" sentence_list = sentence.split() sentence_list[-3] = "penguin" sentence = " ".join(sentence_list) print(sentence)
My favorite animal is a penguin or chipmunk
What is the purpose of using inheritance among classes?
To easily add additional functionality to an existing class. It makes your code easier to maintain, since code is not copied all over the place.
What is the purpose of using classes?
To logically group data and methods together.
What would be the output of the following code? for i in range(2): print("Tracy") print("Turtle")
Tracy Tracy Turtle
What would the output of the following code be? x = "Tracy" print(x * 5)
TracyTracyTracyTracyTracy
What kind of data structure is user_data in the following declaration? user_data = ("TJ", 24, "artLover123")
Tuple
Which of the following data structures is immutable?
Tuple
The following snippet is from a program that asks the user what he/she wants to order. The user's input is stored in the variable item_ordered. If the user enters 3, what will the following code snippet print? item_ordered = input("Enter the name of the item you wish to order: ") try: print("You have ordered the following item: " + item_ordered) except TypeError: print("I'm sorry. You have entered an invalid item.")
You have ordered the following item: 3
What would be the output of the following code? colors = ["red", "green", "blue", "yellow"] color.reverse() colors.append("orange") colors.sort() print(colors)
["blue", "green", "orange", "red", "yellow"]
What is the value of the list after this program runs? days = ['Mon', 'Tues', 'Wed', 'Thurs', 'Fri'] days.reverse() days.extend(['Sat', 'Sun'])
['Fri', 'Thurs', 'Wed', 'Tues', 'Mon', 'Sat', 'Sun']
What function would you use to get the position of a character in a string?
find
Given the following 2D list, which of the following expressions would get the element "cucumber"? food = [ ["apple", "banana", "kumquat"], ["cucumber", "onion", "squash"], ["candy", "soda", "sugar"] ]
foods[1][0]
Given the following list: my_list = ["s", "Z", "e", "c", "c", "e", "r", "h", "e", "p", "t"] which program below would give the following output: s e c r e t
for index in range(len(my_list)): if index % 2 == 0: print(my_list[index])
Which of the following programs would produce the following output: 1. honey 2. bread 3. jelly 4. plates
my_list = ["honey", "bread", "jelly", "plates"] for index in range(len(my_list)): print(str(index+1) + ". " + my_list[index])
Which of the following programs would alter my_list to consist of the following: ['red', 'green', 'blue', 'orange', 'yellow']
my_list = ['red', 'green', 'blue', 'orange'] my_list.append('yellow')
Which of the following list comprehensions will create the same list as the for loop below? my_list = [] for i in range(6): my_list.append(i*2)
my_list = [i*2 for i in range(6)]