Predict the output of the following code:

def sum(n):

    if n == 0:

        return 0

    else:

        return n + sum(n-1)

x = 5

y = sum(x)

print(y)

x = sum(x-2)

print(x, end='!')

Answer:

Answer by student

The output is:

-lock-

15

6!

Detailed answer by teachoo

  • The code defines a recursive function named sum that takes a parameter n and returns the sum of the first n natural numbers.
  • A recursive function is a function that calls itself within its body, until a base case is reached.
  • The base case for this function is when n is 0, in which case it returns 0.
  • The recursive case is when n is greater than 0, in which case it returns n + sum(n-1) , which means adding the current number to the sum of the previous numbers.
  • The code then assigns 5 to a variable x and calls the function sum with x as an argument, storing the result in a variable y .
  • The function call sum(5) will return 15 , which is 1 + 2 + 3 + 4 + 5, and this value will be assigned to y .
  • The code then prints the value of y , which is 15, followed by a newline character.
  • The code then calls the function sum again with x-2 ie., 5-2 = 3 as an argument, and assigns the result to x .
  • The function call sum(x-2) will return 6, which is 1 + 2 + 3 , and this value will be assigned to x .
  • The code then prints the value of x , which is 6, followed by an exclamation mark and no newline character.

So, the output of the code is:

15

6!

-endlock-

Remove Ads
Davneet Singh's photo - Co-founder, Teachoo

Made by

Davneet Singh

Davneet Singh is an IIT Kanpur graduate and has been teaching for 16+ years. At Teachoo, he breaks down Maths, Science and Computer Science into simple steps so students understand concepts deeply and score with confidence.

Many students prefer Teachoo Black for a smooth, ad-free learning experience.