How to Print in a For Loop in One Line in Python?

Estimated read time 1 min read

To print in a for loop in one line in Python, you can use the end parameter of the print() function to specify the character(s) that should be printed after each item. By default, the end parameter is set to \n, which adds a newline character after each item. To print items on the same line, you can set the end parameter to an empty string, like this:

for i in range(10):
    print(i, end='')

In this example, we use a for loop to iterate over the numbers from 0 to 9, and we print each number on the same line using the end parameter of the print() function.

The output of the above code will be:

0123456789

Note that when you use the end parameter to print items on the same line, you’ll need to manually add any separators or other characters between the items if you want them to appear. For example, if you want to separate the numbers with commas, you can modify the above code like this:

for i in range(10):
    if i < 9:
        print(i, end=', ')
    else:
        print(i)

This will print the numbers separated by commas, with a newline character at the end:

0, 1, 2, 3, 4, 5, 6, 7, 8, 9

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply