Print 2 20 python результат

A Complete Guide to the Python print() Function

There’s a reasonable chance one of your first encounters with Python included print() , possibly in the form of a “Hello, World!” program. The Python print() function is a basic one you can understand and start using very quickly.

But there’s more to it than meets the eye. In this article, we explore this function in detail by explaining how all the arguments work and showing you some examples.

A good reference for how the Python print() function works is in the official documentation. The function accepts several arguments as shown below with their default values:

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

We have touched on the print() function in another article. In the sections below, we’ll go through the arguments one by one and show you everything you need to know to use this function to its full potential. For those of you who are new to Python, take a look at this mini track, which includes interactive coding challenges to accelerate your learning.

*objects

The thing to be printed is represented by the first argument *objects and can be basically anything. It is commonly a string but may be an integer, a float, a variable, a list, or a dictionary, among others. The print() function can also take more than one object.

Читайте также:  Все типы данных языка python

Since it’s common to print strings, it’s worth mentioning that strings may be defined with either single quotes (‘string’) or double quotes («string»). Your personal preference and the use case determine which to use. To demonstrate this, consider the following two examples:

>>> string = 'She asked "How do you print quotes?"' >>> string = "It's about time to program something"

If you’re interested in learning more about working with strings, check out this course. We also have an article where we show you how to index and slice strings.

The most basic use of the Python print() function is for simply printing a string:

Unspecified keywords take on their default values, which are listed above in the introduction.

Normal string operations may be used within the function. As an example, you can multiply a string by an integer as shown here:

>>> print("print this twice " * 2)

At this point, it’s important to touch on string formatting. The old-school way is with %-formatting; however, this isn’t recommended because it gets a little cumbersome with longer strings.

The better way is to use str.format() , where the replacement fields are indicated with curly braces. Let’s define some variables and print them in a string:

>>> name = "Mary" >>> age = 20 >>> print("<> is <> years old".format(name, age)) Mary is 20 years old

For more examples of string formatting, the official documentation is a good reference. You can also use this method to print tabular data – we have written a separate article on the topic.

Another formatting method is known as f-string formatting. It’s similar to the above example, but it’s a little more compact. Using the same variables from the above, we can write:

>>> print(f" is years old") Mary is 20 years old

If you want to print an iterable object like a list or an array, using a starred expression helps unpack the iterable and print it nicely:

Try printing the same list without the star and see what you get. Also, try printing the sequence given by the built-in function range() with and without the star. We’ll see some more examples with starred expressions in the next section.

sep

The second argument of the Python print() function defines the separator. If more than one object is given as the first argument, then sep defines what delimiter to place between them. Building on the previous example, we define the separator to be the newline character:

>>> print(*[1, 2, 3, 4], sep="\n") 1 2 3 4

Another use case for this argument is for printing some results nicely. We can define a variable and print its value in a human-readable sentence like this:

>>> result = 10 >>> print("Result of experiment ", result, sep=" is ") Result of experiment is 10

Here, the string «Result of experiment» and the variable result both together are the *objects argument, and the value of sep is printed between them.

end

The end keyword allows you to define something to be printed automatically at the end of the output. It defaults to the newline character («\n»).

None of the arguments of the Python print() function are required, strictly speaking. If no arguments are given, the end keyword is printed, which is the newline character by default. It’s pretty straightforward, but for the sake of completeness, let’s build on the previous example by adding an exclamation point at the end:

>>> print("Result of experiment", result, sep=" is ", end="!") Result of experiment is 10!

file

Not specifying this keyword writes to the terminal in Python by default. The documentation linked above says the default value is sys.stdout , which means “write to standard output” in Python. This is a built-in file object that displays anything written to it (with the .write() method) to the console. If you want to write to a file in Python, specify your own file object with the file keyword.

In anticipation of the final example, let’s define the following string, and save it to the file “flush_demo.py” (don’t worry – this’ll all make sense soon):

>>> open_file = open('flush_demo.py', 'w') >>> string = "import time\nfor num in range(10, 0, -1):\n\tprint(str(num)+' ', end='', flush=True)\n\ttime.sleep(1)\nprint('\\nCountdown finished!')" >>> print(string, file=open_file) >>> open_file.close()

Now, go to your current working directory, and you see the new file we have created. The string is in fact a program, which we’ll use shortly.

It’s important to note you need to define the file object in write mode then close it at the end. If you want more details about writing to file in Python, we have an article covering that.

flush

The flush keyword is a recent addition to the print() function. It accepts a Boolean, either True or False .

Normally, the output to a file or the console is buffered. The buffer is «flushed» (or printed) only when it is full or when a newline is reached. Setting this keyword to True forcibly flushes the buffer before it is full or before a newline character is encountered.

To see this in action, we need to use the file we just created in the previous example. To run this script, open the terminal, navigate to the correct directory, and run:

You see we have created a countdown clock. With flush=True , the buffer is flushed after every individual number is printed in the loop, then the program sleeps for 1 second. With flush=False , the program sleeps for 10 seconds and the buffer is only flushed at the end of the program, printing the sequence of numbers all at once.

To You, From the Python print() Function

To wrap up this article on the Python print() function, here’s a personalized thank you message. Just copy and paste this into your console:

>>> print(f"Thanks ", end=", and Goodbye!")

Источник

Функции Print Python 3

Функция print в Python выводит заданные объекты на стандартное устройство вывода (экран) или отправляет их текстовым потоком в файл.

Полный синтаксис функции print()

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

Параметры print()

  • objects – объект, который нужно вывести * обозначает, что объектов может быть несколько;
  • sep – разделяет объекты. Значение по умолчанию: ‘ ‘ ;
  • end – ставится после всех объектов;
  • file – ожидается объект с методом write ( string ). Если значение не задано, для вывода объектов используется файл sys.stdout ;
  • flush – если задано значение True , поток принудительно сбрасывается в файл. Значение по умолчанию: False .

Примечание: sep, end, file и flush — это аргументы-ключевые слова. Если хотите воспользоваться аргументом sep , используйте:

print(*objects, sep = 'separator')

Возвращаемое значение

Функция print в Python не возвращает значений; возвращает None .

Пример 1 : Как работает функция print в Python?

a = 5 # Передаётся два объекта print("a highlight" data-hscroll>
Python — это весело. a = 5 a = 5 = b

В примере, приведенном выше функции print Python 3 , во всех трёх выражениях передаётся только параметр objects , поэтому:

  • Используется разделитель ' ' — обратите внимание на пробел между двумя объектами в результатах вывода;
  • В качестве параметра end используется '\n' ( символ новой строки ). Обратите внимание, что каждое выражение print выводится в новой строке;
  • file — используется файл sys.stdout . Результат выводится на экран;
  • Значение flush — False . Поток не сбрасывается принудительно.

Пример 2: функция print() с разделителем и параметром end

a = 5 print("a =", a, sep='00000', end='\n\n\n') print("a highlight" data-hscroll>
a =000005 a =05

Мы передали в программу, пример которой приведен выше, параметры sep и end .

Пример 3: функция print() с параметром file

С помощью Python print без перевода строки также можно вывести объекты в файл, указав параметр file :

sourceFile = open('python.txt', 'w') print("Круто же, правда?", file = sourceFile) sourceFile.close()

Код, приведенный выше, пытается открыть файл python.txt в режиме записи. Если файл не существует, программа создаёт файл python.txt и открывает его в режиме записи.

В примере мы передали в параметр file объект sourceFile . Объект-строка ' Круто же, правда? ' записывается в файл python.txt ( после чего можно открыть его текстовым редактором ).

В конце исполнения программы файл закрывается методом close() .

МК Михаил Кузнецов автор-переводчик статьи «

Источник

Оцените статью