Recursiveness using Python

Asked

Viewed 195 times

0

I am trying to create a recursive function that takes a positive integer number N and prints all even numbers from 0 to N in ascending order.

I’m only managing to do the opposite, that is, print the numbers down. Below will be the code that I built, but it does not perform the task you want. Already, I want to thank for the help and attention of all who will cooperate.

def sequencia_de_numero(number):
    if number == 0:
        print(number)
    else:
        if number % 2 == 0:
            print(number)
            return sequencia_de_numero(number -1)
        else:
            return sequencia_de_numero(number - 1)

2 answers

4

Calling the function itself before the print works:

def sequencia_de_numero(number):
    if number < 0:
        return -1
    
    sequencia_de_numero(number - 1)
    
    if number % 2 == 0:
        print(number, end=' ')

Then just call the function normally:

sequencia_de_numero(40)

-2

Here is an example of a recursive function:

def factorial(x):
    if x < 3:
        return x
    else:
        return x * factorial(x - 1)

But if you want to make a crescent sequence, have no need to use functions, use a loop for:

for i in range(0, 42, 2): #O terceiro número na função range é o passo, se você usar 2, só vai ter números pares
    print(i)
  • 2

    And what is the purpose of an example of recursive factorial in this question?

  • Because this function is recursive, and demonstrates recursion

Browser other questions tagged

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