Print() in Python. Syntax, errors, end and sep arguments

Print() – probably the very first command that a beginner encounters when learning Python from scratch. Almost everyone starts with a simple greeting on the screen and moves on to further study of the syntax, functions and methods of the language, without thinking about additional features. print (). However, in Python 3 this command provides access to the basic data output function with its inherent parameters and capabilities. Knowing these features will allow you to optimize the output of data for each specific case.

Feature Benefits print() in Python 3

In the third version of Python print() included in the basic set of functions. When performing a check type(print) information is displayed: classbuiltin_function_or_method. Word builtin indicates that the function being tested is inline.

Never mindhon 3 output objects (objects) are placed in brackets after the word print. On the example of the output of a traditional greeting, it would look like this:

For Python 3: print(‘Hello, World!’).

In Python 2, the statement is applied without parentheses: printHello, World! ‘

The result in both versions will be the same: Hello, World!

If in the second version of Python the values ​​after print put in brackets, then a tuple will be displayed – a data type that is an immutable list:

print(1, ‘first’, 2, ‘second’)

(1, ‘ first’, 2, ‘ second ‘)

When trying to remove the brackets after print in the third version of Python, the program will give a syntax error.

print("Hello, World!")
File "", line 1      print "Hello, World!"                          ^  SyntaxError: Missing parentheses in call to 'print'. Did you mean print("Hello, World!")?

 Peculiarities of print() syntax in Python 3

Function syntax print () includes the actual object or objects (objects), which can also be called values ​​(values) or elements (items), and a few options. How objects are rendered is determined by four named arguments: the element separator (September), a string printed after all objects (end), the file where the data is output (fillet), and a parameter responsible for output buffering (flush).

print(value, ..., sep='', end='n', file=sys.stdout, flush=False)

A function call is possible without specifying parameter values ​​and even without any objects: print (). In this case, the default parameters are used, and if there are no elements, an undisplayed empty string character will be displayed – in fact, the value of the parameter endn. Such a call, for example, can be used for vertical indentation between pins.

All non-keyword arguments (objects) are written to the data stream, converted to strings separated by September and completed end. Parameter Arguments September и end also have a string type, they may not be specified when using the default values.

Parameter September

Values ​​of all parameters print are described as keyword arguments September, end, fillet, flush. If the parameter September is not specified, then its default value is applied: September= ”, and output objects are separated by spaces. Example:

print(1, 2, 3)

1 2 3

As an argument September you can specify another value, for example:

  • separator missing sep=»;
  • new line output sep =not’;
  • or any line:

print(1, 2, 3, sep=’separator word’)

1 word-separator 2 word-separator 3

Parameter end

By default end=’n’, and the output of objects ends with a newline. Replacing the default value with another argument, for example, end= “, will change the format of the output data:

print(‘one_’, end=»)

print(‘two_’, end=»)

print(‘three’)

one_two_three

Parameter fillet

Functional print () supports output redirection via parameter fillet, which by default refers to sys.stdout – standard output. The value can be changed to sys.stdin or sys.stderr. file object stdin applied to the input, and stderr to send interpreter hints and error messages. Using the parameter fillet you can set the output to a file. These can be .csv or .txt files. Possible way to write a string to a file:

fileitem = open(‘printfile.txt’,’a’)

def test(objects):

for element in objects:

print(element, file=fileitem)

fileitem.close()

test([10,9,8,7,6,5,4,3,2,1])

At the output, the elements of the list will be written to printfile.txt one per line.

Parameter flush

This parameter has to do with data stream buffering and since it is a boolean it can take two values ​​− True и False. By default, the option is disabled: flush=False. This means that saving data from the internal buffer to a file will only occur after the file is closed or after a direct call to flush (). To save after each call print () the parameter needs to be assigned a value True:

file_flush = open(r’file_flush.txt’, ‘a’)

print(«Recordlinesвfile«, file=file_flush, flush=True)

print(«Recordsecondlinesвfile«, file=file_flush, flush=True)

file_flush.close()

Another example of using the parameter flush using the time module:

Print() in Python. Syntax, errors, end and sep arguments

In this case, the argument True parameter flush will allow the numbers to be displayed one at a time in three seconds, while by default all numbers would be displayed on the screen after 15 seconds. To visually see the effect of the parameter flush, it’s better to run the script in the console. The fact is that when using some web shells, in particular, Jupyter Notebook, the program is implemented differently (without taking into account the parameter flush).

Printing Variable Values ​​with print()

When displaying a string containing the value assigned to a variable, it is enough to specify the desired identifier (variable name) separated by a comma. The type of the variable should not be specified, because print converts data of any type to strings. Here is an example:

a = 0

b = ‘Python from scratch’

print(a,’– number, а‘,b,’– line.’)

0 is a number and Python from scratch is a string.

Another tool for passing variable values ​​to the output is the method format. Print at the same time, it acts as a template in which instead of variable names in curly braces, indexes of positional arguments are indicated:

a = 0

b = ‘Python from scratch’

print(‘{0} is a number and {1} is a string.’.format(a,b))

0 is a number and Python from scratch is a string.

Instead of format the % symbol can be used, which works on the same principle of placeholders (in the previous example, curly brackets acted as placeholders). In this case, the index numbers are replaced by the data type returned by the function:

  • placeholder %d is used for numeric data;
  • the placeholder %s is for strings.

a = 0

b = ‘Python from scratch’

print(‘%d is a number and %s – string.’%(a,b))

0 is a number and Python from scratch is a string.

If instead of a placeholder for integers %d specify %sfunction print will convert the number to a string and the code will work correctly. But when replacing %s on %d an error message will be displayed because the reverse conversion is not performed.

Print() in Python. Syntax, errors, end and sep arguments

Conclusion

Using the function print various data output options can be implemented. In addition to the methods described in this article, there are other ways to use this tool that will become available as you delve deeper into the world of Python programming.

Leave a Reply