The code won't recognize my if statement (Python) -
the code wont recognize if statement. when run code, enter following number: -10. however, returns else statement, when should return if statement. doing wrong?
def distance_from_zero(d): if type(d)== int or type(d)==float: return abs(d) else: return "not integer or float!" x = raw_input("enter number: ") print distance_from_zero(d)
raw_input
returns string. if type number 9, doesn't return integer 9
, returns string "9"
. therefore test type(d)== int or type(d)==float
never true.
you
def distance_from_zero(d): try: return abs(int(d)) except valueerror: pass try: return abs(float(d)) except valueerror: pass return "not integer or float!" x = raw_input("enter number: ") print distance_from_zero(x)
this makes use of design philosophy popular in python called "duck typing", in which, rather test see object's type is, treat object whatever type want , handle exception pops if isn't type.
Comments
Post a Comment