April 28th, 2004, 04:40 AM
How to ensure input number range?
I am writing my first Python program, which is a simple little lottery thing.
It runs well, but the user can input any numbers he wishes, and I want to limit him to a specific bit range.
I have tried various ways but can't seem to understand how to do this.
The problem is:
I have a seven-digit number. The first six digits can be between 1 and 35, while the seventh digit can only be between 1 and 10.
A gentle shove in the right direction would be much appreciated. Maybe even a reference for me to read? I do have the Reference Manual.
April 28th, 2004, 07:50 AM
I presume that this is a text-mode program, in which case the best you can do is ask for a number, and if it is not in the right range then print an error message and try again.
If it is a GUI program such as Tkinter or wxWindows then you have a number of other options, such as using a spin control or a drop-down list of possible numbers.
def getNumberInRange(min, max):
val = raw_input('Please enter a number between %s and %s' % (min, max) )
val = int(val)
if min <= val <= max:
print 'Incorrect - please try again'
print getNumberInRange(1, 35)
Dave - The Developers' Coach
Last edited by DevCoach; April 28th, 2004 at 07:56 AM.
April 28th, 2004, 09:21 AM
Excellent, thank you very much.
Solved my immediate problem and led me into a new area (GUI). So my studies continue.
Very grateful, for sure!
April 30th, 2004, 09:59 AM
another common solusion would be to do an 'if number in range' check i.e.
I also believe you can use xrange() aswell as range() for this.
imaginary python shell
>>> min = 1
>>> max = 50
>>> num = 20
>>> if num in range(max, min): print True
Note: none of this is tested in particular the last section in the second example may not work however the rest is probably fine . Let me know if it doesnt work for you.
def inrange(num, min, max):
return int(num) in range(max, min)
except ValueError, message:
if __name__ == '__main__':
num = raw_input('Please enter a number')
min = 1
max = 50
while not inrange(num, min, max): num = raw_input('Please enter a number')
Hope this helps,