How to print different output in same line ?

In this tutorial, I am going to talk about “How to print different output in the same line in Python ?” (with different print statements).

How to print different output without newline in Python

All of you need this sometime during competitive programming when you have to print output in one line for different cases as shown below.

Let you have to print range of value in a loop, as a result we will get the output as
shown below the code:
def foo(x):
    for i in range(1,x):
        print(i)
    
foo(5)

Output:
1
2
3
4

Now consider if we want our output all in the same line as:- 1 2 3 4. Then want we have to do? Don’t worry read further you will get it.

However, the solution to this problem is dependent on the version of python used. Generally, we used Python version 3 and above. But we also consider this problem with respect to Python 2 also.

Learn How to escape from \n newline character in Python

Firstly we consider Python3 in our account:

In python3 we can use end statement within the print statement. For example, we have two print var1 and var2 in the same line then use the following line as written below:-

print(var1,end="")
print(var2)

Code for printing a range of number in one line( only for Python version 3):-

def fun1():
    n=int(input("Enter upper range: "))
    for i in range(n):
        print(i,end="")
    return


fun1()
Input:
Enter upper range: 10
Output:
0 1 2 3 4 5 6 7 8 9

Now for python2:

For Python version 2 we have to use ‘,’ along with the print statement. So we have to write like this print(var1), print(var2).

for example

Code for printing a range of number in one line( only for Python version 2):-

def fun2(n):
    for i in range(n):
        print(i,end="")
    return

fun1(10)
Enter upper range: 10
Output:
0 1 2 3 4 5 6 7 8 9

In short, firstly we can use end after the variable within the print statement in Python3. Similarly in Python2, we have to use comma(,) in addition to the print statement so we will get our output in one line(without newline).

Read also Find the memory address of a variable in Python

Leave a Reply

Your email address will not be published. Required fields are marked *