Python print function with argument

Python print() function

Python print() function basically prints the given input or object to the output screen or the corresponding stream file.

print(objects, sep=value, end=end_value, file, flush)

Python print() function Arguments:

Arguments Description Required/Optional
object(s) An object or input string Required
sep=’value Specification on how the objects are to be separated.
Default separator value is ‘ ‘
Optional
end=’end_value’ Specifies what is to be printed at the end.
Default value is ‘\n’
Optional
file It is an object with a write method. Default value is sys.stdout. Optional
flush It is a boolean value that specifies whether the output obtained is flushed (True) or buffered (False). Default value is False. Optional

1. Basic understanding of Python print() function

# Passing a single object print("Engineering Discipline")

2. Printing of multiple objects with Python print() function

input = "Safa" print("Result is: ", input) # Contains two objects

3. Printing a Tuple and a List with Python print() function

Python print() function can be used to print Strings, Tuples, Lists, etc. to the output screen.

input_tuple = ("YES", "NO", 200) # Tuple print(input_tuple) input_list = [10,'Apple', 20,'Football', 70] # List print(input_list)
('YES', 'NO', 200) [10, 'Apple', 20, 'Football', 70]

4. Python print() function with “sep” keyword

By default, as you all must have observed, the values in the output are separated by space. But, now the User can customize it by replacing the default value i.e. ‘ ‘ (space) using any symbol or value.

value1 = int(10) value2 = 'Social Science' print(value1, value2, sep='+')

5. Python print() function with “end” keyword

As observed, the default value of the ‘end’ parameter is ‘\n’ i.e. the Python print() functions ends with a newline (‘\n’).

Читайте также:  What is this keyword in java

But, now the User can customize it by replacing the default value i.e. ‘\n'(newline) using any symbol or value.

my_list = [10, 20, 0, 32, 56, 78, 90] print('Printing the list. ') for x in my_list: print(x, end='$')
Printing the list. 10$20$0$32$56$78$90$

6. Python print() function with “file” keyword

Python print() function’s file parameter enables user to write to a file. If the mentioned file doesn’t exist, it creates a new file with the specified name and writes the output to it.

input_file = open('Print_function.txt','w') print('Social Science', file = input_file) input_file.close()

Print Function

Conclusion

Thus, in this article, we have understood the working of Python’s print() function.

References

Источник

To print strings to console or echo some data to console output, use Python inbuilt print() function.

print() function can take different type of values as argument(s), like string, integer, float, etc., or object of a class type.

Python print()

The following is a simple demonstration of how to use print() function in a Python shell.

>>> print("Hello World! Welcome to Python Examples.") Hello World! Welcome to Python Examples. >>> print(10) 10

Syntax of print()

The syntax of print() function is

print(*objects, sep=' ', end='\n', file=None, flush=False)

Python - Print to Console

Examples

1. Print string to console

In this example, we will print a string to console output. Pass string as argument to the print() function.

Python Program

Yeah! That one print statement is all of the program. Run it from your command prompt or terminal using python command. Or you can run it from your Jupyter Notebook.

The string is printed to the console as shown below.

2. Print number to console

In this example, we will pass integer (number) as argument to print() function and print the number to the console.

Python Program

Any datatype passed to the print function is implicitly converted to string and printed to the console. Hence, the int we passed as argument to print() is first converted to string, and then print to the console.

3. Print variables to console

You can provide multiple values to print() function as arguments. They will be printed to console with single space as a default separator. Again, you can specify your own separator, and we shall see that in our next example.

Python Program

Please note that space is printed out to console, between x and y.

4. print() with a specific separator between values

You can pass a string for named parameter sep to override the default separator.

Python Program

x = 'pi is' y = 3.14 print(x, y, sep=' : ')

x and y have been printed to the console with the specified separator.

5. Print with a specific end value

We already know that we can specify an ending value for print() function. New line character is the default ending for print() function in Python. You can override this by passing a string to the named parameter end as shown in the below Python program.

Python Program

print('Hello', end='-') print('World', end='.\n')

Video Tutorial

Summary

In this tutorial of Python Examples, we learned how to print a message to console, a variable or any other datatype to the console, using Python print() builtin function with the help of well detailed Python programs.

Источник

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.

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.

Источник

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