I didn't understand how the solution of this exercise works

hey
i was doing this simple python exercise
’ Exercise Question 6: Write a recursive function to calculate the sum of numbers from 0 to 10

Expected Output :

55’
it was pretty easy and my answer was
'def sum(n):
k=0
for i in range(n+1):
k+=i
else:return k

print(sum(10))’
it worked properly
but when i looked at the solution i didnt get how does it work exactly
the solution was

def calculateSum(num):
    if num:
        return num + calculateSum(num-1)
    else:
        return 0

res = calculateSum(10)
print(res)

please explain it to me
thanks

Hi,

The question is asking for a specific technique to be used when getting the result: recursion. Your answer uses iteration instead.

The defining aspect of a recursive function, is a function that calls itself within its definition. A characteristic that is found in many recursive functions is a base case that establishes potential start and break points.

A common mathematical operation that is commonly associated with recursion is the factorial. (For example, in this article: https://www.khanacademy.org/computing/computer-science/algorithms/recursive-algorithms/a/the-factorial-function)

Recursion can be sometimes tricky to grasp at first but it can be a powerful tool once you control it. Some recursive functions can be instead written with loops, but not all can (and sometimes it’s more appropriate to use one over the other). The issue of picking the right tool for the job and all that…

Here’s a simple example:

def hello(num):
  if num == 0:
    return
  print(str(num) + " hello")
  hello(num-1)

hello(3)
#output:
3 hello
2 hello
1 hello
2 Likes

OH
thank you so much , i totally missed the recrusion part , and even if i didn’t
i had no idea what it is until now
thank you again for the clairification

1 Like

This topic was automatically closed 41 days after the last reply. New replies are no longer allowed.