Hướng dẫn check if number python

Introduction

In this article, we'll be going through a few examples of how to check if a variable is a number in Python.

Show

Python is dynamically typed. There is no need to declare a variable type, while instantiating it - the interpreter infers the type at runtime:

variable = 4
another_variable = 'hello'

Additionally, a variable can be reassigned to a new type at any given time:

# Assign a numeric value
variable = 4

# Reassign a string value
variable = 'four'

This approach, while having advantages, also introduces us to a few issues. Namely, when we receive a variable, we typically don't know of which type it is. If we're expecting a Number, but receive variable, we'll want to check if it's a number before working with it.

Using the type() Function

The type() function in Python returns the type of the argument we pass to it, so it's a handy function for this purpose:

myNumber = 1
print(type(myNumber))

myFloat = 1.0
print(type(myFloat))

myString = 's'
print(type(myString))

This results in:




Thus, a way to check for the type is:

myVariable = input('Enter a number')
if type(myVariable) == int or type(myVariable) == float:
    # Do something
else:
    print('The variable is not a number')

Here, we check if the variable type, entered by the user is an int or a float, proceeding with the program if it is. Otherwise, we notify the user that they've entered a non-Number variable. Please keep in mind that if you're comparing to multiple types, such as int or float, you have to use the type() function both times.

If we just said if type(var) == int or float, which is seemingly fine, an issue would arise:

myVariable = 'A string'
if type(myVariable) == int or float:
    print('The variable a number')
else:
    print('The variable is not a number')

This, regardless of the input, returns:

The variable is a number

This is because Python checks for truth values of the statements. Variables in Python can be evaluated as True except for False, None, 0 and empty containers like [], {}, set(), (), '' or "".

Hence when we write or float in our if condition, it is equivalent to writing or True which will always evaluate to True.

numbers.Number

A good way to check if a variable is a number is the numbers module. You can check if the variable is an instance the Number class, with the isinstance() function:

import numbers

variable = 5
print(isinstance(5, numbers.Number))

This will result in:

True

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

Note: This approach can behave unexpectedly with numeric types outside of core Python. Certain frameworks might have non-Number numeric implementation, in which case this approach will falsely return False.

Using a try-except block

Another method to check if a variable is a number is using a try-except block. In the try block, we cast the given variable to an int or float. Successful execution of the try block means that a variable is a number i.e. either int or float:

myVariable = 1
try:
    tmp = int(myVariable)
    print('The variable a number')
except:
    print('The variable is not a number')

This works for both int and float because you can cast an int to float and a float to an int.

If you specifically only want to check if a variable is one of these, you should use the type() function.

Conclusion

Python is a dynamically typed language, which means that we might receive a data type different than the one we're expecting.

In cases where we'd want to enforce data types, it's worth checking if a variable is of the desired type. In this article, we've covered three ways to check if a variable is a Number in Python.