The end
parameter is used to specify what should be printed at the end of the print
function’s output instead of the default newline character ('\n'
). You can use this parameter to control the ending character or string that separates multiple print
statements.
Here’s an example of how you can use the end
parameter:
print("Hello", end=", ")
print("world!", end=" ")
print("Python", end=" rocks!")
Output: Hello, world! Python rocks!
n this example, we’ve used different values for the end
parameter to customize the separation between the printed statements.
Remember that by default, the end
parameter is set to '\n'
, so each print
statement ends with a newline character, which moves the cursor to the next line. If you want to prevent this behavior and keep the output on the same line, you can set end=''
.
Here’s an example demonstrating the default behavior:
print("Line 1")
print("Line 2")
Output:
Line 1
Line 2
And here’s an example to keep the output on the same line using the end
parameter:
print("Line 1", end='')
print("Line 2")
Output: Line 1Line 2
This way, you have more control over the formatting of your output when using the print()
function in Python.
Python print end example
Here are a few more examples of how you can use the end
parameter with the print()
function in Python:
Printing numbers on the same line with a space separator:
for i in range(1, 6):
print(i, end=' ')
Creating a progress bar effect:
import time
for i in range(11):
print(f"Progress: {i * 10}%", end='\r')
time.sleep(0.5)
This will print a progress bar that updates on the same line as the percentage increases.
Printing a pattern on a single line:
pattern = "*"
for _ in range(5):
print(pattern, end='')
pattern += "*"
Displaying items from a list on the same line:
fruits = ["apple", "banana", "cherry", "date"]
for fruit in fruits:
print(fruit, end=' | ')
Printing a countdown:
import time
for i in range(5, 0, -1):
print(i, end=' ', flush=True)
time.sleep(1)
print("Blastoff!")
Output:
In these examples, the end
parameter is used to control the behavior of the print()
function and customize the output format. You can adjust the value of the end
parameter to achieve the desired output style.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.