Repeat codes with while loop

Asked

Viewed 59 times

-1

I’m having trouble executing a noose while within another while.

I used the code below, which does everything right, but at the time I type 1 it only repeats the question "Do you want to repeat? type 1 for yes and 2 for no:", and I want you to repeat the whole program but it just repeats the last sentence.

resp = int(1)

n1 = -1

n2 = -1

while resp == 1:

    while n1 > 10 or n1 < 0:
        n1 = float(input("Qual valor da sua primeira nota?: "))
        if n1 > 10 or n1 < 0:
            print('Nota invalida.')
    while n2 > 10 or n2 < 0:
        n2 = float(input("Qual valor da sua segunda nota?: "))
        if n2 > 10 or n2 < 0:
            print('Nota invalida.')
        media = (n1 + n2) / 2
        print('A sua média foi de {}'.format(media))
    resp = int(input('Deseja repetir? digite 1 para sim e 2 para não: '))
  • This happens because the n1 and n2 continue with the entered value, reset the two variables after the question "Want to repeat?"

1 answer

0

Before when the program ran out if the user wanted to run it again could not, because it did not enter the loops while n1 > 10 or n1 < 0 and while n1 > 10 or n1 < 0, due to the fact that the condition in the loops is false, because at the end of the program the variables n1 and n2 would be with a value below 10 and above 0, there are 2 ways to fix this:

1 - Maintaining the structure of your code (resetting variables when the program runs again)

resp = int(1)
n1 = -1
n2 = -1

while resp == 1:

    if resp == 2:
        n1 = -1
        n2 = -1

    while n1 > 10 or n1 < 0:
        n1 = float(input("Qual valor da sua primeira nota?: "))
        if n1 > 10 or n1 < 0:
            print('Nota invalida.')

    while n2 > 10 or n2 < 0:
        n2 = float(input("Qual valor da sua segunda nota?: "))
        if n2 > 10 or n2 < 0:
            print('Nota invalida.')

    media = (n1 + n2) / 2
    print('A sua média foi de {}'.format(media))
    resp = int(input('Deseja repetir? digite 1 para sim e 2 para não: '))

2 - Pythonic shape, visually more beautiful/pleasant and easy to understand:

resp = 1

while resp == 1:

    while True:
        n1 = float(input("Qual valor da sua primeira nota?: "))
        if n1 > 10 or n1 < 0:
            print('Nota invalida.')
        else:
            break

    while True:
        n2 = float(input("Qual valor da sua segunda nota?: "))
        if n2 > 10 or n2 < 0:
            print('Nota invalida.')
        else:
            break

    media = n1 + n2 / 2
    print(f'A sua média foi de {media}')
    # Se estiver usando o python 3.6 ou inferior utilize: print('A sua média foi de {}'.format(media))
    resp = int(input('Deseja repetir? digite 1 para sim e 2 para não: '))

Browser other questions tagged

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