By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,898 Members | 1,162 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,898 IT Pros & Developers. It's quick & easy.

Req: Error Trapping / Data Validation

P: 17
Hi!

I'm a beginner using Python 2.5

I'm trying to write a module which will peform the function of data entry and error trapping.

If the user enters an integer outside of a pre-defined range or tries to enter an non-integer value, the module will ask to re-enter until a correct response is made.

I want to call the module repeatedly with different sets of parameters for allowable data range from different points within the main program.

I'm sure this is a very common problem, but can't find the exact solution that I'm looking for in any book or on line, and would be very grateful for your help & guidance.

I've attached my latest (buggy, non-working) attempt to illustrate what I'm trying to achieve.

Many thanks in anticipation

Dave

Expand|Select|Wrap|Line Numbers
  1.  
  2. def getdata(low_limit,high_limit):
  3.  
  4. """Ask user to input integer between certain values
  5. If non-integer is entered, or integer is outside of defined range then
  6. Ask user to re-input until correct response is given"""
  7.  
  8.     try:
  9.         n=int(input('Please enter integer between',low_limit,' and ',high_limit,' >'))
  10.         return int(n)
  11.     except (ValueError,TypeError, n<low_limit, n>high_limit):
  12.         return "Error - please re-enter"
  13.  
  14. def main():
  15.     getdata(0,10)
  16.     print "done"
  17.  
Nov 19 '10 #1
Share this Question
Share on Google+
7 Replies


bvdet
Expert Mod 2.5K+
P: 2,851
Instead of a try/except block, use a while True loop. Example:
Expand|Select|Wrap|Line Numbers
  1. >>> while True:
  2. ...     ans = raw_input("Enter an integer between 1 and 10")
  3. ...     if ans.isdigit():
  4. ...         ans = int(ans)
  5. ...         if 1 <= ans <= 10:
  6. ...             print "You entered a valid number (%s)" % (ans)
  7. ...             break
  8. ...         else:
  9. ...             print "You entered an INVALID number (%s). Try again." % (ans)
  10. ...     else:
  11. ...         "You entered a letter (%s). Try again." % (ans)
  12. ...         
  13. You entered a letter (AA). Try again.
  14. You entered an INVALID number (13). Try again.
  15. You entered a valid number (5)
  16. >>> 
Nov 19 '10 #2

P: 17
Hi Bvdet

Many thanks for your help - much appreciated

3 further thoughts / queries:

1)
I was wondering if it is possible to go one step further, and make this module completely customisable for repeated use by somehow passing logical arguments (as strings) to define module parameters for error detection.

e.g. so that I could call the module from one point in main() as:

getdata(' 1 <= ans <= 10 ')

...to force the user to input a value which is not a letter and within the range 1-10
...then maybe later in the same main program, if I want the user to input another variable with different error parameters I could do something like e.g.

getdata(' ans%3==0 and ans>0 ')

...to get the user to input a value which is not a letter but is greater than zero and divisible by 3

I'm not sure if it is possible to convert strings to parameters that can be passed to a function, and then interpreted as booleans in this way, but it would keep the main() loop really clutter-free and be an elegant solution if it were possible.

2)
I attempted to add further variables and text characters to the "input" statement of the error trapping function to make it display the parameters when it was called.
My pseudocode:
n=int(input('Please enter integer between',low_limit,' and ',high_limit,' >'))

- is obviously wrong.
Is there a neat way to append variable values and further text strings within the same input statement as above? or do I have to do something like:

explain = 'Please enter integer between' + str(low_limit)+ 'and ' str(high_limit) +' >'
input (explain)

3)
Would Python 3.x instead of 2.x offer me more functionality to do this sort of task?

Sorry to ask dumb questions, but hope I've managed to explain what I'm trying to achieve...
Just not sure if it can be done or how to do it ;-)

Kind regards

Dave
(UK)
Nov 19 '10 #3

bvdet
Expert Mod 2.5K+
P: 2,851
#1 - Something like these functions:
Expand|Select|Wrap|Line Numbers
  1. def getint(low, high):
  2.     while True:
  3.         ans = raw_input("Enter an integer between %s and %s" % (low, high))
  4.         if ans.isdigit():
  5.             ans = int(ans)
  6.             if low <= ans <= high:
  7.                 print "You entered a valid number (%s)." % (ans)
  8.                 return ans
  9.             else:
  10.                 print "You entered an INVALID number (%s). Try again." % (ans)
  11.         else:
  12.             print "You entered an alpha character(s) (%s). Try again." % (ans)
  13.  
  14. print getint(15, 125)
  15.  
  16.  
  17. def getint1(expression):
  18.     while True:
  19.         X = raw_input("Enter an integer 'X' such that %s" % (expression))
  20.         if X.isdigit():
  21.             X = int(X)
  22.             if eval(expression):
  23.                 print "You entered a valid number (%s)." % (X)
  24.                 return X
  25.             else:
  26.                 print "You entered an INVALID number (%s). Try again." % (X)
  27.         else:
  28.             print "You entered an alpha character(s) (%s). Try again." % (X)
  29.  
  30. print getint1('X%3==0 and X>0')
#2 Use string formatting as shown above.
#3 I don't know of anything in Python 3 that makes this task easier.
Nov 19 '10 #4

P: 17
Many thanks Bvdet

These routines do exactly what I needed.
They also have taught me some very useful new techniques, so will study these for future reference.

Best wishes

Dave
Nov 20 '10 #5

P: 17
Hi again!

With the second routine, if a user enters a negative number or a non integer, the isdigit() command detects "." or "-" as non digit characters, and so returns the error message "You entered an alpha character..."

I've tried converting the code to Python 3 and using the isnumeric() function, but this does not return "True" if the string contains "." or "-" either...

Is there an easy way to modify the code to include detection and appropriate error messages if the user enters a negative number or non-integer?

Thanks again!

Dave
Nov 20 '10 #6

bvdet
Expert Mod 2.5K+
P: 2,851
To allow for a leading "-" character: if ans.lstrip("-").isdigit():

To allow a float entry, the function needs to be modified.
Expand|Select|Wrap|Line Numbers
  1. def getfloat(low, high):
  2.     while True:
  3.         ans = raw_input("Enter a number between %s and %s" % (low, high))
  4.         try:
  5.             ans = float(ans)
  6.             if low <= ans <= high:
  7.                 print "You entered a valid number (%s)." % (ans)
  8.                 return ans
  9.             else:
  10.                 print "You entered a number out of range (%s). Try again." % (ans)
  11.         except:
  12.             print "You entered an INVALID number (%s). Try again." % (ans)
Nov 20 '10 #7

P: 17
Many thanks for this - much appreciated.

Now you've explained how to do it, it seems obvious!

Best wishes

Dave
Nov 21 '10 #8

Post your reply

Sign in to post your reply or Sign up for a free account.