Python Forum
Listing the factors of a number
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Listing the factors of a number
#1
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.")
Reply
#2
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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
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().
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020