Python print with arguments

Python print() Function Parameters Explained (A Complete Guide)

You may be familiar with the print() function that takes only one parameter, that is, the item that you want to print. In reality, the print() function takes additional 4 parameters.

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

The print function parameters are:

  1. *objects – an object/objects to be printed.
  2. sep – the separator between multiple printed objects.
  3. end – the character/string printed at the end after the object.
  4. file – specifies the file where the output goes. By default this is the console.
  5. flush – flushes the stream/file forcibly if set True

In the above, only the first argument *objects is mandatory. The rest of the arguments are not.

In this guide, you will learn what each of the print parameters means and when to use them.

Python print() Function Parameters

You have probably used Python’s print() function this way:

Or even like this with an arbitrary number of arguments:

n1 = 1 n2 = 2 n3 = 3 print(n1, n2 ,n3)

But according to the official documentation, the print() function follows this syntax:

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

There seem to be 5 arguments that the print() function accepts. This may cause some confusion, so let me show you how what each of these arguments does, and when they are useful.

Читайте также:  vertical-align

1. *objects

The *objects parameter represents an arbitrary number of arguments. This makes it possible to call the print() function any number of inputs. This is why there is an asterisk * in front of the argument name. If there was no asterisk, you could only print one element at a time.

print("Hello") # Print a single value print(1, 2, 3) # Print multiple values

2. sep

The separator parameter sep acts as a separator if the print() function is called with multiple values. By default, this is set an empty string, ‘ ‘.

If you want to change it, you need to specify the separator by providing the argument as a keyword argument in the print() function call. In other words, you have to add sep=’something’ into the print() function call.

For instance, let’s separate each element by two new lines:

The separator is useful if you want to customize the way multiple values are printed into the console.

3. end

The end parameter specifies the string/character to which the printed value ends. By default, it is a line break.

As you may know, calling multiple print() functions adds a new line automatically. This is because, by default, each print() function call adds a newline character ‘\n’ to the end of the row.

If you do not want each print to cause a new line, you can change the value of the end parameter in the print() function call.

For instance, let’s use a blank space instead of a new line:

print("Hello", end=" ") print("world")

Tweaking the end parameter in the print() function can be useful if you want to change the way consecutive prints appear in the console.

4. file

The file parameter determines where the print() function sends the output. By default, it sends the output into the console.

By default, the print() function displays the output in the console. But this is just one stream where the output can be displayed. You can for example print the results into a separate text file. To do this, specify the file parameter.

For example, let’s print a string to a new file called example.py:

with open("example.txt", "w") as text_file: print("Hello, file!", file=text_file)

As a result, you will not see a print in the console. Instead, the string is printed to the file called example.txt in the same folder with your project.

5. flush

Flushing in Python means flushing the output stream buffer. If you want to flush the output stream when printing, you need to set flush argument True in the print() function call.

But why would you ever do something like that?

In Python, the input/output functions, such as print(), are expensive to call. To improve the performance, your operating system stores input/output data into a buffer before sending it to the stream, such as into the console.

When you print in Python, the data is piled up into a buffer until there is a line break. When a line break occurs, the printed data is sent to the console.

Sometimes this can cause headaches.

Let’s demonstrate this via an example where we build a count-down timer. This timer works such that it prints numbers 3, 2, and 1 one second apart from one another and then prints “Go” at the end like this:

As you know, calling print() function automatically adds a line break at the end. To make the counter work, however, you do not want line breaks. Instead, you want to display between each second, so you need to replace the automatically added line break with three dots.

Here is how you would probably implement the counter described above:

import time s = 3 for countdown in reversed(range(s + 1)): if countdown > 0: print(countdown, end=". ") time.sleep(1.0) else: print("Go")

But if you run this program, you notice it waits for 3 seconds and only then prints the whole thing in one go.

This problem occurs because of the absence of line breaks. As you learned, the operating system optimizes the print() calls by buffering them until it sees a line break. The first line break in the above code happens only on the last line print(“Go”). Until this, the buffer stores all the printed items, and nothing appears in the console.

To overcome this issue, you need to tell the operating system not to buffer subsequent print() function calls. In other words, you want to flush the buffer every time you call print().

To do this, simply set flush=True into the print() function call:

import time s = 3 for countdown in reversed(range(s + 1)): if countdown > 0: print(countdown, end=". ", flush=True) time.sleep(1.0) else: print("Go")

Now if you run the program, you will see the countdown timer work as expected.

Источник

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.

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!")

Источник

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