Home > Net >  Asking until the input is in the list?
Asking until the input is in the list?

Time:10-31

Trying to understand while loops but after typing in the input a number that is not in the list, it doesn't keep asking until it is one of the numbers in the list.

number = 12
while number not in [0,1,2,3,4]:
    number = input("type a number: ")
    print(number)
    if number in [0,1,2,3,4]:
        print('one of those numbers')
    else:
        break
print('not one of those numbers')

the above gives this if you type 4343:

type a number: 4343
4343
not one of those numbers

CodePudding user response:

If you step through your code you can see that the "number" variable gets what you typed in, 4343. Then you check to see if number is in the list of 0-4. It's not, so execution proceeds down the "else" branch, which is a break. Break will "break" the execution of your loop, so the next thing printed is "not one of those numbers" and execution stops and you are not asked for another input.

If you were to type a number like "4" what would happen? Well, the same thing I think. That's because your input comes in as a string, not a number, and you are asking if the string "4" is in the list of numbers, and it isn't. You need to parse the input as an int, you can do that by wrapping your input call in the "int" function - int(input("Type a number: ")) and now "number" will be an int, not a string.

CodePudding user response:

number = 12
while number not in [0,1,2,3,4]:
    number = int(input("type a number: "))
    print(number)
    if number in [0,1,2,3,4]:
        print('one of those numbers')
        break
    else:
        print('not one of those numbers')
        continue

As @inteoryx told that when you give an input it's a default string value. You have to convert it to integer and you used break statement if the number not in the list. break gets you out of the loop you should use continue statement instead. I added break in the if statement that will get you out of the loop if the number is in the list.

  • Related