1

Tengo un programa de adivinar el número en 5 oportunidades, funciona bien, pero como puedo hacer que el usuario solo pueda introducir números y no letras? y que al introducir una letra no le cuente como una oportunidad.

En el primer código se puede ver como importo el programa de elegir el número aleatorio.

Como al parerecer si quiero postear todo el código necesito "x" letras que equivalen a "x" código, por eso he también he escrito esto hahah.

def main(): 
    import random
    
    guesses = 5
    number = random.randint(1, 10)
    count = 1
    win = False
    while guesses > 0:
        
        
        user_input = int(input("Enter your number here: "))

        guesses -= 1
                     
        if user_input > number:
            print("Your number is too high, try with a lower number.")
            print(f"You have {guesses} guesse(s) more. ")
            
        elif user_input < number:
            print("Your number is too low, try with a higher number.")
            print(f"You have {guesses} guesse(s) more. ")
                    
        else:
            print(f"Congratulation! You guess the number in {count} attempt(s).")
            print(f"The number was {number}.")
            win = True
            guesses = 0
            restar = input("If you want to play again type 'Yes', if you want to quit the game type 'No': ")
            Change = restar.upper()
            if Change == "YES":
                main()
                
            else:
                Change = restar.upper()
            if Change == "NO":
                print("Good game. See you next time.")
                   
        count += 1

     if win == False:
        print("")
        print("Sorry you don't have any more guesses.")
        print(f"The number was {number}.")
        restar = input("If you want to play again type 'Yes', if you want to quit the game type 'No': ")
        Change = restar.upper()
        if Change == "YES":
            main()
        else:
            Change = restar.upper()
            if Change == "NO":
                print("Game over. See you next time")
main()
2

1 respuesta 1

2

Una manera de hacerlo es usar un bloque try, asi

while True:
    try:
        user_input = int(input("Enter your number here: "))
        break
    except ValueError:
        pass

print(user_input)

Si el usuario ingresa algo que no es un número, la función int genera una excepción ValueError, frente a la cual no hacemos nada y seguimos en el ciclo while.

Si el usuario ingresa un número, se ejecuta el break y sales del while

2
  • hay alguna manera en la que no se use try y except? esque aun no he aprendido eso el 4 oct. 2020 a las 17:07
  • 2
    @NelsonReimundo. Ahora ya lo aprendiste :-)
    – Candid Moe
    el 4 oct. 2020 a las 17:08

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.