How can I check if the type is int or float?


#1

Question

How can I check if the type is int or float?

Answer

To determine whether or not the value given to the function is an int or a float, we need to understand what is being returned to us by the type() function.
type() accepts one argument, as we know, and returns its type as either int, float, or str, among others. It does not return it as a string like ”int”.
If your code looked like this:

def my_function(value):
  if type(value) == “str”:
    return “It’s a string!”

That would be invalid! type() will never return ”str”, so it cannot possibly enter that conditional statement.
Another common error is misusing type()’s argument. For example, if you checked for type(int) or type(float), that’s not quite what we’re trying to do in this exercise. Be sure to give the argument given to your function as the argument for type().
Lastly, keep in mind that == is used for comparison, while = is used to assign values. If you use = in an expression being checked, you will get an error.


FAQ: Learn Python: Functions - Review: Built-In Functions
#2

I don’t get it. Why does

print type(5)

result in <type ‘int’> and not just int ?

Thanks in advance


#3

2 posts were split to a new topic: Why Do We Check Datatypes Without Quotes?


#4

I’d suggest to check the type of ‘n’ in if statements using this :

if type(n) is int:
if type(n) is float:
if type(n) is str: