Python provides numerous built-in functions that are readily available to us at the Python prompt. Some of the functions like input()
and print()
are widely used for standard input and output operations respectively.
Python Output Using print() function
We use the print()
function to output data to the standard output device (screen), As follows
print('Welcome to print screen")
Output
Welcome to print screen
In the same way, we can also print the values stored inside any variable.
a = 10
print('The value of a is', a)
Output
The value of a is 10
In the second print()
the statement, we can notice that space was added between the string and the value of variable a. This is by default, but we can change it.
The actual syntax of the print()
function is:
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
Here, objects
is the value(s) to be printed.
The sep
separator is used between the values. It defaults into a space character.
After all values are printed, end
is printed. It defaults into a new line.
The file
is the object where the values are printed and its default value is sys.stdout
(screen). Here is an example to illustrate this.
print(1, 2, 3, 4)
print(1, 2, 3, 4, sep='*')
print(1, 2, 3, 4, sep='#', end='&')
Output
1 2 3 4 1*2*3*4 1#2#3#4&
Output formatting
Sometimes we would like to format our output to make it look attractive. This can be done by using the str.format()
method. This method is visible to any string object.
>>> x = 5; y = 10
>>> print('The value of x is {} and y is {}'.format(x,y))
The value of x is 5 and y is 10
Here, the curly braces {}
are used as placeholders. We can specify the order in which they are printed by using numbers (tuple index).
print('I love {0} and {1}'.format('bread','butter'))
print('I love {1} and {0}'.format('bread','butter'))