简体   繁体   中英

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

I'm trying to create a recursive function using only if statements and recursion that will accept at most 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 most 5 inputs using only if statements and recursion.

Edit: Global variables are not allowed. The function must not take in any parameters. The function can only make use of strings or mathematical techniques from the math module.

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:

  • uses recursion
  • uses a function that takes in no parameters
  • no global variables
  • no imports ( math is allowed, but we don't need it here)
  • 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()

You could do something like:

def foo(count=5):
    if count == 1:
        return [input()]
    else:
        return [input()]+foo(count-1)

This will output a list with the n inputs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM