Reputation: 57
I'm practicing the basics of Python and I had a exercise of doing a function that asks for the user for a number and the function will return him all the divisors of that number so I done this
def divisor_generator():
integer = raw_input("Enter a number:")
integer = int(integer)
list = []
for divisors in range(integer+1):
if divisors%integer == 0:
list.append(divisors)
print list
and for example the output for the integer 50 was
[50, 0]
I really want to keep it simple and I don't understand what is not good about it, I searched for so many answers but none of them was on my level of understanding. Why is my function not working as expected?
Upvotes: 1
Views: 911
Reputation: 39072
Here is the correct version (I am using python 3.6.1
). You need to switch the position of integer
and divisors
. And you need to start your range from 1
otherwise you get division by zero
error
def divisor_generator():
integer = input("Enter a number:")
integer = int(integer)
list = []
for divisors in range(1, integer+1):
if integer%divisors == 0:
list.append(divisors)
print (list)
By the way, in case you are also interested in a bit concise and different solution to your problem, here is another solution (you don't need it though necessarily):
integer = int(input("Enter a number:"))
divisors = [i for i in range(1, integer+1) if integer%i == 0]
print (divisors)
Upvotes: 1
Reputation: 56
Your modulo is backwards.
Your example is evaluating to i % 50
when you want 50 % i
.
Upvotes: 1
Reputation: 45826
Your division is backwards.
I think you meant:
# I took the s off of "divisors" since it's actually a single number
integer % divisor == 0
Think of it this way, if integer
is 50, and divisor
is 2, with the way you had it, it would be:
2 % 50 == 0
If numerator is less than the denominator, that check will never be true, except for the when the numbers are the same. I always walk myself through this mental check just to make sure I didn't accidentally put the numbers backwards.
And, as mentioned in the comments, don't create variables called list
. list
is a built in function, and shadowing it has the potential to cause errors later.
Upvotes: 2