Interactive Python List Quiz 1

Interactive Python Code Quiz

Problem Context

Your monthly expenses are stored in a list. Review the initial code below and then answer the questions that follow by writing the correct Python code.

# Initial monthly expenses
# January to May
exp = [2200, 2350, 2600, 2130, 2190]

Quiz Questions

1. What Python code finds how many extra dollars you spent in Feb compared to Jan?

Show Answer & Explanation

Correct Code: exp[1] - exp[0]

Explanation: Python lists are zero-indexed.

  • January's expense (2200) is at index 0: exp[0]
  • February's expense (2350) is at index 1: exp[1]

This code subtracts the value at index 0 from the value at index 1, giving 2350 - 2200 = 150.

2. What Python code finds your total expense in the first quarter (first three months)?

Show Answer & Explanation

Correct Code: exp[0] + exp[1] + exp[2]

Alternative: sum(exp[0:3]) is also a great answer!

Explanation: The first quarter includes Jan (exp[0]), Feb (exp[1]), and March (exp[2]). Summing them gives 2200 + 2350 + 2600 = 7150.

3. What Python code checks if you spent exactly 2000 dollars in any month?

Show Answer & Explanation

Correct Code: 2000 in exp

Explanation: The in operator checks if a value exists in a list. It returns a boolean (True or False). Since 2000 is not in the list, this code evaluates to False.

4. June's expense is 1980. What Python code adds this to the end of the list?

Show Answer & Explanation

Correct Code: exp.append(1980)

Explanation: The .append() method adds a single item to the very end of a list, modifying it in-place. After this code, the list becomes [2200, 2350, 2600, 2130, 2190, 1980].

5. You got a 200$ refund for April. What Python code corrects the list?

Show Answer & Explanation

Correct Code: exp[3] = exp[3] - 200

Alternative: exp[3] -= 200 is also correct!

Explanation: April is the 4th item, so it's at index 3 (exp[3]). This code takes the current value (2130), subtracts 200, and assigns the new value (1930) back to that same index.

Post a Comment

0 Comments