213k views
5 votes
Write a function called stop_at_four that iterates through a list of numbers. Using a while loop, append each number to a new list until the number 4 appears. The function should return the new list.

1 Answer

6 votes

Answer:

def stop_at_four(input_list):

output_list = []

index = 0

while index < len(input_list):

if input_list[index] != 4:

output_list.append(input_list[index])

index += 1

else:

break

return output_list

Step-by-step explanation:

The function stop_at_four has an argument (input_list) which is the list of numbers we want to test.

The output_list is the list of the new numbers that will be generated.

index=0 is the counter with an initial value of 0

The while loop contains an if statement that ensures that a number that is being checked on the input list which is not equal to 4 is appended to the output_list and the counter increases.

The while loop encounters the break statement once a number 4 appears in the list of numbers.

It returns the output_list which contains numbers without 4.

User Jerreck
by
3.7k points