Detect if a variable holds int value or string value in Python

Detect if a variable holds int value or string value in Python:

 

1.Function Definition:

    • The function check_variable_type takes a single argument variable.
    • It uses is instance to check if variable is an instance of int.
    • If the variable is an integer, it returns “Integer”.
    • If the variable is an instance of str, it returns “String”.
    • If the variable is neither an integer nor a string, it returns “Other”.
  1. Example Usage:
    • Two variables var1 and var2 are defined, with var1 being an integer and var2 being a string.
    • The function check_variable _type is called for each variable, and the results are printed.

This approach ensures that you can accurately determine whether a variable is holding an integer or a string value. If you need to handle more types, you can extend the function with additional is instance checks.

Program:

# Sample variables
var1 = 42
var2 = “Hello, world!”
var3 = 3.14
var4 = [1, 2, 3]

# Function to check the type
def check_variable_type(variable):
if isinstance(variable, int):
return “Integer”
elif isinstance(variable, str):
return “String”
elif isinstance(variable, float):
return “Float”
elif isinstance(variable, list):
return “List”
else:
return “Unknown type”

# Check types of variables
print(f”var1 is of type: {check_variable_type(var1)}”)
print(f”var2 is of type: {check_variable_type(var2)}”)
print(f”var3 is of type: {check_variable_type(var3)}”)
print(f”var4 is of type: {check_variable_type(var4)}”)

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top