简体   繁体   English

如何使用递归和 if 循环在 Python 中仅接受 5 个输入

[英]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.我试图创建一个递归 function 仅使用if语句和递归,最多接受 5 个输入。 If more than 5 inputs are received, the function returns None .如果接收到超过 5 个输入,则 function 将返回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.我知道在每次递归调用中,count 都会重置为 0,因此程序会无限期地运行。 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.我只是不知道如何修改它,以便我最多只能使用if语句和递归来接受 5 个输入。

Edit: Global variables are not allowed.编辑:不允许使用全局变量。 The function must not take in any parameters. function 不得带入任何参数。 The function can only make use of strings or mathematical techniques from the math module. function 只能使用math模块中的字符串或数学技术。

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. foo()本身不接受任何参数。

This meets all of the following constraints described by OP in the comments:这符合 OP 在评论中描述的所有以下约束:

  • uses recursion使用递归
  • uses a function that takes in no parameters使用不接受任何参数的 function
  • no global variables没有全局变量
  • no imports ( math is allowed, but we don't need it here)没有进口( math是允许的,但我们在这里不需要它)
  • returns None if 5 is not received within 5 tries, else returns 5.如果在 5 次尝试内未收到 5,则返回None ,否则返回 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这将 output 一个包含 n 个输入的列表

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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