Accept entry with only 1 digit

Asked

Viewed 72 times

1

I would like to know a way to accept only the entry with 1 digit. In the case below: 1, 2 or 3.

Entries of type 0001, 01, 0002. (with zero left) was not valid (presented an error) and returned to type again a number between 1 and 3.

Can someone help me?

def choice_game_to_play():
    playing = False
      
    
    try_login = 0
    
      print("*****************************************")
      print("*************CHOICE A GAME!**************")
      print("*****************************************\n")
    
      while not playing:
    
        try:      
          try_login += 1
    
          playing = try_login == 6
    
          print("(1) Roll dice - (2) Guess a number - (3) Jokenpo\n")
    
          game = int(input("Choice a game between 1 and 3: "))
         
          if game <= 0 or game > 3:
            print("\n**********Invalid value, try again!**********\n")
          else: 
            if game == 1:
              play_dice()  
            elif game == 2:
              play_guessing() 
            elif game == 3:
              play_jokenpo()
              
        except ValueError:
          print("\n*************Invalid value, try again!*************\n")
          continue   
  • Try: game = input("Choice a game between 1 and 3: ")&#xA;while (game not in ["1", "2", "3"]):&#xA; print("\n**********Invalid value, try again!**********\n")&#xA; game = input("Choice a game between 1 and 3: ")&#xA;game = int(game)&#xA;.

  • Hummm, I understand the logic! I will implement. Thanks

  • I wanted to understand why this question had negative votes. Could anyone who gave negative votes talk about?

  • This has been happening a lot. The questions are clear, well structured. However, it seems that if the person does not understand, or does not know how to answer, vote negative.

2 answers

1

When we want to restrict the number numbers to just "1" digit, we realize that we want numbers that only belong to the set [-9, 9], that is to say...

numeros = [-9, -8, -7, -6 , -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Now, how are you using only the numbers "1", "2" e "3", you can convert them into "string" and then use them.

Another thing, when we work with functions we must know how to structure them and how to call them.

According to what you want, I have developed the following code...

print("*************************************************")
print("*****************\033[34mCHOICE A GAME!\033[m******************")
print("*************************************************")
print()

def playDice():
    print('\nStarting Dice...')
    # Insert the game code "Dice" here!
    # Insira o código do jogo "Dice" aqui!


def playGuess():
    print('\nStarting Guess...')
    # Insert the game code "Guess" here!
    # Insira o código do jogo "Guess" aqui!


def playJokenpo():
    print('\nStarting Jokenpo...')
    # Insert the game code "Jokenpo" here!
    # Insira o código do jogo "Jokenpo" aqui!


def choice_game_to_play():

    print("(1) Roll dice - (2) Guess a number - (3) Jokenpo")

    game = input("Choice a game between 1 and 3: ").strip()
    while game not in '123':
        print("\n************\033[31mInvalid value, try again!\033[m************")
        game = str(input("Choice a game between 1 and 3: "))

    if game == '1':
        playDice()
    elif game == '2':
        playGuess()
    elif game == '3':
        playJokenpo()


choice_game_to_play()

See how the code works on repl it.

1

The line game = int(input("Choice a game between 1 and 3: ")) flame int and this immediately converts the typed value to an integer (and if it is not an integer, a Typeerror happens and the program jumps to Except) - but then, after this conversion, if the user typed "001", it is already in the variable "game" only the numerical value "1"And you have no control over it.

It’s best to accept the return of input how it comes - which is a string, and then use some ifs to control what is typed, before extracting the integer value of the numbers.

This has the advantage, besides the try...except generic in the whole block that allows more appropriate messages to be given to the user at each attempt.

The code above already makes a part of it with if game <= 0 or game > 3: - you can do something like:


while True:
   game_str = input("Choose a game between 1 and 3: ")
   if not game_str.isdigit():
       print("Please, pick a numeric choice")
       continue  # volta ao "while", repetindo a pergunta
   if len(game_str) != 1:  # Aqui trato o conteúdo como string: o valor digitado deve ter apena sum caractere
       print("Please, type just the number 1-3")
       continue
   game = int(game_str)  # só aqui converto o valor para numérico
   if 0 < game <=3:
       break # Valor entre 1 e 3 - saimos do "while True" que repete a pergunta sempre
   print("Please, the option should be in the range 1-3")

# codigo fora do While continua o jogo
...

Above, besides taking the initial content as a string, I put a "while True" that includes the question - and only the test in the "if" that checks if everything is ok contains the "break" command that makes the code exit the "while" and continue. Until everything is ok, for one reason or another, while is running and repeats the input.

Browser other questions tagged

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