Thread: Code Help!!!!

    #1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2013
    Posts
    3
    Rep Power
    0

    Code Help!!!!


    what is a simple code I can use to say when a user enters anything but numbers 0 through 9 that their input is invalid?
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    43
    Rep Power
    2
    I am sure there's a more effective way to do this..

    Code:
    #Make an array of acceptable numbers, in string form.
    numbers = []
    for x in xrange(10): numbers.append(str(x))
    
    #Checks if raw input is contained within the numbers array
    if not raw_input("enter a number, 0-9: ") in numbers:
    	print "Input invalid"
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    138
    Rep Power
    2
    Originally Posted by eliskan
    I am sure there's a more effective way to do this..
    The only thing I can add is to use string.digits:

    Code:
    import string
    
    if not raw_input("enter a number, 0-9: ") in string.digits:
    	print "Input invalid"
    http://www.catb.org/esr/faqs/smart-questions.html#code
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    194
    Rep Power
    3
    Couple of issues I see with the previously provided solutions. The foremost is probably that the input value hasn't been stored anywhere. I'm assuming the user wants it for something.

    Also in these situations the user should usually be asked again if the input is incorrect, so a while loop is indicated.

    As for using string.digits, this may end up allowing several undesired inputs. string.digits is literally the string "0123456789". This means it will pass strings like "12", "456", etc.

    My top choices:
    python Code:
    num = None
    while num not in [str(i) for i in xrange(10)]:
        if num != None:
            print("Invalid input. Please try again.")
        num = raw_input("Enter a number between 0-9: ")
    python Code:
    while 1:
        num = raw_input("Enter a number between 0-9: ")
        if num.isdigit() and len(num)==1:
            num = int(num)
            break
        else:
            print("Invalid input.  Please try again.")
    python Code:
    while 1:
        try:
            num = int(raw_input("Enter a number between 0-9: "))
            if not -1<num<10:
                raise ValueError
            break
        except ValueError:
            print("Invalid input.  Please try again.")
    All of which admittedly look more complicated
    -Mek

IMN logo majestic logo threadwatch logo seochat tools logo