Write a program that reads a list of integers into a list as long as the integers are greater than zero, then outputs the values of the list.
Ex: If the input is:
10
5
3
21
2
(a negative 6 goes after this but I don’t know how to get it to show)
the output is:
[10, 5, 3, 21, 2]
You can assume that the list of integers will have at least 2 values.
This is the code I used
user_numbers = int(input())
lst = []
while True:
user_numbers = int(input())
if user_numbers > 0:
break
lst.append(user_numbers)
print(user_numbers, ', ')
my output ends up like this:
5 ,
I have tried to change the " if user_numbers > 0" to "user_numbers < 0" but all that does it produce a EOF Error.
>Solution :
You want to stop when the number is negative, so the loop should break when user_numbers < 0, not when user_numbers > 0.
Also, the first line should be removed because you read an integer but don’t add it to the list.
Finally, you want to print the whole list at the end, not the last number, so it should be print(lst).
Updated code:
lst = []
while True:
user_numbers = int(input())
if user_numbers < 0: # We replace '>' with '<'
break
lst.append(user_numbers)
print(lst)