Home > Software engineering >  How do I make a for loop not accept negative integers in a list?
How do I make a for loop not accept negative integers in a list?

Time:10-21

Can anyone help me with this problem, I'm trying to make a for loop that does not accept any negative integers, therefore asking the user to enter a positive integer.

current = []
print("Enter 6 integers greater than 0")
for i in range(6):
    current.append(eval(input()))

CodePudding user response:

You just need to put an if statement,

current = []
print("Enter 6 integers greater than 0")
for i in range(6):
    input_value = input()
    if int(input_value) < 0:
        print('Not acceept negative numbers')
    else:
        current.append(input_value)
        

CodePudding user response:

if your getting your input from the user just turn the string into a list of int with list comprehension and then loop through it

    check = True
    answer = input("Please enter 6 integers greater than 0 separated by comas:")
    while check:
    list_1 = answer.split(",")
    num = [int(x) for x in list_1]
    for number in num:
        if number < 0:
            answer = input("Please do not enter negative integers. Enter 6 integers")
            break
        else:
            check = False
  • Related