Python: Check if Variable is a Number

Spread the love

In this article, we’ll be going through a few examples of how to check if a variable is a number in Python.
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

myFloat = 1.0

myString = ‘s’

This results in:
<class ‘int’>
<class ‘float’>
<class ‘str’>

Thus, a way to check for the type is:
myVariable = input(‘Enter a number’)
if type(myVariable) == int or type(myVariable) == float:
# Do something
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’)
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.
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:

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
tmp = int(myVariable)
print(‘The variable a number’)
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.
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.

X ITM Cloud News


Leave a Reply

Next Post

I'm Building a 16-bit, along with Assembler, C-ish Language, and Later Turning the Whole Thing into a Fantasy Game Console. Here I'm Extending the Assembler to Parse and Resolve Data and Constant Directives

Wed Sep 16 , 2020
Spread the love           submitted by /u/FrancisStokes [link] [comments] X ITM Cloud News

Cloud Computing – Consultancy – Development – Hosting – APIs – Legacy Systems

X-ITM Technology helps our customers across the entire enterprise technology stack with differentiated industry solutions. We modernize IT, optimize data architectures, and make everything secure, scalable and orchestrated across public, private and hybrid clouds.

This image has an empty alt attribute; its file name is x-itmdc.jpg

The enterprise technology stack includes ITO; Cloud and Security Services; Applications and Industry IP; Data, Analytics and Engineering Services; and Advisory.

Watch an animation of  X-ITM‘s Enterprise Technology Stack

We combine years of experience running mission-critical systems with the latest digital innovations to deliver better business outcomes and new levels of performance, competitiveness and experiences for our customers and their stakeholders.

X-ITM invests in three key drivers of growth: People, Customers and Operational Execution.

The company’s global scale, talent and innovation platforms serve 6,000 private and public-sector clients in 70 countries.

X-ITM’s extensive partner network helps drive collaboration and leverage technology independence. The company has established more than 200 industry-leading global Partner Network relationships, including 15 strategic partners: Amazon Web Services, AT&T, Dell Technologies, Google Cloud, HCL, HP, HPE, IBM, Micro Focus, Microsoft, Oracle, PwC, SAP, ServiceNow and VMware