I’m trying to create a recursive function using only if loops that will accept at max 5 inputs. If more than 5 inputs are received, the function returns None. The code I have so far is:
def foo()
count = 0
n = int(input())
if n == 5:
return n
elif count != 5:
count += 1
return foo()
else:
return None
I understand that in each recursive call, count gets reset to 0 and hence, the program runs indefinitely. I just can’t figure out how to modify it so that I can accept at max 5 inputs using only if statements and recursion.
edit:
global variables are not allowed
the function must take no input
the function can only make use of strings or mathematical techniques from the math module
>Solution :
The following should suit your needs. It uses a helper method that takes in the number of inputs that you have remaining. foo() itself takes in no parameters.
This meets all of the following constraints described by OP in the comments:
- recursive solution
- uses a function that takes in no parameters
- no global variables
- no imports
- returns
Noneif 5 is not received within 5 tries, else returns 5.
def get_input(inputs_remaining):
if inputs_remaining <= 0:
return None
result = int(input())
if result == 5:
return 5
return get_input(inputs_remaining - 1)
def foo():
return get_input(5)
foo()