When I was learning programming in school I never understood what recursion was and kept getting confused. I thought I would never have to write such code again and you can imagine my surprise when I saw this challenge.
Luckily, I did some research on it yesterday and looking at the explanation and code in Python it was quite simple to grasp as it was clear plus I read it like three times to get the gist of it.
Basically a recursive function is a function that calls itself.
The Task:
Write a factorial function that takes a positive integer, N as a parameter and prints the result N! of (N factorial).
# defining my function that accepts an integer.
def factorial(num):
# if the integer is 1 then the function returns the value 1
if num ==1:
return num
#if the intege ris not 1 then it calculates the factorial by calling the same function we created subtracting 1 from the integer.
else:
return num * factorial(num -1)
'''
Sample Input
3
Sample Output
6
'''
Top comments (0)