-2

I just started python few days ago, and didn't really understand end =' ' in nested loop. Can anybody explain me this

count=0
for i in range(10):
    for j in range(0, i):
        print (count, end='')
    count +=1
    print()
selbie
  • 100,020
  • 15
  • 103
  • 173

4 Answers4

2

'' is the "empty string" (e.g. nothing). The "end" parameter is what gets printed after the preceding set of variables. The default value of "end" is the newline (i.e. subsequent print statements will begin on a new line). By specifying '', the loop above will literally print out

1
22
333
4444
55555
666666
7777777
88888888
999999999

with each inner loop result on a single line. Without the end='' param, it would get printed out as:

1
2
2
3
3
3
...
9
9

The final print() at the end of the inner loop, just prints a new line.

selbie
  • 100,020
  • 15
  • 103
  • 173
0

End is print function keyword argument. The default value of end is \n meaning that after the print statement it will print a new line. If you redefine end, print will output your redefined value after using.

print("123", end="=")
#prints '123='

'' means empty string, so, you wil get output with no delimiters.

Dmitry
  • 2,026
  • 1
  • 18
  • 22
0

The default value of end is \n meaning that after the print statement it will print a new line. So simply stated end is what you want to be printed after the print statement has been executed,

prints an according Count value and stays in the same line. If you left out the end='' each time a newline would be printed

Sachith Wickramaarachchi
  • 5,546
  • 6
  • 39
  • 68
-1

We learn everything by doing, So lets suppose we remove that end="" at the end of the print function. So you code will look like this

    count=0
for i in range(10):
    for j in range(0, i):
        print (count)
    count +=1
    print()

and the output will be as

1
2
2
3
3
3
...

Now this output may or may not be your desired output depending on where you want to use the code you may be wondering why this happens when you have not specified python to add a new line, its due to the fact that print function add new line character at the end of the output by default so if you doesnot want that to happen add end="" for the output line end with a empty string or nothing. likewise use end="/t" for tab end="." to end the print statement with a period and so on.

ProTip use

print()

when ever you want a new line in or out of a loop