Wednesday, September 8, 2021

Python Is Integer

Python Is Integer

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.

  1. isinstance() method
  2. is_integer() method
  3. type() method
  4. try except method
Python isinstance

Python 3 isinstance() Examples

Example1

In [2]:
isinstance(5,int)
Out[2]:
True

Example2

In [3]:
isinstance(5.5,int)
Out[3]:
False

Example3

In [4]:
isinstance('hello',int)
Out[4]:
False

Python 2 isinstance() Examples

Python 2 has two integer data types - int and long.

Example1

In [7]:
isinstance(long(5),(long))
Out[7]:
True
In [8]:
isinstance(5,long)
Out[8]:
False
In [9]:
isinstance(5,int)
Out[9]:
True
is_integer Python

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

In [6]:
x = 5.5
x.is_integer()
Out[6]:
False

However is_integer() can be used for integers if we first convert integer to float as shown in example 2.

Example2

In [7]:
x = 5
float(x).is_integer()
Out[7]:
True

Note: You can't use float(x).is_integer() standalone. You will need

(continued...)

from Planet SciPy
read more

No comments:

Post a Comment

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...