asked 133k views
5 votes
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 -6 the output is: [10, 5, 3, 21, 2] You can assume that the list of integers will have at least 2 values.

2 Answers

3 votes

Final answer:

To write a program that reads a list of integers into a list until the integers are greater than zero, you can use a while loop. Here's the Python code: num_list = []; while True: num = int(input("Enter an integer: ")); if num <= 0: break; num_list.append(num); print(num_list)

Step-by-step explanation:

To write a program that reads a list of integers into a list until the integers are greater than zero, you can use a while loop. Here's the Python code:

num_list = []

while True:
num = int(input("Enter an integer: "))
if num <= 0:
break
num_list.append(num)

print(num_list)

This code initializes an empty list, then iterates using a while loop, asking the user for an integer input. If the input is less than or equal to zero, the loop breaks. Otherwise, the integer is added to the list. Finally, the list is printed as the output.

answered
User Cory Loken
by
7.4k points
3 votes
# Initialize an empty list to store the integers
integer_list = []

# Read integers until a non-positive integer is encountered
while True:
num = int(input("Enter an integer (0 or negative to stop): "))
if num
answered
User Shawndreck
by
7.8k points

No related questions found