In Python, the print() function is used to display output on the console. It is one of the most commonly used functions in Python for debugging and outputting information.
For example:
print("Hello World!")
# Output: Hello World!In this example, the print() function displays the string "Hello, World!" on the console.
Syntax
print(object(s), sep=separator, end=end, file=file, flush=flush)Let’s break down the parameters of the print() function:
- object(s):
The object(s) to be printed. You can pass any number of objects (strings, integers, lists, etc.), and they will be converted to strings before being printed.
For example:
print("Hello", 42)
# Output: Hello 42- sep='separator':
Specifies how to separate the objects, if there is more than one. The default separator is a space ' '. You can change this to any string. (This is optional)
For example:
print("Hello", "World", sep=", ")
# Output: Hello, World- end='end':
Specifies what to print at the end. By default, it is a newline character (\n), meaning the next output will be printed on a new line. You can change this to any string. (This is optional)
For example:
print("Hello", "World", end="!")
# Output: Hello World!- file:
An object with a write() method (such as a file object). The default is sys.stdout, meaning output will be printed to the console. (This is optional)
For example:
# writing to a file
with open("output.txt", "w") as file:
print("Hello, World!", file=file)- flush:
A Boolean value, specifying if the output is flushed (True) or buffered (False). Default is False. (This is optional)
For example:
print("Hello", flush=True)This will flush the output buffer, meaning that it will be printed to the console immediately.
Now, let’s take a look at the example using sep and end parameters.
print("Hello", "World", sep=", ", end="!\n")
# Output: Hello, World!In this example:
- The
sepparameter places a comma and a space between"Hello"and"World". - The
endparameter changes the default newline to an exclamation mark followed by a newline.
👉 Next tutorial: Python Escape Sequence Characters