0

I need to take an input and convert it to whatever type of variable it is. For example if the input is two, I need to figure out that 2 is and integer and then store the int converted input to an int type variable. For example:

>>> myInput = input("Input a number: ")
>>> if myInput is float:
>>>   print("myInput is a float")
>>> if myInput is int:
>>>   print("myInput is an integer")
Input a number: 2
myInput is an integer

However, what actually happens is:

Input a number: 2

and then the program ends.

RedSox2
  • 7
  • 8
  • 1
    `input()` returns a string. – Corentin Pane Jun 04 '20 at 17:36
  • 1
    Does this answer your question? [Recognising an input() as either a str, float, or int and acting accordingly](https://stackoverflow.com/questions/40185070/recognising-an-input-as-either-a-str-float-or-int-and-acting-accordingly) – Corentin Pane Jun 04 '20 at 17:38

3 Answers3

0

input() returns a string, you have to convert it first. You can determine if it can be a float or an integer by checking for the presence of a '.'

myInput = input("Input a number: ")
if '.' in myInput:
    try:
        myInput = float(myInput)
        print(f'{myInput} is a float')
    except ValueError:
        print(f'{myInput} is not a number')
else:
    try:
        myInput = int(myInput)
        print(f'{myInput} is an integer')
    except ValueError:
        print(f'{myInput} is not a number')
alec_djinn
  • 10,104
  • 8
  • 46
  • 71
0

int and float are not data types, they are built-in functions which convert their argument to an int and a float, respectively. You can use a try catch for this. If calling int(myInput) raises a ValueError, then the string doesn't represent a valid integer, and same with float(myInput).

try:
    int(myInput)
    print('myInput is an int')
except ValueError:
    pass
try:
    myInput = float(myInput)
    print('myInput is a float')
except ValueError:
    pass

Another option

0

This is not a much-sophisticated way but it will work in a good way - I believe Coding should always be fun.

def check_input_type(value):

    out = 'Input is String: {}'
    def is_float(val):
        return not (float(val)).is_integer()

    ord_val = ord(value[0])
    if not ord_val >= 65:
        try:
            if is_float(value):
                out = 'Input is Float: {}'
            else:
                out = 'Input is Integer: {}'
        except ValueError:
            pass
    return out.format(value)

check_input_type(input("Input a number: "))

Let's test:

check_input_type(input("Input a number: "))

Input a number: 78.89
Out[37]: 'Input is Float: 78.89'

check_input_type(input("Input a number: "))

Input a number: 1arrow
Out[38]: 'Input is String: 1arrow'

check_input_type(input("Input a number: "))

Input a number: 123
Out[39]: 'Input is Integer: 123'

check_input_type(input("Input a number: "))

Input a number: 123-one-two-three
Out[40]: 'Input is String: 123-one-two-three'