Doubt with loop for counter

Asked

Viewed 127 times

2

I want to run this very simple loop:

for i in range (1, 5):
    num = int(input("Digite um numero positivo: "))
    if (num < 0):
        print("Você digitou um número negativo, tente de novo.")

If the user enters a negative number, I want this "guess" not to be added to the counter i, that is, I want to subtract 1 from i so that the guess is not accounted for.

I’ve tried to put i = i -1 below my if but this does not change the value of i of my accountant.

1 answer

4


No need to manipulate the value of i. Just make a loop infinite, and only interrupt it when the number is positive:

for i in range (1, 5):
    while True:
        num = int(input("Digite um numero positivo: "))
        if (num < 0):
            print("Você digitou um número negativo, tente de novo.")
        else: break

The while True wheel "forever", and is only interrupted by break, which in turn is only called when the number is not negative.

After the while is interrupted, the for continues to the next iteration.

  • 1

    Thank you very much solved my problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.