"Wayne" <sri...@gmail.com> wrote
Data validation is also a good thing:

I agree with this bit but...

def mysum(n1, n2):
    try:
       n1 = int(n1)
       n2 = int(n2)
   except ValueError:
       print "Error! Cannot convert values to int!"

   return n1+n2

Or do something similar.

In a dynamic language like Python this kind of data validation - which is actually type validation - is not necessary.

It would be better to do:

def mysum(n1,n2):
   try:
      return n1+n2
   except TypeError:
      print "Cannot add %s and %s" % (n1,n2)

One of the most powerful features of Python is that you can use "Duck Typing" to create powerful polymorphic functions like this that can add two objects, regardless of type, provided they support addition. Limiting it to integers would be a big limitation.

In Python data validaton should normally be restricted to catching invalid data *values* not invalid data types.

HTH,

--
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/

_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to