Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the job of the "end" argument in the print function?

Tags:

python

for example in this code below the with the end the integers stay on the same line but without the it does not.

num = 5
for i in range(1, num +1):
  for j in range(num, i-1, -1):
  print(j, end="")
print()
like image 738
terriyon Avatar asked Feb 08 '23 07:02

terriyon


2 Answers

The end statement for printing in Python allows the programmer to define a custom ending character for each print call other than the default \n

For instance, if you have a function that is to print all values within a list on the same line, you do:

def value(l):
    for items in l:
        print(l, end=' ')

So if the list argued to this function contains the values [1, 2, 3, 4], it will print them in this manner: 1 2 3 4. If this new ending character parameter was not defined they would be printed:

1
2
3
4

The same principle applies for ANY value you provide for the end option.

like image 175
m_callens Avatar answered Feb 25 '23 13:02

m_callens


In Python 3, the default ist end='\n' for the print function which is a newline after the string is printed.

To suppress this newline, one can set end='' so that the next print starts in the same line.

This is unrelated to the for loop.

like image 28
bastelflp Avatar answered Feb 25 '23 13:02

bastelflp