num = input("Enter Something:")
print(type(num))
for some reason when running this code, or any alternative version even without text (string), it still outputs a string.
<class 'str'>
is there any way to check for all types like expected? e.g str and int
>Solution :
The problem is that input() returns a string, so the datatype of num will always be a string. If you want to look at that string and determine whether it’s a string, int, or float, you can try converting the string to those datatypes explicitly and check for errors.
Here’s an example of one such check:
def check_user_input(input):
try:
# Convert it into integer
val = int(input)
print("Input is an integer number. Number = ", val)
except ValueError:
try:
# Convert it into float
val = float(input)
print("Input is a float number. Number = ", val)
except ValueError:
print("No.. input is not a number. It's a string")
I got this example here where there’s a more thorough explanation: https://pynative.com/python-check-user-input-is-number-or-string/
Here is a solution based on that for your problem specifically:
def convert_input(input):
try:
# Convert it into integer
val = int(input)
return val
except ValueError:
try:
# Convert it into float
val = float(input)
return val
except ValueError:
return input
num = input("Enter Something:")
num = convert_input(num)
print(type(num))