How can I prove that a value from input is a number in Python?

Question:

For a task I had to write a programm the programm functions nicely so I dont have a problem there. But I have to use input() and than I have to prove if the type is correct. I only needs integer but the type of input(5) is a str. Althought I need a int. But if use int(input()) thats also dont work because I want that my programm says this is a str or a float and because of this we cant move on. So that the programm now this is a number or not

I did try with only input() that were all Strings regardless of the content and i know why this is so but I dont like it. Then I tried int(input()) but this only works if I use actually only numbers. But I have also to type in strings and floats and then the programm should only say it is the wrong type but shouldnt print out an error message

Asked By: Yanoisa

||

Answers:

s = input()


try:
    print(int(s))

except:
    print("not int")
Answered By: rtoth

We can achieve this by using eval only.

e.g:

val = input()
try:
    val = eval(val)
except NameError:
    pass

In try it will try to return the exact data type, like int, float, bool, dict, and list will works fine but if input value is string it will go to NameError and print val is string.

if we want to handle some case on the basis of data type, we can do it using this:

if isinstance(val, int):
    print("This is integer")

if isinstance(val, float):
    print("This is float")

if isinstance(val, str):
    print("This is string")

similary for others as well.

Answered By: Usman Arshad
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.