Reputation: 323
Recently I am creating a function:
def TaxiFare(the_number_of_km):
if the_number_of_km >= 2:
return 24
elif the_number_of_km > 2:
return 24 + int((the_number_of_km - 2)/0.2) * 1.7
else:
return None
print('Something goes wrong !')
TaxiFare("Wrong")
I want to return None
and print 'Something goes wrong !'
when I input non-numerical values in the argument.
However, it turns out:
TypeError: '>=' not supported between instances of 'str' and 'int'
How can I fix it?
Upvotes: 1
Views: 103
Reputation: 2277
Try this:
def TaxiFare(the_number_of_km):
try:
if the_number_of_km >= 2:
return 24
elif the_number_of_km < 2:
return 24 + int((the_number_of_km - 2)/0.2) * 1.7
except TypeError:
print('something goes wrong !')
return None
print(TaxiFare(3.7))
You can use try: except:
to see if it have a error or not.
and did you mean this -> elif the_number_of_km < 2:
instead of this -> elif the_number_of_km > 2:
because you are doing the statement 2 times. >= 2
and > 2
Upvotes: 2
Reputation: 1
Do type checking at first.
def TaxiFare(the_number_of_km):
if not isinstance(the_number_of_km, int):
return None
print('Something goes wrong !')
elif the_number_of_km >= 2:
return 24
elif the_number_of_km > 2:
return 24 + int((the_number_of_km - 2)/0.2) * 1.7
Upvotes: 0
Reputation: 1
All you need to do is to make sure the argument of the function is an integer, you can have another if statement checking if its an integer or string by using type() before executing your code.
def TaxiFare(the_number_of_km):
if type(the_number_of_km) == str:
print('Something goes wrong !')
else:
if the_number_of_km >= 2:
return 24
elif the_number_of_km > 2:
return 24 + int((the_number_of_km - 2) / 0.2) * 1.7
TaxiFare("Wrong")
Upvotes: 0