How to use "while not in" in Python?

Asked

Viewed 3,591 times

0

I tried to loop with while to check if a condition was met. If the user enters 0, 1 or 2 the program should stop asking the user which number he will choose. If the user chooses a number other than 0, 1 or 2, the program will ask the user which number he wants to choose.

lista = [0, 1, 2]
usuario =''
while usuario not in lista:
    usuario = input('Escolha um número entre 0 e 2: ')

The behavior I observed was not what I expected. Instead of the program asking the user to choose a number when they enter a number contained in the list, he continued to ask the user to choose a number. I thought that if the user chose a number from the list the program should stop. Can anyone tell where I am missing?

I also tried to make that loop this way, but I had the same problem:

lista = [0, 1, 2]
usuario =''
while usuario != lista:
    usuario = input('Escolha um número entre 0 e 2: ')

P.S.: I am using Windows 7; Python 3.6.5 and Pycharm.

3 answers

9


The error is that the function input at all times returns a string and you are checking whether a string belongs to a list of integers. This condition will never be satisfied.

print('1' in [0, 1, 2])  # False

If you want to check if an integer belongs to a list of integers, you need to do the conversion:

while usuario not in lista:
    usuario = int(input('Escolha um número entre 0 e 2: '))

Thus, usuario will also be an integer and when the user enters a list value, the condition will be satisfied.

As commented, this can generate an exception ValueError if the user enters something other than a number. To prevent this, simply use the try/except:

while usuario not in lista:
    try:
        usuario = int(input('Escolha um número entre 0 e 2: '))
    except ValueError:
        print('Por favor, entre com um número')

Still, if the goal is just to read a value between 0 and 2, you do not need to define a list for this, just make the condition 0 <= usuario <= 2. For example:

while True
    try:
        usuario = int(input('Escolha um número entre 0 e 2: '))
        if not 0 <= usuario <= 2:
            raise ValueError('Número deve estar entre 0 e 2')
        break
    except ValueError as error:
        print(error)
  • That’s right, thank you.

3

A simple solution, which avoids the errors already mentioned as ValueError in the case of trying to convert a non-numeric character to int, it would validate if the input is a digit, that is, if what the user typed converts to integer.

lista = [0, 1, 2]

while True:
    usuario = input('Escolha um número entre 0 e 2: ')
    if usuario.isdigit() and int(usuario) in lista:
        break
  • It’s a good solution too. In this case, usuario would be a string, which depending on the problem may be interesting.

  • Yes, yes... But until then it is quiet right, once validated that is digit, then can already make the conversion without fear of being happy.

  • It can even be reduced to if int(usuario) in lista: ..., since by the question and the accepted answer from Anderson it is not necessary to treat/prevent exceptions because the input may be letters

1

The problem is that user will come back as a string, tries to write

 while usuario not in lista:
      usuario = input('Escolha um número entre 0 e 2: ')
      if(regex(usuario)
           usuario = int(usuario)
      else 
         print('Digite um Numero')  
  • I tried this, but it returns an error: "Valueerror: invalid literal for int() with base 10: ' '"

  • 1

    Yes, this will happen whenever the user types something that is not passive from conversion to an integer, such as a letter or an empty space. One solution is to use a regular expression to see if the input is a number.

Browser other questions tagged

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