Noob Question: Force input to be int?

Paul Rubin http
Tue Jan 23 05:27:08 EST 2007


wd.jonsson at gmail.com writes:
>     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
>         print "Error: Invalid build number!"
>         print "Select a build number from 0 to " + str(len(BuildList) - 1)
>         print
>         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?

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
program.

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
        try:
           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
        print "Error: Invalid build number!"



More information about the Python-list mailing list