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
CodePudding user response:
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))
CodePudding user response:
Input always returns string. If you want some other type you have to cast. For example:
input_int = int(input("Enter something"))
CodePudding user response:
You should know that, the default input is set to return string. To make this clear, do refer to the following example:
>>> number_input = input("Input a number: ")
Input a number: 17
>>> number = number_input
>>> print(type(number))
<class 'str'>
Python defines the number_input
as a string, because input
is by default a string. And if python recognizes number_input
as string, variable number
must also be a string, even though it is purely numbers.
To set number
as a int, you need to specify the input as int(input("Input a number: "))
. And of course, if you want to input float, just change the data type to float input.
But answering your question, you can't print <class 'str'>
and <class 'int'>
at the same time.
CodePudding user response:
By default when you type Input() python run it as string so you can change or actually limit it by usage of int()
integer_number = int(input("only numbers accepted: "))