Python Forum
Listing the factors of a number - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: General (https://python-forum.io/forum-1.html)
+--- Forum: Code sharing (https://python-forum.io/forum-5.html)
+--- Thread: Listing the factors of a number (/thread-11715.html)



Listing the factors of a number - TitaniumGene - Jul-22-2018

I wrote this code after taking a few basic Python courses. I welcome feedback on how to improve it.

print("This program will list the factors of a number for you.")

#Need a function to find factors of an integer.
def find_factors(integer):
    factors = []

    #It has to be 1 more than the integer to include the actual integer.
    for i in range(1, integer + 1):
        if integer % i == 0:
            factors.append(i)
    return print("The factors of",integer,"are",factors,".")


#Check the input for valid.
while True:
    product = input("Enter a positive integer: ")
    if product.isalpha() == True:
        print("That is not an integer.")
    elif product.isdigit() == True:
        print("That is a valid response.")
        product = int(product) #Converts the product string into an integer.
        find_factors(product)
        break
    else:
        print("Try again.")



RE: Listing the factors of a number - ichabod801 - Jul-23-2018

You only need to check up to the square root of the number. But to do that, you need to append the factor you found (i (which is a bad variable name, use more descriptive names like 'factor' or 'possible')), and the number divided by the factor.

For example, checking factors of 16, you get 2 as a factor. You add that to the factors list, as well as 16 / 2 = 8.


RE: Listing the factors of a number - WolfWayfarer - Jul-23-2018

Being a beginner myself I'll give you the little help I can think of, you might want to document your functions, instead of using a comment line on top with:
#my comment
you could try the docstring which would give you something like this:

def find_factors(integer):
    """ Need a function to find factors of an integer.
    """
    factors = []
Your docstring will show up when people use help().