[英]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.