pythonpython-3.xlistconditional-statements

Create a program to ask a number and print all divisors


Below is my code:

num= int(input("Please enter number"))
lista= []

for i in range(1,100):
    if num%i ==0:
        lista.append(i)
print(i)

But when I run the same, I get the below output:

Please enter number24
99

Process finished with exit code 0

According to the above logic, my understanding is that the loop will iterate for 99 times because of the range given, and if the remainder is zero for "i", then it should be appended on the list. Not sure where and why my logic is wrong.


Solution

    1. You are printing just i, instead you need to print the complete list at end of loop.
    2. You are iterating in the range of [1, 100) only for the divisors, however, to find all divisors with this naive approach, you would ideally need to iterate over range of [1, num). For example, 1000 is a divisor for 2000, but your approach would miss the case.
    3. Instead of lista, you can use list_divisors as the variable name as it is more readable.

    So your code becomes:

    num = int(input("Please enter number"))
    list_divisors = []
    
    for i in range(1, num):
        if num % i ==0:
            list_divisors.append(i)
    print(list_divisors)