+ 3
How to check whether an object is string or integer in python. Also using if... else... to determine them
I created an input() command and now i want to know whether the input is str or int. I will use if... and else... statement to print (something) if input id int and print(anything) if it's a string. How can I do it ? Could anybody tell it. Plzzzzzz...đđđ
9 Answers
+ 4
Hello.
input function always returns a string of what user has typed, but you can make the program to check, whether each character user typed is valid to be an integer.
You can test it with 2 easy ways, when x = input().
condition variable will be True if x is integer.
#1:
condition = x.isnumeric()
#Checks whether x (string) only includes numeric characters, returns True if it does, else it returns False.
#if the method isnumeric finds decimal point "." or a subtraction mark "-", it also returns False, that's why it doesn't always work.
#2:
try:
int(x)
except ValueError:
condition = False
else:
condition = True
#Checks whether x can be converted to an integer.
#Also supports subtraction character to be included in x.
Then you could use the condition variable in if conditions later in the program.
Later in the program you could use:
if condition:
y = int(x)
else:
y = x
del condition
print("y is", " " if type(y) == int else " not ", "an integer", sep="")
+ 3
Type can also be checked with:
val = 3 // 2
if isinstance(val, int):
# do ...
+ 3
Rayyan, even if your work is done, i just want to give a very simple check from input() if itâs an int or not:
inp1 = '123'
inp2 = 'hello'
def is_int(check):
try:
int(check)
return True
except:
return False
print('inp1', is_int(inp1))
print('inp2', is_int(inp2))
+ 2
But Seb TheS,
It can't be used with input() function as every object's type is str in input()
+ 2
However, Thank you everyone for advising me right.
My work is done.
+ 2
Kay, uh...
Thanks Lother!
+ 1
But the type() only tells the class girl. I can't use it with if... else... statement.
0
Rayyan Nafees You can use type in if statements to test, whether an objects belongs to a certain class.
type(5) == int #True
type("5") == int #False
type("5") == str #True
But like Lothar mentioned isinstance(x, y) would perform the same work than type(x) == y
isinstance(5, int) #True
isinstance("5", int) #False
isinstance("5", str) #True