Screen IO
Contents
Screen IO#
Input from keyboard and output to screen are important for a program’s interaction with the user. Here we discuss some frequently used features of terminal and Jupyter based screen IO. Graphical user interfaces (GUIs) are possible in Python, too, but won’t be discussed here.
Input#
The input
function does not provide more functionality than we have already seen. It takes one argument, the text to be printed on screen, and returns a string with the user’s input.
Output#
The print
function provides some fine-tuning. We already saw that it takes an arbitrary number of arguments. Each argument which is not a keyword argument will be send to screen. Outputs of multiple arguments are separated by one space. Non-string arguments are converted to strings automatically.
Instead of spaces, different separators can be specified with the keyword argument sep='...'
.
a = 3
b = 2.34
c = 'some_string'
print(a, b, c, sep=' | ')
3 | 2.34 | some_string
Note
Note the difference to print(a, b, c, ' | ')
, which yields 3 2.34 some_string |
.
The print
function automatically adds a line break to the output. If this is not desired we may pass something else as keyword argument end='...'
, an empty string for instance.
print('some text', end='')
print(' and some more text')
some text and some more text
Line breaks may be added wherever appropriate by writing \n
in a string.
print('some text with line break\nin a string')
some text with line break
in a string
Note
The \
character is not printed but interpreted as escape charater
. The character following \
is a command to the output algorithm. Next to \n
we already met \'
and \"
. If you have to print a \
on screen use \\
.
Calling print
without any arguments prints a line break. Thus, print()
and print('')
are equivalent.
Automatic Ouput in Interactive Python#
In JupyterLab and also in the Python interpreter’s interactive mode we do not have to write print(...)
everytime we want to see some result. JupyterLab automatically prints the value of the last line in a code cell. The Python interpreter automatically prints the value of the last command issued. Instead of
print(123 * 456)
56088
we may simply write
123 * 456
56088
While plain Python calls print
on the value to output, JupyterLab calls it’s own function display
. For simple data like numbers and strings display
does the same as print
, but for complex data like tables or images display
produces richer output. Even audio files and videos may be embedded into Jupyter notebooks by calling display
on suitably prepared data (or leaving this to JupyterLab if data is produced in the last line of a cell).