Perplexityy - 4 months ago 6x

Python Question

I've written a function that takes as input a positive integer n and recursively returns a list of factorial values 1!, 2!, . . . , n!.

However, I can't get it to print the list just a single time. I've tried placing the print statement in various loops/locations and it always prints at least 3 times. I've also tried printing the function but it returns 'None', it only seems to print if I have a print statement in the function. Why is this?

Here is my code:

`def calc_Factorial(my_list, n, x, e):`

if not my_list:

my_list.append(n-(n-1))

calc_Factorial(my_list, n, x, e)

else:

if len(my_list) < n:

my_list.append(my_list[e]*x)

calc_Factorial(my_list, n, x+1, e+1)

if len(my_list) == n:

print(my_list)

e = 0

x = 2

n = int(input('Enter number: '))

my_list = []

calc_Factorial(my_list, n, x, e)

Answer

The value is being printed multiple times because you are using `print`

inside the recursive function. You should return instead of printing inside the recursive function.

```
def calc_Factorial(my_list, n, x, e):
if not my_list:
my_list.append(n-(n-1))
return calc_Factorial(my_list, n, x, e)
else:
if len(my_list) < n:
my_list.append(my_list[e]*x)
return calc_Factorial(my_list, n, x+1, e+1)
if len(my_list) == n:
return (my_list)
e = 0
x = 2
n = int(input("Enter number: "))
my_list = []
print (calc_Factorial(my_list, n, x, e))
```

Source (Stackoverflow)

Comments