In Python, variables can hold various types of data, including integers (int) and floating-point numbers (float).
When dealing with dynamic data, it’s crucial to ascertain whether a variable contains a numeric value before performing mathematical operations.
We will discuss two methods that help you achieve this goal: the type() function and the isinstance() function.
def is_number(variable):
"""
This function checks if a variable is a number.
Args:
variable: The variable to check.
Returns:
True if the variable is a number, False otherwise.
"""
return type(variable) in (int, float)
The type()
function returns the type of the given variable. If the type is either int or float, the function returns True, indicating that the variable is a number.
Otherwise, it returns False.
Example Code:
def is_number(variable):
"""
This function checks if a variable is a number.
Args:
variable: The variable to check.
Returns:
True if the variable is a number, False otherwise.
"""
return type(variable) in (int, float)
# Examples
number = 10
result_number = is_number(number)
string = "Hello"
result_string = is_number(string)
print(f"Is {number} a number? {result_number}")
print(f"Is {string} a number? {result_string}")
Is 10 a number? True
Is Hello a number? False
def is_number(variable):
"""
This function checks if a variable is a number.
Args:
variable: The variable to check.
Returns:
True if the variable is a number, False otherwise.
"""
return isinstance(variable, (int, float))
The isinstance()
function verifies if the variable is an instance of either the int or float class.
If the variable is indeed an instance of either of these classes, the function returns True; otherwise, it returns False.
Example Code:
def is_number(variable):
"""
This function checks if a variable is a number.
Args:
variable: The variable to check.
Returns:
True if the variable is a number, False otherwise.
"""
return isinstance(variable, (int, float))
# Examples
number = 20
result_number = is_number(number)
string = "Good Bye"
result_string = is_number(string)
print(f"Is {number} a number? {result_number}")
print(f"Is {string} a number? {result_string}")
Is 20 a number? True
Is Good Bye a number? False
The choice between the type()
and isinstance()
methods depends on your coding style and specific requirements.
The type()
function offers a concise approach, while the isinstance()
function provides more explicit validation.