Noob Question: Force input to be int?
consmash at gmail.com
consmash at gmail.com
Wed Jan 24 12:57:09 EST 2007
On 23 Sty, 10:59, wd.jons... at gmail.com wrote:
> 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)
> print
> num = 0
> for i in BuildList:
> print str(num) +" " + i
> num = num + 1
> print
> 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?
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.
More information about the Python-list
mailing list