Reputation: 21
I am creating a list of positive integers from user input. The list will have 5 values. in case of a negative input, that value will not go to the list and issue an error massage and ask for the number again. The issue I am having with my code is the loop is dropping after 5 execution. whereas, I want it to keep running untill I am getting 5 positive inetegers.
lists = []
for i in range(5):
s = int(input('Enter a number: '))
if s >= 0:
lists.append(s)
else:
print("Enter a valid number")
print(lists)
Upvotes: 0
Views: 199
Reputation: 8444
Use the while loop instead of the for loop:
while len(lists)<5:
s = int(input('Enter a number: '))
if s >= 0:
lists.append(s)
else:
print("Enter a valid number")
For loop is better suited for a known number of iterations, and while loop will check for a condition before it is executed.
Upvotes: 1
Reputation: 10624
You would better change it to a while loop, like below:
lists = []
while len(lists)<5:
s = int(input('Enter a number: '))
if int(s) >= 0:
lists.append(int(s))
else:
print("Enter a valid number")
Upvotes: 5