0
0
PythonHow-ToBeginner · 3 min read

How to Check if Variable is Integer in Python: Simple Guide

In Python, you can check if a variable is an integer by using the isinstance() function with int as the type. For example, isinstance(variable, int) returns True if the variable is an integer, otherwise False.
📐

Syntax

The syntax to check if a variable is an integer uses the isinstance() function:

  • isinstance(variable, int): Returns True if variable is an integer.

This function takes two arguments: the variable to check and the type to compare against.

python
isinstance(variable, int)
💻

Example

This example shows how to check different variables to see if they are integers:

python
x = 10
print(isinstance(x, int))  # True

y = 3.14
print(isinstance(y, int))  # False

z = '5'
print(isinstance(z, int))  # False
Output
True False False
⚠️

Common Pitfalls

One common mistake is to check the type by comparing with type() directly, which is less flexible and can fail with subclasses. Also, strings that look like numbers are not integers.

Wrong way:

if type(variable) == int:
    print("It's an integer")

Right way:

if isinstance(variable, int):
    print("It's an integer")
python
variable = 5

# Wrong way
if type(variable) == int:
    print("Using type(): It's an integer")

# Right way
if isinstance(variable, int):
    print("Using isinstance(): It's an integer")
Output
Using type(): It's an integer Using isinstance(): It's an integer
📊

Quick Reference

Check MethodDescriptionExample Result
isinstance(variable, int)Checks if variable is integer or subclassTrue if integer
type(variable) == intChecks if variable is exactly int type (less flexible)True if exactly int
str.isdigit()Checks if string contains only digits (not integer type)True if string digits

Key Takeaways

Use isinstance(variable, int) to check if a variable is an integer in Python.
Avoid using type(variable) == int because it is less flexible with subclasses.
Strings that look like numbers are not integers; use conversion if needed.
isinstance() works well with inheritance and is the recommended approach.