简体   繁体   English

输入 function 能否用于将参数传递给递归 function?

[英]Can the input function be used to pass an argument to a recursive function?

First time posting here.第一次在这里发帖。 New to Python and experimenting to try and better understand recursion and the input function. Python 的新手并尝试更好地理解递归和输入 function。 In this code, I'm trying to take user input (x) and pass it to a recursive function.在这段代码中,我试图获取用户输入(x)并将其传递给递归 function。 I think it will print a list of (x) numbers, where the difference in each successive number reduces by 1. Whatever it does, I will learn from but I really just want to know what I need to change to take user input and pass it to this recursive function.我认为它会打印一个(x)数字列表,其中每个连续数字的差值减少 1。无论它做什么,我都会从中学习,但我真的只想知道我需要更改什么来获取用户输入并通过它到这个递归 function。 The code was inspired by this example:该代码受此示例的启发:

https://www.w3schools.com/python/trypython.asp?filename=demo_recursion https://www.w3schools.com/python/trypython.asp?filename=demo_recursion

Thanks.谢谢。

x = int(input("Choose a number "))

def add_last(x):
  result = x + (add_last(x- 1))
  print(result)

add_last(x)

Recursive functions must always have an “end” case, ie, when to end the recursion?递归函数必须始终有一个“结束”情况,即,何时结束递归?

So in add_last , probably add something like:所以在add_last中,可能会添加如下内容:

if x==0:
   return 0

Without an end case you will likely run into a RecursionError: maximum recursion depth exceeded如果没有结束情况,您可能会遇到RecursionError: maximum recursion depth exceeded

Since you're just printing, you don't need to return anything.由于您只是打印,因此您无需返回任何东西。

def add_last(x):
    if x == 0:
        return
    print(x)
    add_last(x-1)

print("\n\nRecursion Example Results")
add_last(6)

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

相关问题 如何将输入作为 function 的参数传递? - How to pass input as argument of a function? Python - 将变量/对象作为要在函数中使用的参数传递? - Python - pass a variable/object as argument to be used in a function? 为什么不能在递归函数中使用yield - why can't yield be used in a recursive function Python:传递要在input()函数中显示的参数 - Python: pass an argument to be displayed in the input() function 编写递归函数时,何时将“count”作为参数从一个递归调用传递到另一个与定义“count + = 递归函数”? - When writing a recursive function, when to pass 'count' as argument from one recursive call to another vs. defining "count += recursive function"? Julia 可以将参数传递给内部匿名函数吗? - Can Julia pass an argument to an inner anonymous function? 我可以将异常作为参数传递给python中的函数吗? - Can I pass an exception as an argument to a function in python? 我可以将任意关键字参数传递给 function 吗? - Can I pass arbitrary keyword argument into a function? 在递归 function 中更改了参数的 COPY - In recursive function changed COPY of argument Python function 参数不能用作子变量 function - Python function argument can't be used as a variable in a child function
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM