Print all the dividers from a number, unsupported operand type for string and range

Question:

I am trying to exercise my python and do exercices. One exercise is to print all dividers of a number.

I thus tried the following:

a = input("give me a number:")
give me a number:34
x = range(0,200)

for elem in x:
    y= a /x
    if y == 0:
        print(y)

I had the following error: "unsupported operand type(s) for /: ‘str’ and ‘rangeĀ“"

What am I doing wrong?

wWhy is python considering that "a" is a string? Is my understanding correct?

Asked By: Tomas Michel

||

Answers:

Firstly, from the docs, input returns a string, therefore you have to convert it to an integer. Secondly, you’re dividing by x which is a range object, you should instead divide by elem. You should also start your range object from 1 instead of 0 to avoid dividing by 0. There is also no need to go up to 200 you should go to a//2 instead. Finally, your division will never give y=0 I think you meant to use the % operator instead.

I think this is what you’re looking for:

a = int(input("give me a number:"))

for i in range(1, a//2+1):
    if not a%i:
        print(i)

Output (with a=10):

1
2
5
Answered By: Nin17

try this…

a = int(input("give me a number: "))
for elem in range(2,a+1):
  if a%elem == 0:
    print(elem)
Answered By: Abhishek Kumar
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.