0

I have a recursive function that calls itself until it gets the correct input.

def input_something(prompt = ""):
    playerInput = input(prompt)
    if playerInput == "": 
        print("Error: No input")
        input_something(prompt)
    elif not playerInput.isspace():
        return playerInput
    else:
        print("Error: Incorrect input")
        input_something(prompt)

while True:
    print("Input Value")
    inp = input_something("> ")
    print(type(inp))
    print(inp)
    print("\n")

The function works fine if you give it a normal value however it breaks if you first give it an empty string and then a character/string. Instead of outputting the string as intended it gives a None type.

Can anyone explain this?

JudasMoses
  • 378
  • 4
  • 22

3 Answers3

1

You need to return the result of the recursive call:

def input_something(prompt = ""):
    playerInput = input(prompt)
    if playerInput == "": 
        print("Error: No input")
        return input_something(prompt)
    elif not playerInput.isspace():
        return playerInput
    else:
        print("Error: Incorrect input")
        return input_something(prompt)

Otherwise, the recursively called function will run but its return value will be thrown away. Note that your original function does not return in two out of the three branches. In Python, not returning anything means the returned value is None.

ales_t
  • 1,967
  • 11
  • 10
0

Changing the function input_something to:

def input_something(prompt = ""):
    playerInput = input(prompt)
    if playerInput == "": 
        print("Error: No input")
        return input_something(prompt)
    elif not playerInput.isspace():
        return playerInput
    else:
        print("Error: Incorrect input")
        return input_something(prompt)

It fixes the issue.

It's because when the code first enters the function and we input something other than a correct input, it doesn't ever return a value to the while loop.

If I enter "" then "hello", the correct string "hello" will be returned to the first iteration of input_something and NOT to the while loop, then since we do nothing with that value, the function simply exits without changing the playerInput variable to the correct string "hello".

Wasp
  • 16
  • 1
0

The code displayed ends in infinite recursive loop, irrespective of the correct value. If your intention is to recursively check until correct input is provided the following code will do:

def input_something(prompt = ""):

playerInput = input(prompt)

while True:
    if playerInput == "": 
        print("Error: No input")
        return input_something(prompt)
    elif not playerInput.isspace():
        return playerInput      
    else:
        print("Error: Incorrect input")
        return input_something(prompt)

inp = input_something("> ")
print(inp)
ibrahim
  • 81
  • 1
  • 9