Bob Reynolds
Bob Reynolds

Reputation: 1009

Return all divisors of a number - Python

I want to find all divisors of a number in Python. I'm doing this greatly in Javascript, C#, Java, but my Python code work only with print statement correctly. But I don't want to print divisors, I want to assign them to some variable, or displaying them calling function in print.

def mainFunction(number):
    for i in range(1, number+1):
        if number % i == 0:
            return i

Upvotes: 0

Views: 1866

Answers (3)

Jura
Jura

Reputation: 49

One more, using generator:

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

for divisor in mainFunction(10):
        print( divisor )

Upvotes: 2

Talon
Talon

Reputation: 1884

Like this, your function will return on the first possible divisor (so almost always 1). If you want to keep searching after your first finding, you must save it, e.g. in a list (or use a generator etc).

def mainFunction(number):
    divisors = []
    for i in range(1, number+1):
        if number % i == 0:
            divisors.append(i)
    return divisors

Upvotes: 3

andreis11
andreis11

Reputation: 1141

for example saving them in a list

def return_divisors(number):
      return [x for x in range(1,number+1) if number % x == 0 ]

print(return_divisors(1))
print(return_divisors(2))
print(return_divisors(10))
print(return_divisors(121))

[1]
[1, 2]
[1, 2, 5, 10]
[1, 11, 121]

Upvotes: 2

Related Questions