1
Hello. I am a beginner in programming and have been trying to develop on my own programs that I learned in programming book exercises. I made my version of the classic "Guess the number", where the user has (n) attempts to hit a number randomly generated by the program. My problem is the trial counter. The counter I put (5x) only covers in case the user hits only by typing numbers, or misses the 5 attempts. However, there is an entry validator. If the user types a letter, the validator enters a loop and only leaves if he enters a number, and within that loop I could not insert a counter. My question is: How can I count invalid characters as number of attempts?
Variáveis usadas:
x = contador de tentativas
t = número de tentativas final
n = número digitado pelo usuário
r = número aleatório gerado pelo módulo random
Program code:
    #!/usr/bin/python3
    #coding=utf-8
    #Filename=num.py
    # Importa os módulos necessários
    import random
    import time
    # Define uma linha vazia
    def vazio():
        print()
    # Define uma linha pontilhada
    def linhas():
        print('----------------------------------------------')
    # Define três pontinhos
    def pontinhos():
        print('.')
        time.sleep(0.3)
        print('.')
        time.sleep(0.3)
        print('.')
        time.sleep(0.3)
    # Define o título    
    def title():
        print('##############################################')
        time.sleep(0.5)
        print('#################### NUM #####################')
        time.sleep(0.5)
        print('##############################################')
        time.sleep(1.5)
        pontinhos()
    # Define a introdução
    def intro():
        nome = input('\nQual é o seu nome? ')
        vazio()
        linhas()
        time.sleep(1)
        print('\nOlá %s!\n' % nome)
        linhas()
        time.sleep(1)
        print('\nEu estou pensando em um número...\n')
        linhas()
        time.sleep(1)
        print('\nEntre 1 e 100...\n')
        linhas()
        time.sleep(1)
        print('\nAdivinhe qual...\n')
        linhas()
        time.sleep(2)
    # Define o main loop 
    def main():
    """ Adivinhe o número aleatório de 1 a 100  com no máximo 5 tentativas """
        title()
        intro()
        x = 0
        n = 0
        t = 0
        r = random.randint(1,100)
        while True:
            # Se errar ou acertar...tente novamente ou saia do jogo...
            if x == 5 or n == r:
                # Se errar
                if x == 5 and n != r:
                    print('\n5 tentativas não foram suficientes! :(\n')
                    linhas()
                # Errando ou acertando...
                x = 0
                t = 0
                r = random.randint(1,100)
                s = input('\n[S] para sair: ')
                linhas()
                vazio()
                if s == 'S' or s == 's':
                    pontinhos()
                    print('Agradeço por jogar NUM!')
                    break
                else:
                    title()
            # Verifica se números são digitados ao invés de letras...
            while True:    
                try:
                    n = int(input('\nDigite um valor: '))
                    vazio()
                    pontinhos()
                    linhas()
                    break
                except ValueError:  # Se digitar letra ao invés de n....
                    linhas()
                    print('\nIsso não é um número!\n')
                    linhas()
            # Se acertar        
            if n == r:   
                print('\nVocê acertou em %d tentativas! :)\n' % t)
                linhas()
                time.sleep(1)
            # Se o número digitado for menor que a resposta...
            elif n > r:
                print('\nO número é menor que isso!\n')
                linhas()
                time.sleep(1)
            # Se o número digitado for maior que a resposta...
            elif n < r:
                print('\nO número é maior que isso!\n')
                linhas()
                time.sleep(1)
            x = x + 1
            t = t + 1
    # Chama o main loop
    main()