Printing with Python
The Python Print Function
Printing is a key concept in all programming languages. You need to be able to print in order to return data to the screen or to output it to a file. Python has a print function, which has a lot of functionality which we will go through here.
One thing to keep in mind is that print works differently in different versions of Python. More on this shortly.
The print function works differently in python 3 than it did in python 2. To print in python 2.x you simply used print followed by the statement. For example:
$ print 100
This would have returned '100' to the screen. However, if you were to run that in Python 3 you would receive an error along the following lines:
$ python3 Python 3.2.3 (default, Apr 10 2013, 05:03:36) [GCC 4.7.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> print 100 File "", line 1
This is because in Python 3 you need to use parentheses with the print function.
This difference is a common reason why python 2 programs don't run successfully in the python 3 interpreter - though as you can see, this particular issue is easily fixed!
The print function has a number of arguments:
print(value1, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
The print function can:
- The print function can print an arbitrary number of values ("1, v2, ..."), which are separated by commas.
- By default a print call is ended by a newline, though it's possible to do a print without a new line.
- The output of the print function is send to the std output stream (sys.stdout) by default.
- It's possible to change the seperator between values by assigning an arbitrary string to the keyword parameter "sep"
Python print() Examples
# printing a string: print('Please wait...') # printing a variable: message = 'Please wait...' print(message) # print with a blank separator print('hello', 'world', sep=' ') hello world
Thanks for reading! Hopefully this has given a little bit of an introduction to the python print function. Look out for some more advanced articles soon!
© 2020 Jen