-1
def recursion():
    A=input("please enter a number between 1-5:")
    if A.isdigit():
        A=int(A)
        if A in range(1,6):
            return A
        else:
            recursion()
    else:
        recursion()
print(recursion())

so the first time that I input the right number that it should return it would return the value correctly but when I'm spamming other stuff that it would make the code return back to recursion() line for about 10 times then after that when I put 3 in the input section which is the correct value and it should return 3 but it returns as none why does it return like that cuz I already put return A so for example

please enter a number between 1-5:d
please enter a number between 1-5:sd
please enter a number between 1-5:fsd
please enter a number between 1-5:f4
please enter a number between 1-5:4
None

the first 1 to 4 line I input something that would make it run the recursion() line again but the last one that I input I input it as 4 which it should return as 4 but it returns as none

please enter a number between 1-5:3
3

this is what I mean by the first time that I enter the correct number then it would return correctly I would be very appreciative if you corrected my code because I'm so bad at python I'm just a beginner and sry for terrible grammar I'm not a native speaker but at least I tried

MPH_08
  • 1
  • 1
  • You don't return the results of the recursions. The most important thing to learn about recursive functions is that they work exactly like non-recursive functions. – molbdnilo Nov 27 '20 at 13:03

1 Answers1

0

You need to return the value returned by the call to the recursive function

def recursion():
    A=input("please enter a number between 1-5:")
    if A.isdigit():
        A=int(A)
        if A in range(1,6):
            return A
        else:
            A = recursion()
    else:
        A = recursion()
    return A
print(recursion())

Personally, I'd use a loop to do this instead rather than calling the same function again.

def getNumber():
    valid = False
    while not valid:
        A=input("please enter a number between 1-5:")
        if A.isdigit():
            A=int(A)
            if A in range(1,6):
                valid = True

    return A
print(getNumber())
scotty3785
  • 6,763
  • 1
  • 25
  • 35