0

I have this code where given an integer n, I want to print out all integers in the interval [1→n] that divide n, separated with spaces. I wrote this code:

n = int(input('Enter number:'))

for i in range(1, n+1):
    if (n%i==0):
        print (i)

I get this as the answer:

Enter number:8 

1

2

4

8

But I want my answer next to each other, separated using spaces (so: 1 2 4 8). How do I do this?

Benyamin Jafari
  • 27,880
  • 26
  • 135
  • 150

3 Answers3

3

Instead of:

print(i)

You should put:

print(i, end=" ")

This will change the end of line string from "\n" to " ". This will give you the desired output.


Another method would be to build a list of results and print it out at the end:

n = int(input('Enter number:'))
final_results = list()

for i in range(1, n+1):
    if (n%i==0):
        final_results.append(str(i))

print(" ".join(final_results))
ritlew
  • 1,622
  • 11
  • 13
0
print(i), 

(with the comma) Should do the job.

Benyamin Jafari
  • 27,880
  • 26
  • 135
  • 150
0

I would suggest accumulating all intermediate results, and only when the computation is done, print it.

n = int(input('Enter number:'))
dividers = []
for i in range(1, n+1):
    if (n%i==0):
        dividers.append(i)
print(dividers)

If you want to print them with nice comma separation, you can do something like this:

print(', '.join(str(divider) for divider in dividers))

Benefits

First, this reduces the number of calls to wherever you are printing to (by default, this is stdout)

Second, the code becomes more readable and easier to adjust and expand later-on (for example, if you later decide that you want to pass those dividers onto another function)

Edit: adjusted the join operation per ritlew's comment

Ori
  • 1,680
  • 21
  • 24