191k views
1 vote
The following code causes an infinite loop. Can you figure out what’s incorrect and how to fix it?

def count_to_ten():
# Loop through the numbers from first to last
x = 1
while x <= 10:
print(x)
x = 1

A. should use a for loop instead of a while loop
B. The X variable is initialized using the wrong value
C. Variable X is assigned the value 1 in every loop
D. Needs to have parameters passed to the function

1 Answer

2 votes

Answer: The issue with the code is that the variable x is assigned the value of 1 in every loop, which means the condition x <= 10 will always be true, causing an infinite loop. To fix the issue, the variable x should be incremented in each loop, not set back to 1. Here's the corrected code:

def count_to_ten():

# Loop through the numbers from first to last

x = 1

while x <= 10:

print(x)

x += 1

Explanation: Option C correctly identifies the issue and the corrected code fixes it by incrementing x by 1 in each loop. Therefore, the correct answer is C.

User Coltuxumab
by
8.3k points