Noob Question: Force input to be int?

Discussion in 'Python' started by wd.jonsson, Jan 23, 2007.

  1. wd.jonsson

    wd.jonsson Guest

    Hello everyone!
    I have a piece of code that looks like this:

    if len(BuildList) > 0:
    print "The script found %d game directories:" % len(BuildList)
    num = 0
    for i in BuildList:
    print str(num) +" " + i
    num = num + 1
    print "Select a build number from 0 to " + str(len(BuildList) - 1)
    buildNum = int(raw_input('Select build #> '))

    while buildNum > (len(BuildList) -1) or buildNum <= -1:
    print "Error: Invalid build number!"
    print "Select a build number from 0 to " + str(len(BuildList) -
    buildNum = int(raw_input('Select build: '))

    The problem is with the while buildNum-loop. If the user enters a
    non-numeric value in the buildNum input, the scripts throws an
    exception. I need to constrict the user to ONLY use integers in the
    input box. How can I solve this issue?
    wd.jonsson, Jan 23, 2007
    1. Advertisements

  2. I have a piece of code that looks like this:

    How about this:

    while True:
    x = int( raw_input( 'Enter an integer: ' ) )

    print 'Okay, now I have this integer: %d' % x

    Daniel Nogradi, Jan 23, 2007
    1. Advertisements

  3. wd.jonsson

    Paul Rubin Guest

    You can either validate the input string before trying to convert
    it ("look before you leap") or attempt conversion and handle the
    exception if you get one ("it's easier to ask forgiveness than
    permission"). The second pattern is generally preferable since it
    means you don't duplicate input validation logic all over your

    The below is untested but is a partial rewrite of your code above,
    intended to illustrate a few normal Python practices (I hope I haven't
    introduced bugs) besides the input checking:

    # just loop til you get a valid number, reading the number at the
    # top of the loop. No need to read it in multiple places.
    while True:
    # you don't have to convert int to str for use in a print statement.
    # the print statement takes care of the conversion automatically.
    print "Select a build number from 0 to", len(BuildList) - 1
    buildNumStr = raw_input('Select build #> ')

    # attempt conversion to int, which might fail; and catch the
    # exception if it fails
    buildNum = int(buildNumStr)
    except ValueError:
    buildNum = -1 # just treat this as an invalid value

    # you can say a < x < b instead of (a < x) and (x < b)
    if 0 <= buildNum < len(BuildList):
    break # you've got a valid number, so exit the loop

    # print error message and go back to top of loop
    print "Error: Invalid build number!"
    Paul Rubin, Jan 23, 2007
  4. Ah, thank you for the respone!
    I have not gotten around to test it yet, but I hope it will work! :)

    2007-01-23 10:59:37
    wrote in message
    Daniel Jonsson, Jan 23, 2007
  5. wd.jonsson

    consmash Guest

    Also if you would like to try mentioned approach 'Look before you
    leap', this code should be quite clear:

    buildNumber = ('foo', 'bar')
    n = len(buildNumber)
    loop = True
    while loop:
    input = raw_input('select a build number from 0 to %d: ' % (n-1))
    if input.isdigit():
    ch = int(input)
    loop = not ch in range(n) # if ch is NOT in range of [0, n),
    then it is ok to loop
    if loop:
    print 'Error! Invalid build number'
    print 'Choice: %d' % ch

    In fact I don't know if it applies to python, but in conventional
    languages it is a bad habit to use exceptions for every simple test as
    it takes time to jump around code. So, correct me please.
    consmash, Jan 24, 2007
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.