1

I need help with a small assignment, I'm just starting out in Python... I want to create a data type identifier, wherein if I type an int, it will output "It is an int" and if I type a string it will output "It is a String", basically that...

So far this is my code:

input_data = (input())
data_calculator = (type(input_data))
if data_calculator == str:
    print("It is a String")
elif data_calculator == float:
    print("It is a float")
elif data_calculator == int:
    print("It is an int")
else:
    print("Error mate...")

I think the problem is when I type in the console, it treats the int and float as an str.

Current outputs:

when I type an Int or a float, it keeps outputting, "It is a String"

Any help is appreciated, thank you

1 Answers1

1

input always returns an str value, but you can check if the cast is possible with an exception.

Here is a snippet which does that:

def check_type(_type, val):
    try:
        x = _type(val)
        return True
    except:
        return False

def find_type(val):
    for _type in [int, float, complex]:
        if check_type(_type, val):
            return _type
    if val in ['True' ,'False']:
        return bool
    return str

if __name__ == "__main__":
    while True:
        s = input("s = ? ")
        t = find_type(s)
        print("The value of string s has type", t.__name__)

The output with some test strings is:

s = ? 5
The value of string s has type int
s = ? 3.14
The value of string s has type float
s = ? 1+2j
The value of string s has type complex
s = ? False
The value of string s has type bool
s = ? foo
The value of string s has type str

Edouard Thiel
  • 5,878
  • 25
  • 33
  • ``str(x)`` is not appropriate to check literals – ``str`` works on *every* input. For example, the ``val``s ``12/3``, ``b"bytes"``, ``except`` all are valid inputs to ``str`` without being string literals. – MisterMiyagi Apr 19 '21 at 08:08
  • In fact, same problem with `bool`, I have improved the code. – Edouard Thiel Apr 19 '21 at 08:19