Python recursive function

Asked

Viewed 83 times

2

I need to build a recursive function in Python that takes an integer n and print to zero and then go back to n. Example: n = 5; > 5 4 3 2 1 2 3 4 5

Until then I built a function, but it only prints 5 4 3 2 1:

>>> def regressive(n):
...   while(n):
...     print(n)
...     n = n - 1
...   print('hello!')
...
>>> regressive(5)
5
4
3
2
1
hello!

Does anyone know how to return to n ?

1 answer

6


This function you wrote is not recursive! Recursion is when a function calls itself. You have written an iterative function.

Look at this code:

def Recursiva(n):
  if n == 1:
    print(n)
    return 
  print(n)
  Recursiva(n-1) 
  print(n)

Recursiva(5)

Upshot:

5
4
3
2
1
2
3
4
5

Every recursive function must have a stop criterion, in which case the criterion is that the parameter n being passed is 1.

Then when you call the Recursive function for the first time and pass a number as parameter, it will check if that number is 1, if it is it prints and returns the function, if it is not it prints the number and calls the Recursive with n-1. At the time the criterion is reached, the function calls will be returned and ending the rest of the function where they were called. Printing numbers increasing in value.

It was clear?

  • Understood! Thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.