I'm trying to type a for loop so that when the user types a negative integer, it requires to user to type in a positive integer to move on. Note: The program required to have a for loop.
current = []
test = 1
print("Enter 6 integers greater than 0")
for i in range(6):
userInput = int(input())
if int(userInput) <= 0:
test = 0
while(test != 1):
print('Integer must be greater than 0')
userInput = int(input("Enter integer greater than 0\n"))
if(userInput > 0):
test = 1
break
else:
current.append(userInput)
CodePudding user response:
You can do something like:
current = []
print("Enter 6 integers greater than 0")
while len(current) < 6:
userInput = int(input())
while userInput < 0:
print('Integer must be greater than 0')
userInput = int(input("Enter integer greater than 0\n"))
current.append(userInput)
print(current)
I'm not sure what is the purpose of the test so didn't use in the code.
CodePudding user response:
There is no issue with how the while
loop is nested within the for
loop, however you need to do the if userInput > 0
test inside the while
loop.
With your current code, the while loop will run forever as test
is never going to change from the value 0
inside the while loop
Here is some code for your consideration
current = []
test = 1
print("Enter 6 integers greater than 0")
for i in range(6):
userInput = int(input())
if int(userInput) <= 0:
while(True):
print('Integer must be greater than 0')
userInput = int(input("Enter integer greater than 0\n"))
if userInput > 0:
break
else:
current.append(userInput)