w3resource

Python: Check whether variable is integer or string

Python Basic: Exercise-144 with Solution

Write a Python program to check whether a variable is an integer or string.

Sample Solution-1:

Python Code :

# Check if 25 is an instance of an integer (int) or a string (str).
print(isinstance(25, int) or isinstance(25, str))

# Check if the list containing 25 is an instance of an integer (int) or a string (str).
print(isinstance([25], int) or isinstance([25], str))

# Check if the string "25" is an instance of an integer (int) or a string (str).
print(isinstance("25", int) or isinstance("25", str))

Sample Output:

True                                                                    
False                                                                   
True 

Flowchart:

Flowchart: Check whether variable is  integer or string.

Sample Solution-2:

Python Code :

# Define a function 'test' that takes a parameter 'n'.
def test(n):
    # Check if the type of 'n' is equal to 'int'.
    if type(n) == int:
         # If 'n' is an integer, return the message "It is an integer!"
         return "It is an integer!"
    else:
         # If 'n' is not an integer, return the message "It is a String!"
         return "It is a String!"     

# Call the 'test' function with an integer argument (12) and print the result.
print(test(12))

# Call the 'test' function with a string argument ('23312') and print the result.
print(test('23312'))

Sample Output:

It is an integer!
It is a String!

Flowchart:

Flowchart: Check whether variable is  integer or string.

Python Code Editor :

 

Previous: Write a Python program to determine whether the python shell is executing in 32bit or 64bit mode on operating system.
Next: Write a Python program to test whether a variable is a list or tuple or a set.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/python-basic-exercise-144.php