Loop inside loop While PYTHON

Asked

Viewed 1,396 times

-1

I’m making a program that draws a number from 0 to 5 and the user should guess what it is, but he only has 3 attempts. In case the 3 attempts run out and the user does not guess which is the number, then would show a message saying that exceeded the number of attempts and whether wanted to quit or continue playing, the problem is that come have a loop inside the other if the user type "more" the "continue" assumes I want to return the input saying I tried too many times and not the entire code:

import random
import time
from sys import exit
print('-------------------')
print('JOGO DA ADIVINHAÇÃO')
print('-------------------')
time.sleep(2)
print('Vou pensar num número de 0 a 5...')
time. sleep(1)
tentativa=3
num=random.randint(0, 5)
while True:
 n= int(input('Tente adivinhar qual é: '))
 if tentativa >0:
        if num==n:
            print('Você ACERTOU! PARABÉNS!')
            break
        elif num!=n:
                n2=input(f'Você errou, tem {tentativa}...')
                tentativa=tentativa-1
                continue
 elif tentativa==0:
        while True:
         se=input('Você tentou vezes demais e não acertou digite "mais" para jogar novamente ou "sair" para acabar o jogo: ')
         if se=='sair':
             exit()
         elif se=='mais':
             continue
         elif se!='mais' or se!= 'sair':
             print('Não percebi o que quis dizer...')
             time.sleep(2)
             continue 

How do I make the whole code start again?

2 answers

1

It’s just a matter of simplifying the problem. You have little code that does a lot, so it will be better to separate the responsibilities.

You can create a function that reads the user’s attempt:

def ler_tentativa() -> int:
    while True:
        try:
            return int(input('Tente advinhar o número: '))
        except ValueError:
            print('Erro! Informe um valor inteiro')

You can create a role that asks the user if he wants to continue playing:

def tentar_de_novo() -> bool:
    while True:
        answer = input('Digite "mais" para tentar novamente ou "sair" para encerrar')
        if answer not in {'sair', 'mais'}:
            print('Erro! Não entendi o que quis dizer')
            continue
        return answer == 'mais'

And, thus, you create a loop that lasts as long as there are attempts and when to close them and the user ask to play again just you increase to 3 the number of attempts:

tentativas = 3
sorteado = 5

while tentativas > 0:
    tentativas -= 1
    tentativa: int = ler_tentativa()

    if tentativa == sorteado:
        print('Parabéns')
        break

    if tentativas == 0 and tentar_de_novo():
        tentativas = 3
else:
    print('Fim')

0

You can add an "auxiliary" variable to this and place the trial assignment part and a new number inside the Loop, this way:

import random
import time
from sys import exit
print('-------------------')
print('JOGO DA ADIVINHAÇÃO')
print('-------------------')
time.sleep(2)

inicio = True
while True:

    if(inicio): 
        print('Vou pensar num número de 0 a 5...')
        tentativa=3
        num=random.randint(0, 5)
        time. sleep(1)
        n= int(input('Tente adivinhar qual é: '))
        inicio = False

    if tentativa >0:
        if num==n:
            print('Você ACERTOU! PARABÉNS!')
            break
        elif num!=n:
            n2=input(f'Você errou, tem {tentativa}...')
            tentativa=tentativa-1
            continue

    elif tentativa==0:
        while True:
            se=input('Você tentou vezes demais e não acertou digite "mais" para jogar novamente ou "sair" para acabar o jogo: ')
            if se=='sair':
                 exit()
            elif se=='mais':
                inicio = True
                break
            elif se!='mais' or se!= 'sair':
                print('Não percebi o que quis dizer...')
                time.sleep(2)
                continue

However the code is a little verbose, and apparently with some messages that may cause problem.

I advise to give a studied in functions to make your code less verbose, as some have already mentioned in the answers.

Browser other questions tagged

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