Repeat an algorithm if the answer is wrong in guessing game without losing the drawn number

Asked

Viewed 177 times

1

I made an algorithm in Python with the proposal to guess a number as the user type, ie the guessing game. But I would like to make a condition that makes him type again, in case he does not choose the desired number, I have no idea how I do, because of the module random.

import random
import time

def c():

num =(int(input("Adivinha um numero de 0 a 5: ").strip()))
numB = random.randint(0,5)
print("CARREGANDO..............................")
time.sleep(1)

if num == numB:
    print('Parabéns! Você acertou o numero\n'
          'Você é um vencedor !')
elif num > numB: # Condição do valor diferente, só uma amostra(Está errado)
    print("Valor errado") 

else:
    print("Errado! Tente de Novo")
    time.sleep(1)
    c() 
c()
  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful for you. You can also vote on any question or answer you find useful on the entire site (when you have 15 points).

1 answer

4

Calling the same function is not very suitable, may even burst the stack, although in this case it is highly unlikely that this should occur, but get used to doing it right. It is best to make a loop and exit only if you are right. The draw is obviously out of the loop so as not to draw another number on each attempt, simple and easy when using the right mechanism.

import random

def c():
    numB = random.randint(0, 5)
    while True:
        num = int(input("Adivinha um numero de 0 a 5: ").strip())
        if num == numB:
            print('Parabéns! Você acertou o numero\n'
                  'Você é um vencedor !')
            break
        elif num > numB:
            print("Valor errado")
        else:
            print("Errado! Tente de Novo")
c()

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

Browser other questions tagged

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