Reputation: 13
I'm very new to python, so I'm very very confused about what is wrong with the function. Basically, I want to make a function that check if x is integer, if it is, then it should evaluate it as "positive" or "negative." If not, then I want it to return "not int" as a result.
Here are the function that I tried to fix back and forth for some time now.
def negativeIntAlert(x):
if x != int(x):
return "not int"
else:
if x >= 0:
return "positive"
else:
return "negative"
I do not understand why it doesn't work like it should, because it gives me "not int" almost every time. I also have problems with Boolean type such as: negativeIntAlert(True) and it gives me "positive" instead of "not int", anything I can do to make Boolean = "not int" in this particular function?
Upvotes: 1
Views: 140
Reputation: 739
You may try something like
def negativeIntAlert(x):
if not isinstance(x, int):
return "not int"
else:
if x >= 0:
return "positive"
else:
return "negative"
Update
You want to solve the bool problem, so use type
instead
if type(x) != int:
return "not int"
Upvotes: 3
Reputation: 678
You can try this instead using if condition
def negativeIntAlert(x):
try:
x = int(x)
if x >= 0:
return "positive"
else:
return "negative"
except:
print ("it is no an int")
Upvotes: 0
Reputation: 4292
For historical reason Boolean are inherited from int, so isinstance(True, int)
will give you True
, from PEP-0285:
This PEP proposes the introduction of a new built-in type, bool, with two constants, False and True. The bool type would be a straightforward subtype (in C) of the int type, and the values False and True would behave like 0 and 1 in most respects (for example, False==0 and True==1 would be true) except repr() and str(). All built-in operations that conceptually return a Boolean result will be changed to return False or True instead of 0 or 1; for example, comparisons, the "not" operator, and predicates like isinstance().
So this would be better:
def negativeIntAlert(x):
if isinstance(x, int) and not isinstance(x, bool):
if x >= 0:
return "positive"
else:
return "negative"
else:
return "not int"
Upvotes: 2