Search code examples
pythonreturn

Returning value from a function when the function itself called inside PYTHON


My function in python looks like below:

def choose_sepa_reason_code():
    # This method is for providing proper sepa reason code

    sepa_reason_code = input("\nPlease provide SEPA reason code to reject the payment: ")

    if sepa_reason_code in sepa_reason_codes:
        return sepa_reason_code
    else:
        print("Your reason codes doesnt match the list:\n")
        pprint(sepa_reason_codes)
        choose_sepa_reason_code()

provided_sepa_reason_code = choose_sepa_reason_code()

The if statement is to make sure that user will provide proper code, but if he is wrong at the first time my function later returns None.

Could you please advise how to change it to get final correct user input?


Solution

  • If you really want to call the function recursively, call choose_sepa_reason_code() as return value in your else statement:

    sepa_reason_code = input("\nPlease provide SEPA reason code to reject the payment: ")
    
    if sepa_reason_code in sepa_reason_codes:
        return sepa_reason_code
    else:
        print("Your reason codes doesnt match the list:\n")
        print(sepa_reason_codes)
        return choose_sepa_reason_code()