+ 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...🙏🙏🙏

2nd Jun 2019, 11:16 AM
Rayyan Nafees
Rayyan Nafees - avatar
8 Respuestas
+ 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="")
2nd Jun 2019, 11:23 AM
Seb TheS
Seb TheS - avatar
+ 3
Type can also be checked with: val = 3 // 2 if isinstance(val, int): # do ...
2nd Jun 2019, 11:57 AM
Lothar
Lothar - avatar
+ 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))
6th Jun 2019, 11:48 AM
Lothar
Lothar - avatar
+ 2
But Seb TheS, It can't be used with input() function as every object's type is str in input()
6th Jun 2019, 8:12 AM
Rayyan Nafees
Rayyan Nafees - avatar
+ 2
However, Thank you everyone for advising me right. My work is done.
6th Jun 2019, 8:13 AM
Rayyan Nafees
Rayyan Nafees - avatar
+ 2
Kay, uh... Thanks Lother!
8th Jun 2019, 5:18 PM
Rayyan Nafees
Rayyan Nafees - avatar
+ 1
But the type() only tells the class girl. I can't use it with if... else... statement.
6th Jun 2019, 7:26 AM
Rayyan Nafees
Rayyan Nafees - avatar
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
6th Jun 2019, 7:55 AM
Seb TheS
Seb TheS - avatar