Search code examples
pythonpython-3.xfunctionrecursionnonetype

Function returns NoneType after getting it wrong the first time


I have a function that asks for some specific data. I have another function that takes input, and if it is what it should be, it assigns to the variable from it was called.

The problem is that if I get a wrong value, then it will always return NoneType object, even if I get the good answer the second time.

I tried removing the clear(). I tried to add more return, even where the answer should not pass through. I tried adding a second argument to function with the name of the variable I am trying to assign a value

def ask_input_string(text):

    ''' Takes only one argument. This function asks for input when it is called and returns the value but with the argument provided as text. '''

    variable=input(text)
    if variable=="":
        print("\nField must not be empty")  
        ask_input_string(text)
    try:
        int(variable)
        print("\nPlease enter a name!")
        ask_input_string(text)

    except ValueError:
        return variable

def menu_add():
    clear()

    print("\nPlease add the data required!\n")

    nume=ask_input_string("Name of animal: ")

    animal_type=ask_input_string("\nAnimal Type: ")

Expected Result:

If I add a wrong value, It asks for the correct one. I give the correct one, and it assigns to the variable it was called from.

Actual Result:

If I give the wrong answer at least 1 time, then even if I get the correct one, it will always assign NoneType to the variable it was called from.

If I give the correct answer the first time, it works. It does not work if I give a wrong answer in first place.


Solution

  • def ask_input_string(text):
        variable = input(text)
        if variable == "":
            print("\nField must not be empty")
            return ask_input_string(text)
    
        try:
            int(variable)
            print("\nPlease enter a name!")
            return ask_input_string(text)
        except ValueError:
            return variable
    

    You have to return the values from the recursive call. You wouldn't throw away the result of a function like this normally, and recursion isn't really special, it's just another function call.