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.
>>>> def stop_at_four():
[PYTHON]
Answers
PSEUDOCODE
1 : Get the list of number
2 : Iterates through the list
3 : Append each number to a new list
4 : If number 4 appears, stop the loop and return the list
Code:
def stop_at_four(num_list):
new_list = []
counter = 0
while True:
if num_list[counter] == 4 and counter < len(num_list) - 1:
break
new_list.append(num_list[counter])
counter += 1
return new_list[:]
print(stop_at_four(input().split(' ')))
Example:-
Input: 1 5 7 3 4 7 8
Output: [1,5,7,3]
There are many complex approaches to this problem which requires comparatively lesser code than this but I want to make it simpler because Simple is better than complex.
Some Information :-
◉ While loop iterates as long as the condition remains true.
◉ We can return or use a copy of a list without making the list empty which generally occurs when we return the exact list from a function or block, by using the following syntax, list_name[:] , It is also called list-slicing.
◉ The python split function splits a string into a list by using the separator passed as the function's parameter.