Check if a value is an integer

EasyIf-Else Programs · 25 of 64

Write a Python program to check whether a given value is an integer.

Advertisement
Input
54, 5.4, "54"
Output
54 True
5.4 False
'54' False
True False

Approach

  1. Use isinstance(value, int), and exclude booleans, which are a kind of int.

Solution

Python
for value in [54, 5.4, "54", True]:    if isinstance(value, int) and not isinstance(value, bool):        print(repr(value), True)    else:        print(repr(value), False)
Output
54 True
5.4 False
'54' False
True False

Line by line

Line 2

isinstance checks the type. True is technically an int in Python, so it is excluded explicitly.

Line 3

repr() shows strings with quotes, so “54” is clearly text.

Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More if-else programs

← All 64 If-Else Programs