Interactive Python List Quiz 3

Interactive Odd Numbers Quiz

Problem Context

You want to write a script that creates a list of all odd numbers between 1 and a max number provided by the user. Review the original code below and then answer the questions.


max = int(input("Enter max number: "))

odd_numbers = []

for i in range(1, max):
    if i % 2 == 1:
        odd_numbers.append(i)

print("Odd numbers: ", odd_numbers)
        

Quiz Questions

1. What code asks the user "Enter max number: " and stores their input as an integer in the `max` variable?

Show Answer & Explanation

Correct Code: max = int(input("Enter max number: "))

Explanation: input() gets the text from the user, and int() converts that text into an integer (a whole number) so we can use it for calculations.

2. What code initializes an empty list named `odd_numbers` to store the results?

Show Answer & Explanation

Correct Code: odd_numbers = []

Alternative: odd_numbers = list() is also correct!

Explanation: This creates a new, empty list that we can add items to inside our loop.

3. What code starts a `for` loop to check every number from 1 up to (but not including) `max`?

Show Answer & Explanation

Correct Code: for i in range(1, max):

Smarter Alternative: for i in range(1, max, 2): is also correct and more efficient!

Explanation: range(1, max) iterates over every number. The range(1, max, 2) solution is better because it only iterates over the odd numbers (1, 3, 5, ...) from the start, so you wouldn't need the if statement in the next step.

4. What code checks if the current number `i` is odd?

Show Answer & Explanation

Correct Code: if i % 2 == 1:

Alternative: if i % 2 != 0: is also correct!

Explanation: The modulo operator % gives the remainder of a division. Any number divided by 2 will have a remainder of 1 if it's odd and 0 if it's even.

5. If the number is odd, what code adds the number `i` to the `odd_numbers` list?

Show Answer & Explanation

Correct Code: odd_numbers.append(i)

Explanation: The .append() method adds its argument (in this case, the value of `i`) to the end of the list.

6. What code prints the final list, preceded by the text "Odd numbers: "?

Show Answer & Explanation

Correct Code: print("Odd numbers: ", odd_numbers)

Alternatives: print(f"Odd numbers: {odd_numbers}") or print("Odd numbers: " + str(odd_numbers)) are also correct!

Explanation: This print() function displays the string literal "Odd numbers: " followed by the contents of the odd_numbers list.

Post a Comment

0 Comments