Ahmed
Ahmed

Reputation: 1

How to get divisors of any number

I'm trying to print out divisors of an entered number and not getting the desirable results. I think the code I've written is correct but the outcome isn't really what I'm expecting. Please help me point out my mistakes, if any

def divisors():
    a = int(input("Enter a number: "))
    x = list(range(2, a+1))

    for item in x:
        if a % item == 0:
            print(item)
        else:
            break
    divisors()

Upvotes: 0

Views: 71

Answers (1)

Netwave
Netwave

Reputation: 42786

You should not use break, it makes your loop to stop the first time you encounter a non-divisor:

def divisors():
    a = int(input("Enter a number: "))
    x = list(range(2, a+1))

    for item in x:
        if a % item == 0:
            print(item)

Upvotes: 1

Related Questions