How to use "while not in" in Python?

0

I tried looping while to check if a condition was met. If the user types 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 stop asking the user to choose a number when he enters a number contained in the list, he continued to ask the user to choose a number. I found that if the user chose a number from the list the program should stop. Does anyone know where I'm going wrong?

I also tried doing this 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: ')

Q: I'm using a Windows 7; Python 3.6.5 and PyCharm.

    
asked by anonymous 22.05.2018 / 19:25

3 answers

9

The error is that the function input always returns a text and you are checking if a text 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% w / w% will also be an integer and when the user enters a value from the list, the condition will be satisfied.

As commented out, this can generate a usuario exception if the user enters something other than a number. To prevent this, just use ValueError :

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')

Also, if the goal is just to read a value between 0 and 2, you do not have to define a list for it, just do the try/except condition. 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)
    
22.05.2018 / 19:31
3

A simple solution, which avoids the errors already mentioned as ValueError in case you try to convert a non-numeric character to int, would validate if the input is a digit, ie if what the user said is possible conversion 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
    
22.05.2018 / 19:52
0

The problem is that user will return 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')  
    
22.05.2018 / 19:30