1
for i in range(1,int(input())+1):
    print(((10**i-1)//9)**2)

An extra blank line is being printed in the for loop.

I've tried taking help from different websites.
Current output is:

1
121
12321
1234321
123454321
--here the extra line is being printed--

The expected output would be:

1
121
12321
1234321
123454321
liakoyras
  • 1,101
  • 12
  • 27
Ishita
  • 15
  • 3
  • Possible duplicate of [How to print without newline or space?](https://stackoverflow.com/questions/493386/how-to-print-without-newline-or-space) – liakoyras Sep 07 '19 at 15:35
  • I can't reproduce the problem. Please make a [mre]. Probably the problem is in another part of the code. – wjandrea Sep 07 '19 at 15:53

2 Answers2

2

Thats how print works. It prints the string representation of its argument(s) followed by end which is a newline by default. Thats why your output is not all on the same line to begin with.

You can manually specify end like this:

for i in range(1,int(input())+1):
    print(((10**i-1)//9)**2, end='')

but then everything will be on the same line. The workaround is to print the newlines separately.

for i in range(1,int(input())+1):
    print()
    print(((10**i-1)//9)**2, end='')

Here the newline is being printed before the string which prevents there being a trailing one. However there will be a leading newline instead. But that can be taken care of by not calling print() on the first iteration of the loop.

for i in range(1,int(input())+1):
    if i != 0:
        print()
    print(((10**i-1)//9)**2, end='')
  • 2
    Since you are testing for equality here and not identity, you should use `!=` instead of `is not`. – idjaw Sep 07 '19 at 15:32
1

Since the op wants newlines between the integers but not at the end, a concise way to express this is to build the target string using join and then print that without a newline.

n = int(input()) + 1
text = '\n'.join([ str(((10**i-1)//9)**2) for i in range(1,n) ])
print(text, end='')

The trouble with this approach is that you are constructing the whole text before printing. But this should be suitable for small lists.

an even shorter alternative is to use the arg sep as well as end.

print(*[ str(((10**i-1)//9)**2) for i in range(1,n) ], sep='\n', end='')
Haleemur Ali
  • 26,718
  • 5
  • 61
  • 85