Skip to main content

Python - Output Methods



 print() function is used to output any value or message to the console or any device.

Syntax:

print(value(s), sep=' ', end='\n', file=file, flush=flush)

Parameters:

values: Any values. 

sep: (optional) Separator. Default:' '

end: (optional) Specifies what to print at the end. Default: '\n'

file: (optional)An object with write method. Default: sys.stdout

flush: (optional) A bool to specify if the out is flushed (if True) or buffered (if False). Default: False

Returns: It returns output to the screen


end=" "

It specifies what to print at the end of execution of print() statement. Default: "\n"

Example:

Program1:

print("I love to code")

print("I'm a programmer", end=". ")

print("I'm an expert in python")

Output:

I love to code

I'm a programmer. I'm an expert in python


Program2:

#print a list values without new line

a = [1, 2, 3, 4]

for i in range(4):

    print(a[i], end =" ")

Output:

1 2 3 4

Program3:

#print list values without new line without using loop

a = [1, 2, 3, 4]

print(*a)

Output:

1 2 3 4


sep=" "

Specifies how to separate object if there is more than 1. Default:" "

Example:

print('a', 'b', 'c')

print('a', 'b', 'c', sep="")

print('11','10','1995', sep='-')

print('ram', 'kumar', sep=''", end='@')

print('forgegig.com')

Output:

a b c

abc

11-10-1995

ramkumar@forgegig.com


flush argument:

The I/Os in python are generally buffered, meaning they are used in chunks. This is where flush comes in as it helps users to decide if they need the written content to be buffered or not. By default, it is set to false. If it is set to true, the output will be written as a sequence of characters one after the other. This process is slow simply because it is easier to write in chunks rather than writing one character at a time. To understand the use case of the flush argument in the print() function, let’s take an example.

Example:

Program1:

#building a countdown timer, which appends the remaining time to the same line every second.

import time

count_seconds = 3

for i in reversed(range(count_seconds + 1)):

    if i > 0:

        print(i, end='>>>')

        time.sleep(1)

    else:

        print('Start')

Output:

3>>>2>>>1>>>Start

Output explanation:

 If you run the code as it is, it waits for 3 seconds and abruptly prints the entire text at once. 

Program2:

import time

count_seconds = 3

for i in reversed(range(count_seconds + 1)):

    if i > 0:

        print(i, end='>>>', flush = True)

        time.sleep(1)

    else:

        print('Start')

Output:

3>>>2>>>1>>>Start


file argument:

file argument is used to print the message to stream or file like object. Default: sys.stdout

Example:

import io

# declare a dummy file

dummy_file = io.StringIO()

# add message to the dummy file

print('Hello Geeks!!', file=dummy_file)

# get the value from dummy file

dummy_file.getvalue()


Comments