Python Check only outputting a string

Question:

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

Asked By: umfhero

||

Answers:

Input always returns string. If you want some other type you have to cast.
For example:

input_int = int(input("Enter something"))
Answered By: Batmates

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))
Answered By: CosmicOni

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.

Answered By: CPP_is_no_STANDARD

By default when you type input(), python run it as string data-type so you can change or actually limit it by usage of int()

integer_number = int(input("only numbers accepted: "))
Answered By: Ali Mohammadnia
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.