educative.io

Educative

Multiple print statements in the same line?

I don’t understand this section of the lesson:

“By default, each print statement prints text in a new line. If we want multiple print statements to print in the same line, we can use the following code:”

1 print(“Hello”, end="")
2 print(“World”)
3
4 print(“Hello”, end=" ")
5 print(“World”)
6

Each number (1-6) represents a line, yes? What is the purpose of lines 1-2 above when you can just type print(“HelloWorld”)? Or print(“Hello World”) for lines 4-5? What exactly does ‘end=’ do?

1 Like

Yes, each line (1-6) represents a line. end=" " is used for space after the string instead of a newline.

print(“Hello World”)

and

print(“Hello”,end=" ")
print(“World”)

Both prints the same thing Hello World. For printing HelloWorld you can use both:

print(“HelloWorld”)

and

print(“Hello”,end="")
print(“World”)

Hey Jason, Yes you can do all but there is a proper use of end there. The print statement in Python3 has some optional parameters e.g.

  • end
  • sep

Optional parameters always has the default values, same in that case end parameter has a value of new line, so every time we call

print("Hello World")

it will move the cursor to the new line, because default value for end is ‘newLine’.
But if we use it as

print("Hello",end=" ")

The default value is overwritten and now instead of going to a new line, it add a space and place the cursor there.
Same for the sep parameter, the default value for sep is space but if we use this

print(12, 24, -2, sep=':')

it will print this

12:24:-2

Because the default value has been replaced and instead of using a space, it is using the that colon character which we have provided.

I hope things are clear now, if you still have any ambiguity, you can ask.

2 Likes