Skip to content
Advertisement

How to understand the error in my Python program

code for printing factors of a number

I’m trying to code a program that prints the factors of a number, just as shown in the attached image, but the outcome is totally not what I’m expecting. (I just want the code to return factors of the specified number.) What am I doing wrong and what is the correct way of doing it?

Code:

number=42
factor_list=[]
for num in range(1,number+1):
    num=number/num
    if (number%num)==0:
        factor_list.append(num)
print(factor_list)

Output:

[42.0, 21.0, 14.0, 10.5, 7.0, 6.0, 5.25, 3.5, 3.0, 2.625, 2.0, 1.75, 1.5, 1.3125, 1.0]

Advertisement

Answer

As to why your program does not work, let’s see what is going on step by step:

    number=42
    factor_list=[]
    for num in range(1,number+1):      #for num in [1, 2, 3, 4, 5... 42] (Let's take 28 for example)
        num=number/num                 # num = 42 / 28; num = 1.5 now
        if (number%num)==0:            # 42 mod 1.5 == 0.0
            factor_list.append(num)    # so we add 1.5 to the list.
    print(factor_list)

See the problem in logic now?

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement