Printing messages and execution results on the screen makes an application more informative and user friendly.
Further, it makes the application dynamic since it can display results which are generated on the fly.

Python provides a built-in function print() which writes or prints values to the console or screen.
Since it is a function, it is followed by parenthesis. Value to be printed is written inside parenthesis.
If the value is a string, then it must be enclosed between quotes(either single or double).
Below statement will print Hello World! on the screen.

print("Hello World!")

print() function can also print the result of a calculation directly as shown below

print(2 + 5)
print(3 * 3)

Output will be


Note that print() automatically adds a new line character after the value so that the next print() writes from another line.
Printing empty line
Often we need to add a line break between multiple statements. This could be done by writing print() with empty parenthesis or an empty string between parenthesis. Example,

print(2 + 5)
print("There is a line gap")

which outputs


There is a line gap

Printing variable values
If there is any variable or expression supplied to print(), then they are evaluated before the output is displayed on the screen as shown below

# define variables
x = 2
y = 5
# print variable
# print expression

which prints


Combining text and variable
Often, we need to print the value of a variable along with a meaningful message.
print() function accepts multiple values separated by a comma and prints all of these on the screen. Example,

x = 2
y = 5
print('Sum of numbers is', x+y)

Output is

Sum of numbers is 7

Note that a space is added between the arguments.

Variables between text: format() function
Suppose you want to print a string which contains dyanmic values or variables in between. Suppose, you need to print
Sum of 2 and 5 is 7
where 2 and 5 are resolved from variables.
One method is to print it by separating it logically using a comma as shown below

x = 2
y = 5
print('Sum of', x, 'and', y, 'is', x+y)

This does not look good and is prone to errors.
There is another way using format() function as shown below.

x = 2
y = 5
print('Sum of {} and {} is {}'.format(x,y,x+y))

Supply the string to be printed to the print() function with empty curly braces({}) as placeholders for variable values.
This string should be followed by format() function containing variables in the same order in which they need to be printed.
Output will be

Sum of 2 and 5 is 7

Note that format() is a function of python strings and has nothing to do with print() function.


Liked the article ? Spread the word...

This Post Has 2 Comments

  1. Gifto

    Am interested to know more about python


      This course covers details about basic python. Further there is an advanced topics section too.
      Still if you want to learn any other topic, do mention it here and we will try to add it.

Leave a Reply