🔒 Access Required

Enter the exam password to continue

Incorrect password. Try again.
Progress Saved!

🎓 COMP 163 Practice Final Exam

Introduction to Programming - Practice Assessment

âąī¸ Time:
00:00:00
P1: 0/5
P2: 0/5
P3: 0/2
P4: 0/2
P5: 0/2
P6: 0/4

Part 1: Explain Code (20%)

Review each code block and select the choice that accurately explains what it does.

Question 1 4 points

Review the code block and select the choice that accurately explains what it does.

1price1 = 45
2price2 = 32.5
3total = (price1 + price2) / 2
4print(int(total))
This code assigns an integer value to price1 and a float value to price2. It then adds these prices and performs integer division by 2. The total variable stores an integer value and then this value is displayed.
This code assigns an integer value to price1 and a float value to price2. It then adds these prices and divides by 2 to calculate total. The total variable stores a float value and then this value is cast to an integer before being displayed.
This code assigns float values to both price1 and price2. It then adds these prices and divides them by 2. The total variable stores a float value that is cast to an integer before being displayed.
This code assigns float values to both price1 and price2. It then adds these prices and divides them by 2. The total variable stores an integer value and this value is displayed.
Question 2 4 points

Review the code block and select the choice that accurately explains what the function does.

1def format_text(text):
2 result = ""
3 for i in range(len(text)):
4 if i % 2 == 0:
5 result += text[i].lower()
6 else:
7 result += text[i].upper()
8 return result
9
10if __name__ == "__main__":
11 print(format_text("hello world"))
The function returns a new string containing only the characters from the original string that were at even positions (e.g., index 0, 2, 4).
The function returns a new string where each character at an even index is made lowercase, while characters at an odd index are made uppercase.
The function iterates through a string and, for each odd character, prints it on a new line, making it uppercase if its index is an even number.
The function returns a new string where each character at an even index is made uppercase, while characters at an odd index are unchanged.
Question 3 4 points

Review the code block and select the choice that accurately explains what the function does.

1def calculate_total(items, prices):
2 total = 0
3 for item in items:
4 total += prices[item]
5 return total
6
7if __name__ == "__main__":
8 price_list = {"burger": 5.99, "fries": 2.49, "drink": 1.99}
9 order = calculate_total(["burger", "fries", "fries"], price_list)
10 print(order)
The function takes a dictionary of item names and dictionary of prices. For each item in the first dictionary, it adds the price to a running total and returns the total price.
The function takes a list of string item names and a dictionary of prices. For each item name in the list, it looks up the price in the dictionary and adds that price to a running total. It returns the total price of all items in the list.
The function takes a list of string item names and a dictionary of prices. For each item name in the list, it looks up the price. If there is a duplicate item, the price is NOT added. It returns the total price.
The function takes a list of string item names and a dictionary of prices. For each item name, it looks up the price and adds that price to a running total. The floor, or rounded down value of the total is returned.
Question 4 4 points

Review the code block and select the choice that accurately explains what it does.

1cards = ["5H", "KD", "3C", "AH", "7S", "QH", "2D"]
2diamonds = 0
3
4for card in cards:
5 if "D" in card:
6 diamonds += 1
7print(f"There are {diamonds} Diamonds")
The cards variable stores a list of strings. The card variable stores an integer equal to the number of elements in cards. The diamonds variable stores a Boolean value.
The cards variable stores a string. The variable card stores each character in cards as the loop iterates. The diamonds variable is a counter incremented when card equals "D".
The cards variable stores a list of strings. The card variable stores an integer equal to the number of characters in cards. The diamonds variable stores a Boolean value.
The cards variable stores a list of strings. The variable card stores each element in the list as the loop iterates. The diamonds variable is a counter, initialized to 0 and incremented when the element contains "D".
Question 5 4 points

Which of the following statements is true about this code?

1room_assignments = {
2 "floor1": ["Oak", "Elm", "Pine"],
3 "floor2": ["Maple", "Birch", "Ash"],
4 "floor3": ["Cedar", "Spruce", "Willow"]
5}
6
7floor_choice = "floor2"
8print(f"Available rooms on {floor_choice}:")
9for room in room_assignments[floor_choice]:
10 print(room)
This code iterates through all of the items in the room_assignments dictionary and displays all of the keys.
This code iterates through all of the items in the room_assignments dictionary and displays all of the values.
The code accesses a specified floor from the dictionary and iterates through a dictionary of rooms to display only rooms matching a specified value.
The code accesses a specified floor from the dictionary and iterates through the list of rooms available on that floor to display each room name as output.

Part 2: Determine Output (25%)

Review each code block and type exactly what the interpreter would print out.

Question 1 5 points
âš ī¸ Type out only what the interpreter would print out. No extra quotes or prefixes.

Review the code block and select the choice that shows the correct output.

1a = not(True)
2b = "dog" != "Dog"
3c = a and b
4print(c)
true
false
True
False
Question 2 5 points
âš ī¸ Type out only what the interpreter would print out. No extra quotes or prefixes.

Review the following code. For your answer, type what this prints when run.

1message = "debugging"
2
3print(message[2])
4print(message[-2])
5print(message[0:3])
6print(message[::2])
Question 3 3 points
âš ī¸ Type out only what the interpreter would print out.

Review the following code. For your answer, type what this prints when run.

1inventory = {
2 "pens": "x101",
3 "paper": "x202",
4 "folders": "x303"
5}
6
7inventory["paper"] = "x999"
8del inventory["pens"]
9print(inventory["paper"])
Question 4 5 points
âš ī¸ You intentionally cannot run this code

Given the file pet_registry.txt with contents:

📄 pet_registry.txt golden retriever owned by Smith family on Oak St tabby cat owned by Jones family on Elm Ave golden retriever owned by Brown family on Pine Rd persian cat owned by Smith family on Oak St golden retriever owned by Davis family on Maple Dr

Review the following code.

1def count_pet_type(filename, pet_type):
2 with open(filename, "r") as f:
3 records = f.readlines()
4 pet_count = 0
5 for record in records:
6 if pet_type.lower() in record:
7 pet_count += 1
8 return pet_count
9
10print(count_pet_type("pet_registry.txt", "golden retriever"))

What does this code print when it is run?

Question 5 7 points
âš ī¸ Type out only what the interpreter would print out.

Review the following code. For your answer, type what this prints when run.

1threshold = 75
2test_results = {
3 "Alice": [80, 72, 90],
4 "Bob": [65, 75, 70],
5 "Carol": [88, 92, 75]
6}
7
8for student in test_results:
9 for score in test_results[student]:
10 if score >= threshold:
11 print(f"{score} - {student}")

Part 3: Debug Code (20%)

Fix the bugs in each code block. Press Run to test your code.

Part 3.1: Debug Code 10 points
â„šī¸ Note: To debug code, you may need to add, remove, or rewrite code.

The function count_vowels is intended to count the total number of vowels (a, e, i, o, u) in a given string. It should iterate through each character in the string and increment a counter when a vowel is found. The function should return the total count.

Output
Part 3.2: Debug Code 10 points
â„šī¸ Note: To debug code, you may need to add, remove, or rewrite code.

Read a file named temperatures.txt (which contains one temperature per line, possibly including empty lines or non-numeric lines like "N/A") and safely calculate the average of all valid float temperatures. If a value is blank, it should be skipped. If the value cannot be parsed into a float, use a default value of 72.0. The given file should result in an average of 74.0.

📄 temperatures.txt 68.5 75.0 82.5 N/A 70.0
Output

Part 4: Modify Code (20%)

Modify the code to meet the new requirements.

Part 4.1: Modify Code 10 points
â„šī¸ Note: To modify code, you may need to add, remove, or rewrite code.

The original purpose of the following code was to remove the first task from a to-do list, print a message that it was completed, and return the updated list.

However, there is a bug: when the list is empty, an exception occurs.

Modify the complete_task function so:

  1. If the list is not empty, remove the first item, print that it was completed, and return True.
  2. If the list is empty, print "No tasks remaining." and return False.
Output
Part 4.2: Modify Code 10 points
â„šī¸ Note: To modify code, you may need to add, remove, or rewrite code.

The following program was originally written to double a number that the user inputs. Modify the program so:

  1. The logic is moved into a function run_doubler()
  2. It continues to prompt the user until the user enters "quit"
  3. run_doubler() should return the number of times the user doubled a number
  4. The main calls run_doubler() and prints what was returned

Example output for inputs "5" then "quit":

Enter a number to double (or type quit): 5 10 Enter a number to double (or type quit): quit Thanks for using the doubler! == Doubled 1 numbers. ==
Output

Part 5: Parson's Problems (10%)

Drag the code blocks to the solution area and arrange them in the correct order.

Parson's Problem 1 5 points

Once rearranged, the function should print a "Rolling the dice..." message, pause for between 1 and 2 seconds (inclusive) and print the result of rolling two dice (each 1-6) added together.

â„šī¸ You will not use 3 of the blocks in your program (they are distractors).
đŸ“Ļ Drag from here
if __name__ == "__main__": roll_dice()
die1 = randint(1,6) die2 = randint(1,6)
import random import math def roll_dice():
die1 = random.randint(1,6) die2 = random.randint(1,6)
delay = randint(1,2) sleep(delay)
print("Rolling the dice...")
delay = random.randint(1,2) time.sleep(delay)
import random import time def roll_dice():
print(f"You rolled {die1 + die2}!")
✅ Drop blocks here
Parson's Problem 2 5 points

Once rearranged, the code should prompt a user to first input a movie genre and then a rating (G, PG, PG-13, R).

  • If both genre and rating are in their respective valid lists, print a message about searching for movies.
  • If neither genre nor rating is valid, print a message that neither are recognized.
  • Otherwise, print that one of the inputs is not recognized.
â„šī¸ You will use all of the blocks in your program.
đŸ“Ļ Drag from here
print(f"Neither {genre} nor {rating} are recognized.")
rating = input("What rating? ")
if genre in valid_genres and rating in valid_ratings:
valid_genres = ["Action", "Comedy", "Drama", "Horror"] valid_ratings = ["G", "PG", "PG-13", "R"] genre = input("What genre? ")
print(f"One of your inputs is not recognized.")
print(f"Searching for {genre} movies rated {rating}...")
elif genre not in valid_genres and rating not in valid_ratings:
else:
✅ Drop blocks here

Part 6: Evaluate GenAI Output (5%)

Evaluate the AI tool's output and select the most accurate assessment.

Question 1 1 point

You enter this prompt into an AI tool:

I need to count how many times a specific character appears in a string. What method should I use?

This is the output from the AI tool:

# To count occurrences of a character, use the count() method
text = "mississippi"
count_s = text.count("s")
print(count_s)
# This code will output 3 because there are 3 letter s's
The AI tool's output is accurate and will solve the problem.
The AI tool's output contains accurate details about Python code, but it is irrelevant to the problem.
The AI tool's output is inaccurate because the sample code displays 4 and not 3.
The AI tool's output is inaccurate because the syntax used in the code sample is incorrect.
Question 2 1 point

You enter this prompt into an AI tool:

In the product_prices dictionary, the keys are product names and the values are their prices. I want to display just the prices of all products. Write a loop that iterates through product_prices to show the prices.

This is the output from the AI tool:

product_prices = {"laptop": 999, "mouse": 25, "keyboard": 75, "monitor": 300}
for product in product_prices:
print(product)
The code output by the AI tool will produce a KeyError.
The code output by the AI tool will run without error and aligns with the request in the prompt.
The code output by the AI tool is insufficient because the request was to store the prices.
The AI tool's output doesn't fulfill the request. The provided code will display the product names and not the prices.
Question 3 1 point

You enter this prompt into an AI tool:

This code is producing a syntax error. Identify this error and help me debug my code: age = 17 if age >= 18: print("You can vote!") elif age >= 16 print("You can drive but not vote yet.")

The AI correctly identifies the issue and provides this corrected code:

age = 17
if age >= 18:
print("You can vote!")
elif age >= 16:
print("You can drive but not vote yet.")
The output successfully identifies the issue and debugs the code.
The output is irrelevant because it describes a change that is optional and doesn't identify the error.
The output is inaccurate because elif statements do not require a colon at the end.
The output is insufficient because it explains the code but doesn't debug it.
Question 4 1 point

You enter this prompt into an AI tool:

Review the description, parameters, and return value of this function and create it. is_positive(number) Description: Determines whether a number is greater than zero. Parameters: number (integer or float): The number to check Return value: A Boolean value of True if the number is greater than zero and False otherwise.

This is the output from the AI tool:

def is_positive(number):
if number >= 0:
return True
else:
return False
The function that is output by the AI tool includes return values that do not correspond to the details in the prompt.
The output consists of a function that will run without error and aligns with the request in the prompt.
The function that is output by the AI tool includes parameters that do not correspond to the details in the prompt.
The output consists of a function that aligns with the request in the prompt but uses the wrong comparison operator (>= instead of >).