Print Functions
Universally, programming languages all have some method to output data in the terminal for debugging, logging, or simply for aesthetic reasons.
In Python, this is the print function. Every manual and tutorial, thanks to tradition, will have you say hi to the world. Printing a string is as easy as:
| |
remember that strings are character variables surrounded by '' or "".
Print beyond the strings
Four other types of arguments can be used in the print function.
| |
Notice the comma separation? This is the proper way to end their portion of the line, or else it will fail when run.
*objectsThis is the data you want to print, with*signifying that you can print multiple objects. numbers, variables, strong and wordssep=' 'Represents a separator between objects, defaulting to one character space.end='\n'Sets what to print at the end of an object; the default is a new line character.file=sys.stdoutAllows you to set where the output is sent; the default is the terminal, but you can send it to a log file.flush=FalseIndicates to Python whether or not to output data imedietly or to wait. by default (`false`) python waits. Â
Examples
Printing multiple things at once
Basic multi-printing looks like:
| |
*As you can see, the default of sep=' ' which is one character space is used.
Using the sep, we change what Python puts at the end of the line.
| |
You may have noticed that this is a bit funky, since colors has a , at the end.
This is where string concatenation comes into play. To get rid of the comma, remove the space in the string directly and use a plus sign.
| |
String concatenations combine multiple strings into one; in this example, your merging colors: and blue. Essentially, Python sees it as colors: blue,.
The end parameter: unlocking customization
As mentioned above, the default of end='\n' is to go to the next line (below the last line) like this:
| |
This can be changed easily to function like the previous example and can add more control over the output:
| |
file= connecting to your data
You can use file to directly write your print output down outside of the terminal.
| |
This writes Hello world! into output.txt, creating the output file even if it doesn’t exist.
flush or rather getting to the point
When the flush argument is set to true, it outputs the string instantly.
| |
This code would instantly show you processing.. thanks to flush, wait 2 seconds, then output done!.