How do I print the output in different lines in this code?

Asked

Viewed 43 times

-2

#Divisores I#

def divisores(num):
    for i in range(1, num//2+1):
        if num % i == 0: 
            yield i
    yield num

num = int(input())
print(list(divisores(num)))

The answer is going in the same line, I wanted them to be below each other, but I can’t.

  • 1

    One possibility is for x in lista: print(x).

  • 2

    William, give a searched on the site because it already has enough content on it. ;)

  • Complicating: print('\n'.join([str(i) for i in list(divisores(num))]))

1 answer

1


To solve this issue you can use the following code:

def divisores(n):
    for i in range(1, (n // 2) + 1):
        if n % i == 0:
            yield i


num = int(input())
for j in divisores(num):
    print(j)

According to the documentation Yield is an expression of performance that serves as a generating function and thus can only be used in the body of functions.

When a generating function is called, a iterator known as the generator. In this way the generator controls the execution of the generating function. At this point the first expression of income is executed and then its activity is suspended, thus returning the value of the Expression list. Then the process is redone until all operations are completed.

Observing

This code is used to calculate OWN DIVIDERS of a number.

Now, if you want to calculate the NATURAL DIVIDERS of a number, you can use the following code:

def divisores(n):
    for i in range(1, n + 1):
        if n % i == 0:
            yield i


num = int(input())
for j in divisores(num):
    print(j)

Browser other questions tagged

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