Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to accept only 5 inputs in Python using recursion and if loops

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 None if 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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading