1

I was wondering if it was possible to specify the type of input in a function or if I had to use something else.

Imagine that I defined a function (example). I want my parameter (type) to indicate what type the input will be as if

int(input())

If it's not an int, I send an error and I ask again for an input.

def example(type) :
    while True :
        try :
            var = type(input())
        except :
            print("error")
        else :
            break
    return var

example(int)

I don't know if it's possible. Eventually, I want to do it for floats and strings. I bypassed the problem with if / else. Do you have other solutions? I want to shorten my code as much as possible.

akaSIedge
  • 11
  • 1
  • You can use [ininstance](https://docs.python.org/3/library/functions.html#isinstance) to check the type of input – Devesh Kumar Singh Sep 25 '19 at 14:41
  • I guess I'm doing something wrong. ```python def test(type) : var = input() return isinstance(var, type) print(test(int)) ``` When I enter 5, it returns me False. – akaSIedge Sep 25 '19 at 14:55
  • 1
    Well, `input` will always return a string, so checking whether it's an instance of `int` is nonsense. Your current approach looks good enough, any issues with it…? – deceze Sep 25 '19 at 14:59
  • Right I forgot about that, but I managed to solve it. I didn’t know I could set a variable as a class. – akaSIedge Sep 25 '19 at 15:05

1 Answers1

0

input returns a str everytime. And type is already the name of a function in Python (which returns the type of the parameter).

So you will have to convert (cast) the string to int or float if you have to and surround it with try / except I'm afraid.

Fred Lass
  • 1
  • 1