Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Zybook 3.8 LAB: Read values into a list

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading