I’m making a program that determines what type the input is (int, float or str), however I know that the input() function accepts inputs as strings so I’m a bit stuck.
stuff = input('Enter something: ')
print('Input is int?', stuff == int(stuff))
print('Input is float?', stuff == float(stuff))
print('Input is string?', stuff == str(stuff))
The above code is just to provide some context, it doesn’t actually work though.
Or the more practical way:
stuff = input('Enter something: ')
print(type(stuff))
But it always returns <class 'str'> which doesn’t always provide the correct answer e.g what if I entered "10"? Any ideas on how to change the type the input?
>Solution :
Do something like this:
stuff = input('Enter something: ')
try:
# first you try an int, which is the most restrictive one
stuff = int(stuff)
print("It's an int")
except ValueError:
# then you try a float which is less restrictive
try:
stuff = float(stuff)
print("It's a float")
except ValueError:
# if both conversions fail, it's a string
print("Looks like it's a string after all")