kapalkat
kapalkat

Reputation: 406

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?

Upvotes: 0

Views: 611

Answers (2)

Danix
Danix

Reputation: 61

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()

Upvotes: 1

WhatsThePoint
WhatsThePoint

Reputation: 3635

firstly your code wont run because it isnt indented, secondly you cant call a function inside itself.

this would be a better approach to your task:

def choose_sepa_reason_code():
# This method is for providing proper sepa reason code
    while True: #will provide permanent loop
        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 #stops loop and returns the reason code
        else:
            print("Your reason codes doesnt match the list:\n")
            print(sepa_reason_codes)

Upvotes: 1

Related Questions