The print function
Tags: python, beginners, programming
Published: 2022-03-17 16:15:43

A _statement_ is an instruction that the Python interpreter can execute. A _function_ is a block of code that perform a specific action, and typically contain several statements. There are two types of Functions in Python: **Built-in functions** — pre-defined functions like _print()_, and **User-defined functions** — functions created by programmers or developers.

The [print](https://docs.python.org/3/library/functions.html#print) function was an addition to Python 3 and replaced the print statement of Python 2. ([PEP 3105](https://www.python.org/dev/peps/pep-3105/)). We can print values to the screen (_stdout_) by default or an open file. It is, for example, commonly used in debugging. The function can accept any number of _positional arguments_ and defines four optional _keyword arguments_ that already have default values.

### Syntax
`print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)`

| Parameter | Description |
| --------- | :-----------|
| _object(s)_ | Objects, will be converted to string before printed. |
| _sep='separator'_ | Optional — specify how to separate the objects, if there is more than one. The default is ' '. |
| _end='end'_ | Optional — specify what to print at the end. The default is '\n' character (newline). |
| _file_ | Optional — an object with a write method. The default is sys.stdout. |
| _flush_ | Optional — a Boolean, specifying if the output is flushed (True) or the default buffered (False). |

### Escape sequences
First, let's briefly discuss these special characters since they often appear in string literals with a preceding backslash `\`. They allow the representation of invisible control characters and sometimes the escaping of otherwise illegal characters.

| Code | Description |
| ----- | :----------|
| `\'` | single quote |
| `\"` | double quote |
| `\\` | backslash |
| `\n`, `\r`, `\r\n` | newline or line feed (LF) |
| `\r` | carriage return (CR) |
| `\t` | tab |
| `\b` | backspace |

Note that a newline can be a single control character or a sequence of control characters depending on the operating system (OS).
* Windows & Dos represent an EOL as `\r\n`.
* Unix, Linux and macOS represent an EOL as `\n`.
* Mac OS X represent an EOL as `\r`.

## Printing to terminal
1\. You can print a blank line (`\n`), passing no arguments with empty parentheses.
```Python
print()
```

2\. You can print literals. A _literal_ is a notation for representing a value in source code. There are various value types (int, float, tuple, string, etc.).
```Python
print(17)
print(3.14159)
print((58, 128, 168))
print("Press \"Enter\" to continue.")
```
<a href="http://tpcg.io/EPDM2E" target="_blank">[run code]</a>

3\. You can print variables. A _variable_ is a symbolic name that references or points to the computer memory location used to store a value.
```Python
pi = 3.14159
message = "Press 'Enter' to continue."
print(message)
print(pi)
```
<a href="http://tpcg.io/ORKLTQ" target="_blank">[run code]</a>

4\. You can print expressions directly. An _expression_ is combination of operators and operands that is interpreted to produce some other value.
```Python
print(19 + 23)
print("Python was first released " + str(31) + " years aggo.")
```
<a href="http://tpcg.io/8FLSKW" target="_blank">[run code]</a>

5\. You can print multiple literals, separating them with a comma (`,`).
```Python
series = "Monty Python's Flying Circus"
print("Python was named after the BBC comedy series:", series)
print(29, 31, 37)
```
<a href="http://tpcg.io/LRIAIO" target="_blank">[run code]</a>

6\. You can print values with another separator (see `sep`).
```python
print('Hello', 'World!', sep="")
print("", "C", "Users", "Guido", "Documents", sep="/")
print("name", "email", "phone number", "address", sep="," )
```
<a href="http://tpcg.io/764QBO" target="_blank">[run code]</a>

7\. You can print literals without line breaks or trailing newline character (see `end`). 
```Python
print("Proceed with Format (Y/N)? ", end="")
print("Y")
```
<a href="http://tpcg.io/14UMMK" target="_blank">[run code]</a>

## String formatting
Since Python 3.6, you can format string literals with [f-strings](https://docs.python.org/3/reference/lexical_analysis.html#f-strings) ([PEP 498](https://www.python.org/dev/peps/pep-0498/)). Although this is now the recommended way to format string literals, it is not intended completely replace the [str.format()](https://docs.python.org/3/library/stdtypes.html#str.format) and [printf-style formatting](https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting) mechanisms.

A formatted string literal or _f-string_ is a string literal that is prefixed with `f` or `F`. These strings may contain [replacement fields](https://docs.python.org/3/library/string.html#formatspec), which are expressions delimited by curly braces (`{}`). The [format specification mini-language](https://docs.python.org/3/library/string.html#formatspec) is the same as that used by the _str.format()_ method.

### Syntax
`"{" [field_name] ["!" conversion] [":" format_spec] "}"`

| Arguments | Description |
| --------- | :---------- |
| `field_name` | Specifies the object whose value is to be formatted and inserted. |
| `conversion` | Optional — type coercion, to force a type conversion (prefixed with `!`). |
| `format_spec` | Optional — specification of how the value should be presented (prefixed with `:`). |

#### field_name
`arg_name ("." attribute_name | "[" element_index "]")*`

| Arguments | Description |
| --------- | :---------- |
| `arg_name` | [identifier  digit+] |
| `attribute_name` | identifier |
| `element_index` | digit+  index_string |

#### conversion
`"r" | "s" | "a"`

| Arguments | Description |
| --------- | :---------- |
| `r` | Calls [repr()](https://docs.python.org/3/library/functions.html#repr) on the argument before `format_spec` implement [\_\_format()__](https://docs.python.org/3/reference/datamodel.html?highlight=__format__#object.__format__). |
| `s` | Calls [str()](https://docs.python.org/3/library/stdtypes.html#str) on the argument before `format_spec` implement [\_\_format()__](https://docs.python.org/3/reference/datamodel.html?highlight=__format__#object.__format__). |
| `a` |  Calls [ascii()](https://docs.python.org/3/library/functions.html#ascii) on the argument before `format_spec` implement [\_\_format()__](https://docs.python.org/3/reference/datamodel.html?highlight=__format__#object.__format__). |

#### format_spec
`[[fill]align] [sign] [#] [0] [width] [grouping_option] [.precision] [type]`

| Arguments | Description |
| --------- | :---------- |
| `fill` | \<any character> |
| `align` | `<`  `>`  `=`  `^` |
| `sign` | `+`  `-`  `" "` |
| `width` | digit+ |
| `grouping_option` | `_`  `,` |
| `precision` | digit+ |
| `type` | `b`  `c`  `d`  `e`  `E`  `f`  `F`  `g`  `G`  `n`  `o`  `s`  `x`  `X`  `%` |

8\. You can print expressions in f-strings.
```Python
print(f"{43 * 47}")
```
<a href="http://tpcg.io/8CHFWG" target="_blank">[run code]</a>

9\. You can print variables in f-strings (see `field name`).
```Python
nation = ("Mayan")
logo = [2, (52, 121, 175), (255, 222, 77)]

print(f"The Python logo depicts {logo[0]} colored snakes based on ancient \
{nation} drawings.")
```
<a href="http://tpcg.io/89LC4O" target="_blank">[run code]</a>

10\. You can call methods in f-strings (see `field name`).
```Python
group = "Monty Python"
print(f"Eric Idle is an actor of the comedy group {group.upper()}.")
```
<a href="http://tpcg.io/4295I9" target="_blank">[run code]</a>

11\. You can call functions in f-strings (see `field name`).
```Python
def to_upper(string):
    return string.upper()

group = "Monty Python"  
print(f"Eric Idle is an actor of the comedy group {to_upper(group)}.")
```
<a href="http://tpcg.io/WQ9ZKC" target="_blank">[run code]</a>

12\. You can print objects in f-strings (see `field name`). By default, it will print whatever the _\_\_str\_\__ method returns, or you can use explicit conversion flags (see `conversion`).
```Python
class Color:
    def __init__(self, r = 255, g = 255, b = 255):
        self.r = r
        self.g = g
        self.b = b
        
    def __str__(self):
        return "This is a RGB color object."

    def __repr__(self):
        return f"Color({self.r}, {self.g}, {self.b})"
        
flat_blue = Color(r = 52, g = 121, b = 175)
light_gold = Color(r = 255, g = 222, b = 77)

print(f"{flat_blue}")
print(f"{flat_blue!s}")
print(f"{light_gold!r}")
```
<a href="http://tpcg.io/K6LBN8" target="_blank">[run code]</a>

13\. You can format the alignment and padding of values in f-strings (see `align` and `fill`).
```Python
prime_number = 997
language = "Python"

print(f"{prime_number}")
print(f"{97:>3}")
print(f"{prime_number:0>10}")
print(f"{language:^10}")
print(f"{language:-^10}")
```
<a href="http://tpcg.io/KZW7H2" target="_blank">[run code]</a>

14\. You can format the sign, grouping and rounding of numbers in f-strings (see `sign`, `grouping_option`, and `precision`).
```Python
number = 9576890767
amount = 25169.15683

print(f"{number:,}")
print(f"{amount:=+11,.2f}")
print(f"$ {amount:,.2f}")
print(f"R {amount:,.2f}".replace(',', ' '))
```
<a href="http://tpcg.io/3YS97I" target="_blank">[run code]</a>

15\. You can format values as different types in f-strings (see `type`).

```Python
decimal_number = 29
binary_number = 0b11101
index = 0.2827
big_number = 176846309399143769411680

print(f"{decimal_number:5b}")
print(f"{decimal_number:5o}")
print(f"{decimal_number:5x}")
print(f"{decimal_number:5X}")
print(f"{binary_number:5d}")
print(f"{big_number:e}")
print(f"Python has a PYPL-index of {index:.2%}")
```
<a href="http://tpcg.io/F8485G" target="_blank">[run code]</a>


## Printing to a file
The print function doesn't just send text to the screen but more accurately converts objects to strings and writes them to a stream (file-like object). A stream can be any file on your drive, a network socket, or a location in memory (buffer). In addition to this, the operating system provides three standard streams:

| Stream | File Handle | Desciption |
|:------:|:--------------:|:----------:|
| stdin (standard input) | 0 | keyboard input |
| stdout (standard output) | 1 | screen output |
| stderr (standard error) | 2 | screen output |

As mentioned earlier, the print function use stdout by default. However, using a redirection operator (`>`), we can instruct the operating system to use a file stream instead. The _redirection operator_ can either redirect input to a shell command or output from a shell command. To redirect _stderr_, you need to use a _file handle_. File handles are constant numbers associated with the standard streams. These handles allow you to redirect one or more streams at a time.

| Syntax | Descrption |
|:------:|:----------:|
| `program > file` | Redirect _stdout_ to a file. |
| `program 2> file` | Redirect _stderr_ to a file. |
| `program > file 2> file` | Redirect _stdout_ and _stderr_ to separate files. |
| `program >> file`| Append _stdout_ to a file. |
| `program < file` | Type a text file and pass the text to program. |

For example, you might execute `systeminfo.exe` to save the information provided by the systeminfo command to a file.
```Powershell
PS systeminfo > system_info.txt
```

16\. You can use stream redirection for various command-line programs including your own Python scripts.
```Python
# message.py
print("This message will be written to stdout")
```
```Powershell
PS python message.py > message.txt
```

17\. You can use stream redirection in Python. This is done by first obtaining a reference to the standard output using the _stdout_ [file object](https://docs.python.org/3/glossary.html#term-file-object) of the [sys](https://docs.python.org/3/library/sys.html?highlight=sys%20module#module-sys) module. Its a good practice to store the original value of the standard output in a variable before changing it. This way you can reset it back to its original value afterwards. The [with](https://docs.python.org/3/reference/compound_stmts.html#with) statement creates a runtime context that allows you to run a group of statements under the control of a [context manager](https://docs.python.org/3/reference/datamodel.html#context-managers). The [open](https://docs.python.org/3/library/functions.html#open) function tries to open a file in writing mode and if successful returns a _file object_ also called a handle. The following modes are commonly used with the print function:

| Mode | Description |
|:---------:|:-----------:|
| `'r'` | Open for reading (default). |
| `'w'` | Open for writing, truncating the file first. |
| `'x'` | Open for exclusive creation, fails if the file already exists. |
| `'a'` | Open for writing, appending to the end of file if it exists. |
| `'+'` | Open for updating (reading and writing). |


```Python
import sys


default_stdout = sys.stdout # save the original value of stdout

print("This message will be written to stdout.")

with open('message.txt', 'w') as file_object:
    sys.stdout = file_object # redirect stdout to the file
    print("This message will be written to file.")
    sys.stdout = default_stdout # reset stdout to its original value

print("This message will be written to stdout.")
```

18\. You can print to a file directly without using stream redirection (see `file`).
```Python
import sys


print("This message will be written to stdout.")

with open('message.txt', 'w') as file_object:
    print("This message will be written to file.", file=file_object)
```

19\. You can disable buffering of the standard output. The operating system buffers expensive I/O operations to enhance performance, but sometimes buffering can have undesired effects. There are three kinds of streams concerning buffering — unbuffered, line-buffered, and block-buffered. A _line-buffered_ stream waits until there is a EOL in the buffer, whereas a _block-buffered_ stream waits for the buffer to fill up. The standard output is both line-buffered and block-buffered, depending on which event comes first. (see `flush`)
 
```Python
from time import sleep


for number in reversed(range(10 + 1)):
    print(number, end=" ", flush=True)
    sleep(1)
print("Launch!")
```

20\. To round off our look at the print function, here is a real-world example of a text-based progress bar that can be used for command line programs. 
```Python
from time import sleep


width = 10

for progress in range (101):
    fill = width * progress // 100
    track = width - fill
    value = f"{progress / 100:.0%}"
    print("\r[", "#" * fill, " " * track, "]", value, sep="", end="", flush=True)
    sleep(0.1)
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iost6mqldf1sora89wa8.gif)