First time posting here. New to Python and experimenting to try and better understand recursion and the input function. In this code, I'm trying to take user input (x) and pass it to a recursive 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. The code was inspired by this example:
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)
CodePudding user response:
Recursive functions must always have an “end” case, i.e, when to end the recursion?
So in add_last
, probably add something like:
if x==0:
return 0
Without an end case you will likely run into a RecursionError: maximum recursion depth exceeded
I think it will print a list of (x) numbers, where the difference in each successive number reduces by 1.
Well, no. In your function you are simply adding integers, more specifically adding the sum of all previous integers, to the current one. So the return value of your function would simply be another integer, specifically the sigma of x
.
EDIT:
Since you are not returning anything, by default the function returns None
. Therefore the error: TypeError: unsupported operand type(s) for : 'int' and 'NoneType' for the function definition
.
You need to return an integer to make it work.
EDIT 2:
If you are working with huge numbers, and might need to recur multiple times, as @CoderTang suggested you could use sys.setrecursionlimit(you_new_limit)
, to set your own recursion limit.
CodePudding user response:
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)