21. Output with Print
By Bernd Klein. Last modified: 08 Nov 2023.
Introduction
In principle, every computer program has to communicate with the environment or the "outside world". For this purpose nearly every programming language has special I/O functionalities, i.e. input/output. This ensures the interaction or communication with the other components e.g. a database or a user. Input often comes - as we have already seen - from the keyboard and the corresponding Python command, or better, the corresponding Python function for reading from the standard input is input().
We have also seen in previous examples of our tutorial that we can write into the standard output by using print. In this chapter of our tutorial we want to have a detailed look at the print function. As some might have skipped over it, we want to emphasize that we wrote "print function" and not "print statement". You can easily find out how crucial this difference is, if you take an arbitrary Python program written in version 2.x and if you try to let it run with a Python3 interpreter. In most cases you will receive error messages. One of the most frequently occurring errors will be related to print, because most programs contain prints. We can generate the most typical error in the interactive Python shell:
print 42
File "", line 1
print 42
OUTPUT:
File "<ipython-input-1-5d54469f7ddf>", line 1 print 42 ^ SyntaxError: Missing parentheses in call to 'print'. Did you mean print(42)?
This is a familiar error message for most of us: We have forgotten the parentheses. "print" is - as we have already mentioned - a function in version 3.x. Like any other function print expects its arguments to be surrounded by parentheses. So parentheses are an easy remedy for this error:
print(42)
OUTPUT:
42
But this is not the only difference to the old print. The output behaviour has changed as well.
