In Python 3 and higher, print is a function rather than a keyword.
You can also pass a number of parameters to print:
Another way to print multiple parameters is by using a +
What you should be careful about when using + to print multiple parameters, though, is that the type of the parameters should be the same. Trying to print the above example without the cast to string first would result in an error, because it would try to add the number 1 to the string "bar" and add that to the number 3.14.
This is because the content of print will be evaluated first:
Otherwise, using a + can be very helpful for a user to read output of variables
In the example below the output is very easy to read!
The script below demonstrates this
You can prevent the print function from automatically printing a newline by using the end parameter:
If you want to write to a file, you can pass it as the parameter file:
this goes to the file!
You can do more than just print text. print also has several parameters to help you.
Argument sep: place a string between arguments.
Do you need to print a list of words separated by a comma or some other string?
Argument end: use something other than a newline at the end
Without the end argument, all print() functions write a line and then go to the beginning of the next line. You can change it to do nothing (use an empty string of ''), or double spacing between paragraphs by using two newlines.
Argument file: send output to someplace other than sys.stdout.
Now you can send your text to either stdout, a file, or StringIO and not care which you are given. If it quacks like a file, it works like a file.
There is a fourth parameter flush which will forcibly flush the stream.
This modified text is an extract of the original Stack Overflow Documentation created by following contributors and released under CC BY-SA 3.0