While repeating structure does not repeat specific code snippet!

Asked

Viewed 46 times

0

I’m making a simple pair or odd python game that doesn’t perform correctly!

When the player wins, the game does not ask again if he that even or odd! How can I solve?

from random import randint
P_OU_I = ' '
v = 0
while True:
    player = int(input('Digite um valor: '))
    computador = randint(0, 10)
    total = player + computador
    while P_OU_I not in 'PI':
        P_OU_I = str(input('Par ou ímpar: [P/I] ')).strip().upper()[0]
    print(f'Você jogou {player} e o computador {computador}. Total de {total}')
    if P_OU_I == 'P':
        if total % 2 == 0:
            print('Você VENCEU!')
            v = v + 1
        else:
            print('Você PERDEU!')
            break
    elif P_OU_I == 'I':
        if total % 2 == 1:
            print('Você VENCEU!')
            v = v + 1
        else:
            print('Você PERDEU!')
            break
    print('Vamos jogar novamente...')
print(f'GAME OVER! Você venceu {v}')
  • What were your attempts? I suggest edit your question and add those details. Ah! before anything else gives a glance, how to create a [Mre] so you can elaborate a good question and the chances of it being closed (ie have no chance of receiving answers) greatly reduces!

1 answer

0


Actually your code is running correctly according to what it was programmed, it just isn’t doing what you want because you haven’t programmed as it should.

Your mistake is as follows: In line 8 you make a conference to know if you have already been chosen even or odd

while P_OU_I not in 'PI':

In the first execution the code enters this while because the variable is still empty. However, note that you have not cleared this variable at any time after the first round.

To fix it is quite simple, you just need to set again P_OU_I = ' ' like you did at the beginning of the code. See how it looks after fixed:

from random import randint
P_OU_I = ' '
v = 0

while True:
    player = int(input('Digite um valor: '))
    computador = randint(0, 10)
    total = player + computador
    while P_OU_I not in 'PI':
        P_OU_I = str(input('Par ou ímpar: [P/I] ')).strip().upper()[0]
    print(f'Você jogou {player} e o computador {computador}. Total de {total}')
    if P_OU_I == 'P':
        if total % 2 == 0:
            print('Você VENCEU!')
            v += 1
        else:
            print('Você PERDEU!')
            break
    elif P_OU_I == 'I':
        if total % 2 == 1:
            print('Você VENCEU!')
            v += 1
        else:
            print('Você PERDEU!')
            break
    P_OU_I = ' '
    print('Vamos jogar novamente...')
print(f'GAME OVER! Você venceu {v}')

I also changed some things that I think are better. Take a look.

  • 1

    That solved my problem! Thank you!

Browser other questions tagged

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