Showing Output in Python

Introduction

Displaying output on the screen is done using the print() function of Python. The print() function take as many arguments as we can pass separated by commas.

Syntax

The syntax of Python print() is :

print(string, sep =’ ‘, end = ‘ ’, file = file, flush = flush)

where:

string: It specifies the values to be printed on screen (we can give multiple values separated by comma).

To print the string in the new line, \n is used.

Example:

print("1 \n 2 \n 3 ")

Output:

Showing String Output in Python

sep(optional):: It specifies how to separate the multiple values. You can give , / | \=> ? or any other character.

Example 1:

print("1","2","3", sep ='/')

 

Output:

Showing Sep Output in Python

Example 2:

print("GoCoding "," Python "," print() function", sep ='>>')

 

Output:

Showing Sep Output in Python 2

end(optional):: If you want to print something at the end you can give the value to the end By default \n is assumed, that is why control is passed in the next line after the execution of the print statement.

Example:

print("1","2","3", sep ='/', end = 'n')

 

Output:

Showing End Output in Python

file(optional):: It specifies the object with write mode. By default it is bound to sys.stdout                         .

flush(optional): It is a Boolean value specifying whether the output is flushed(value = True) or buffered (value = False). By default the value is False, i.e the values are printed in chunks. If the value is set to be True, the sequence of characters will be printed one after another on screen. This process is time-consuming as printing the values in chunk require less time than printing values character by character.

Example:

import time as time

count = 3

for val in range(count + 1):

                      if val > 0:

                           print(val, end='/', flush = True)

                           time.sleep(1)

                      else:

                            print('Here you go')

 

Explanation:

When you use flush = True, the program will behave as a counter here and prints the value one after another. It will print one character then wait for the desired amount of time (1 sec) then will print another one. Whereas if the flush value is not set to True, the counter will wait for the total desired amount (3 sec) of time and then prints the whole value at once. This scenario will not act as a counter.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.