-3

Code - 1

for i in range(1,5):
  for x in range(1,5):
    print ("A",end="")
  print("*")

Output

AAAA*
AAAA*
AAAA*
AAAA*

Code - 2

 for i in range(1,5):
   for x in range(1,5):
     print("A",end="")

Output

AAAAAAAAAAAAAAAA

My question is why does in Code -2,A after getting printed for 4 time's, doesn't move to the new line automatically as like in Code-1?

My expectation was that A after printing for 4 times will move to the next line as like in Code 1

user87284
  • 1
  • 1
  • 3
    Because `end=""` explicitly does *not* print a newline, and the newline comes from `print("*")`…!? There's no magic newline coming from the end of the loop. – deceze Jul 16 '23 at 09:27
  • This has nothing to do with loops. It is all about your `print` statements. – Gino Mempin Jul 16 '23 at 10:11

2 Answers2

0

print with end="" does not print a newline. In code 1, print("*") prints the newline in the outer loop.

To have the same effect in code 2, you need to add an empty print to the outer loop:

for i in range(1,5):
   for x in range(1,5):
     print("A",end="")
   print()
Fatih Develi
  • 95
  • 2
  • 7
0

When you don't assign the end paramater in print(), by default it will be '\n' which is the newline character. If you assign end to an empty string it will not print a newline. That's why print("A",end="") doesn't create new lines. In your Code - 1 within your outer loop, you have print("*") which will start on the same line as the A's in your inner loop, but then it will end with a newline character. Writing print("*") is the same as writing print("*",end="\n").

It has nothing to do with how your loops are set up. Code - 2 does not have any newline characters in either loop, so it will never move to a new line.

I recommending playing around with the end parameter some more and seeing what happens when you change it to different strings. Look into documentation on print() or its end parameter for more information.

patjcolon
  • 1
  • 3