The print()
function is used to output text to an output stream such as the console, a file, a GUI window, etc.
The syntax for using the print function is as follows:
print(*values, sep=' ', end='\n', file=sys.stdout, flush=False).
*values |
The arbitrary objects to be printed, the objects can be of any valid types such as string, integers, lists, user defined objects, etc. If an object is not a string, it will be converted to its string representation before it is printed. |
sep |
An optional string specifying the value to separate the printed items(if more than one). If not given, it defaults to a space(" " ) |
end |
An optional string specifying the value to be printed at the end after all the values have been printed. It defaults to a new line character("\n" ) |
file |
An object with a write() method where the print values will be written. If not given, it defaults to sys.stdout which is literally the console. |
flush |
A Boolean, specifying if the output is flushed (True ) or buffered (False ). It defaults to False . |
The sep argument
The optional sep
argument specifies the separator that will be inserted between objects when multiple objects are passed to the print function, it defaults to a space.
The end argument
The optional end
argument specifies the characters to be printed after all items have been printed, the default is a new line character, '\n'.
The flush argument
The flush parameter is a Boolean parameter that indicates whether the buffered output should be flushed or not. By default, the output data is buffered meaning that it is written in chunks.
When flush is set to True, the buffered data is immediately written to the output stream. Setting flush to True can also help reduce memory usage if data must be written at regular intervals.
Writing to a custom file
The file
argument is also optional and specifies an output device such as a file, the default is the system's standard output i,.e the console\terminal.
in the above program, the string "Hello, world"
will be printed on the file named my_file.txt.
Writing to a custom objects.
We can make a custom object support being written on by defining the write() method. We then specify the file
argument to be the custom object so that the print()
function will output the values to the object.
The write() method should take the data to be written and apply it to the object.