This notebook explains how to check in Python if a number is a integer.
There are multiple ways to check for integer in Python 2 and Python 3.
- isinstance() method
- is_integer() method
- type() method
- try except method
Python 3 isinstance() Examples
Example1
isinstance(5,int)
True
Example2
isinstance(5.5,int)
False
Example3
isinstance('hello',int)
False
Python 2 isinstance() Examples
Python 2 has two integer data types - int and long.
Example1
isinstance(long(5),(long))
True
isinstance(5,long)
False
isinstance(5,int)
True
is_integer is similar in both Python 2 and Python 3.
is_integer Python is for float numbers. It checks whether a float number is an integer.
Example1
x = 5.5 x.is_integer()
False
However is_integer() can be used for integers if we first convert integer to float as shown in example 2.
Example2
x = 5 float(x).is_integer()
True
Note: You can't use float(x).is_integer() standalone. You will need
from Planet SciPy
read more
No comments:
Post a Comment