How to improve my program that takes a positive integer as its input and spits out its divisors

Hi all,

I would like to improve my python program that takes a positive integer as its input and spits out its divisors, and the following code will do the work.

n = int(input("Write an positive integer :"))
divisors = []
for i in list(range(1,n+1)):
    if n % i == 0:
        divisors = divisors + [i]
print(divisors)

Here, I would like to know why “range(1,n+1)” instead of “range(1,n)”. I checked “range(1,n)” outputs only {1,2,…,n-1}, so I replaced it with n+1.

Also, I would like to improve my code so that if your input is not a positive integer, then machine will ask you to input a number again.

An ideal result of the code will be like this;

Write a positive integer: 0 ; Here you input 0 which is not a positive integer, so machine will ask again.
Write a positive integer: -58 ; Again, it is not positive.
write a positive integer: 24 ; It is a positive integer, so machine will give you the result.
[1, 2, 3, 4, 6, 8, 12, 24]

Any suggestion would be greatly appreciated.

Thanks.

range(m, n) excludes the upper bound, n and only includes up to n - 1.

Aside

The wording of the question struck me as unusual since in these parts we call it, ‘factoring’.

Your method is the brute force approach that in all likelihood is the best approach for our purposes. Mathematicians will disagree, but I’m cool with that.

divisors += [i]

First we’re sure that our function is outputting the values expected, one hundred per-cent of the time. Then we get to user inputs.

NEVER trust user inputs. This much of a red flag should alert you to the vulnerability user input presents to your code environment. For my purposes, I use simulations. Not interested in user input if I can simulate it myself to proof test my code. Create the data model you need, and feed it into your program.

Oops! Forgot to answer the question. My bad. A truth value conditional loop is one approach, or an infinite loop with a breaking condition is another. The latter would be the way to go. Until inputs are within given expected range, loop repeats. Break condition is when input matches expectation, hence, break.

while input is crap
keep looping over input statement
else break

Secret here is now create a function that will be a permanent, and required item in your toolbox, moving forward.

Even simpler is iterating while true…

while True:
    if input() is not crap: break
1 Like