[Tutor] TypeError: unsupported operand type(s)

Alan Gauld alan.gauld at yahoo.co.uk
Sun Mar 22 21:32:56 EDT 2020


On 22/03/2020 20:19, SATYABRATA DATTA wrote:
> The main thing I have to do to take only the meaningful values for my
> problem and which are only those which satisfies Delta>=0 (I want to skip
> the negative Deltas). How to write that in my code

In that case, we can assume that a negative Delta value is due
to faulty input data?
So, as david suggested, it would be reasonable to raise a
ValueError in your code if such an event occurred.

>> def x1(ap,dp,ph,e1,e2,e3,e4,e5,y):
>>     if Delta(ap,dp,ph,e1,e2,e3,e4,e5,y) >= 0:
>>         return 2*(b(ap,dp,ph,e1,e2,e3,e4,e5,y)**3) -
>> 9*a*b(ap,dp,ph,e1,e2,e3,e4,e5,y)*c(ap,dp,ph,e1,e2,e3,e4,e5,y) +
>> 27*(a**2)*d(ap,dp,ph,e1,e2,e3,e4,e5,y)
>>     else:
          raise Valueerror("Delta returned negative result")

try:

np.sqrt(x1(ap,dp,ph,e1,e2,e3,e4,e5,y)**2+y1(ap,dp,ph,e1,e2,e3,e4,e5,y)**2)
except ValueError:
   # do something here? or log the faulty data values or just
   pass   # do nothing.
   raise   # or reraise the error after logging


That way your function never returns an invalid value.
It either returns a float or throws an exception which
you can catch and do with it as you will.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list