Reading Time: 2 minutes
Using print() function in Python
Every programmer is familiar with the builtin print() function. It's used to producing output onto the console, whether it's the interpreter in IDLE, or in command prompt. It is useful while tracing a piece of code to check which branch of the code is being executed.
>>> print("Hello there!") Hello there! >>> print(1) 1 >>> print( [1, 2, 3, 4] ) [1, 2, 3, 4]
The print() function has four optional keyword arguments:
- sep: the separator (a string) between different values, if multiple values provided. Default value - single space.
- end: end-of-print string appended after the value(s) have been printed. Default value - new line character i.e. '\n'
- file: stream to which the output is to be dumped to. Can be a file object too. Default value - sys.stdout which refers to console output.
- flush: when set to True, output of each print() statment is written to the specified stream forcibly. This is useful when we are directing output to a stream. When we perform a write operation to a file, the data is not in file, it is only in the program buffer/internal buffer until the file is closed. Setting flush to True, it writes data from the internal buffer to the operating system buffer after each call to print() function. What this means is that if another process is performing a read operation from the same file, it will be able to read the data you just flushed to the file. Default value - False. To know more about buffers & flush operation, I advise you to visit this link.
Expand the following code snippet for examples illustrating these optional keyword arguments.
' '. You can specify a different separator.
# 'sep' >>> a = 'Hello' >>> b = 'there!' >>> print(a, b) Hello there! >>> print(a, b, sep = ' ') Hello there! >>> print(a, b, sep = '*') Hello*there! # 'end' >>> print("Hi "); print("there!") Hi there! >>> print("Hi ", end = '\n'); print("there!") Hi there! >>> print("Hi ", end = ''); print("there!") Hi there! >>> # 'file' >>> fH = open('outputFile.txt', 'w') >>> print("Hello there!", file = fH) >>> fH.close() # contents of outputFile.txt: Hello there! # 'flush' >>> fH = open('outputFile.txt', 'w') >>> print("Hello there!", file = fH) # contents of outputFile.txt: NO CONTENTS >>> fH.close() # contents of outputFile.txt: Hello there! >>> fH = open('outputFile.txt', 'w') >>> print("Hello there!", file = fH, flush = True) # contents of outputFile.txt: Hello there!