-1
list = [1, 2, 3, 4, 5, 6]
number = input("Please enter a number: ")
number = int(number)
while True:
    if number != (any element of the list):
        number = input("Please enter a number: ")
    else:
        break 

I want the user to enter a number and if that number is not in the list provided the program will ask him to enter that number again until he gets it write

khelwood
  • 52,115
  • 13
  • 74
  • 94
  • 2
    `if number not in allowed_numbers` – Peter Wood Mar 27 '17 at 09:45
  • @Chris_Rands That page has lots of excellent advice about getting user input, but it doesn't specifically address this question of checking whether a list contains a particular item. – PM 2Ring Mar 27 '17 at 09:51
  • Between the two you should be able to get it. – jonrsharpe Mar 27 '17 at 09:55
  • @PM2Ring You're right of course. Perhaps it's more this (http://stackoverflow.com/questions/7571635/fastest-way-to-check-if-a-value-exist-in-a-list). I'm never quite sure how to address these questions that are not truly original, but perhaps cross multiple questions. – Chris_Rands Mar 27 '17 at 09:57

3 Answers3

0

First you must initalize variable "number" E.g.:

number = -1  # Init value should be value not included in list

List variable name, can't be "list". List is the name of Python builtin class.

Jacek Zygiel
  • 153
  • 9
0

You can simply use the in statement to reach your goal.
Your code can be similar to this:

list = [1, 2, 3, 4, 5, 6]
number = input("Please enter a number: ")
number = int(number)
while True:
    if not number in list:
        number = input("Please enter a number: ")
        number = int(number)
    else:
        break

Remember that you can have an exception not handled, I mean, if user insert something different to a number, your code raises an exception.
Please consider to handle this with a try except statement

Giordano
  • 5,094
  • 3
  • 29
  • 48
-1
list = [1, 2, 3, 4, 5, 6]
number = input("Please enter a number: ")
while True:
    if number not in list:
        number = input("Please enter a number: ")
    else:
        break

should do the trick.

jonrsharpe
  • 107,083
  • 22
  • 201
  • 376
DrunkDevKek
  • 455
  • 4
  • 16
  • 2
    Welcome to Stack Overflow! Whilst this code snippet is welcome, and may provide some help, it would be [greatly improved if it included an explanation](//meta.stackexchange.com/q/114762) of *how* and *why* this solves the problem. Remember that you are answering the question for readers in the future, not just the person asking now! Please [edit] your answer to add explanation, and give an indication of what limitations and assumptions apply. – Toby Speight Mar 27 '17 at 09:55