Python Print

Print in Python

The function which prints the specified message on the screen and any other output device is the Python Print() function. By the end of this article, we expect you to be comfortable with what print() is and how it works, and we also show some amazing things one can do using python print(). 

If you want enrich your career and become a professional in python, then visit Mindmajix - a global online training platform : "Python Certification Course"   This course will help you to achieve excellence in this domain



Print() Function: Definition, Description and Usage

The Python print() function helps in printing the specified message onto the screen, or any other standard output device. 

The message can be a string, or any other object, the object will be converted into a string before being written to the screen. Whatever be the message format i.e string or any other object, it finally gets converted into a string only.

The print function in Python is a function which is used to output to the console window whatever you say you want to print out. At the first instance, it might seem that the print function is rather pointless for programming, but it is actually one of the most widely used functions in all of python.

The reason for this being that print() function is great as a debugging tool. "Debugging" can be defined as the act of finding and removing or fixing errors and mistakes present in the code which allows the program to operate according to a set of specifications.

Whenever something isn't acting as expected, one can use the print function to print out what is happening in the program. A lot of times, you would be expecting a variable to be a certain way, but the problem is that you cannot see what the program sees. When you print out the variable, you might be able to see what the variable actually is.

Before we proceed let us look at the python print() format.

The syntax of the print function is of the following format

 

print(object(s), separator=separator, end=end, file=file, flush=flush)

 

print() Parameters

 

The Parameter Values with their description is given below:
  • object(s) As many objects as you like will be converted to string before being printed

 

  • sep='separator' Optional. This specifies how to separate the objects, whenever there is more than one. Default is ''

 

  • end='end' Optional. This specifies what needs to be printed at the end. The Default value is 'n'

 

  • file Optional. This is an object with a write method whose default is sys.stdout

 

  • flush Optional. A Boolean value which specifies if the output is flushed (True) or buffered (False). The default value is False
    

A point to remember is that sep, end, file, and flush are all keyword or named arguments. In case you would want to use sep argument, you have to write:

 

print(*objects, sep = 'separator')
not
print(*objects, 'separator')

Return Value from print()

 

One important thing to remember is that Python print() returns no value. It returns None. This is because in Python 2.x, it is considered as a reserved keyword and not a function.

Let us now move forward by going through a couple of examples using the Python print(). We shall also cover examples using

  • end and sep parameters
  • file parameters

But before that let us see the basic functioning using python print() examples.

[Related BlogsHow To Generate a Random Number In Python

Example 1:

 

How print() works in Python?

 

Let us carefully understand how print in python actually works. 

 

print("Python is fun.")
a = 5
# Two objects are passed
print("a =", a)

b = a
# Three objects are passed
print('a =', a, '= b')


When you run the program, the output generated will be:

 

Python is fun.
a = 5
a = 5 = b

 

In the previous program, only the objects parameter has been passed to print() function (in all three print statements).

Therefore,

' ' separator is used. Observe the space between two objects in output.
end parameter 'n' (newline character) is used. Observe that each print statement displays the output in the new line.
 The output has been printed on the screen.
flush is False. This means that the stream is not forcibly flushed.

 

Frequently Asked Python Interview Questions & Answers

 

Now let us look at another example of Python print() with separator and end parameters which we will further elaborate later in this article. 

 

a = 5
print("a =", a, sep='00000', end='nnn')
print("a =", a, sep='0', end='')

 

When you run the program, the output generated will be:

 

a =000005
a =05

 

We have passed the sep and end parameters in the above program.

Finally, let us see how Python print() works with the file parameter 

In Python, you can print the objects to a file by specifying the file parameter.

 

sourceFile = open('python.txt', 'w')
print('Pretty cool, huh!', file = sourceFile)
sourceFile.close()

 

What this program does is that it tries to open the python.txt in writing mode. If this file doesn't exist, python.txt file is created at that moment and then opened in writing mode. Here, we have passed file object 'sourceFile' as the file parameter.  Here, 'Pretty cool, huh!'  is the string object which is printed to python.txt file. 

Finally, the close() method helps in closing the file.

Example 2:

 

Print() with Separator and End Parameters

 

Usually, the separator between the arguments in the print() function in Python is space by default (softspace feature) , which can be changed and be made to any character, integer or string as per our requirements. To achieve the same, we use the ‘sep’ parameter, which is found only in python 3.x or later. It also finds its use in formatting the output strings.

 

Let us take a look at the below examples:

 

#code for disabling the softspace feature 
print('G','F','G', sep='') 
  
#for formatting a date 
print('09','12','2016', sep='-') 
  
#another example 
print('pratik','geeksforgeeks', sep='@') 


The output generated will be of the following format:

 

GFG
09-12-2016
pratik@geeksforgeeks

 

When the sep parameter is coupled with end parameter it produces amazing results. Some examples showing the combination of the two are:

 

print('G','F', sep='', end='') 
print('G') 
#n provides new line after printing the year 
print('09','12', sep='-', end='-2016n') 
  
print('prtk','agarwal', sep='', end='@') 
print('geeksforgeeks') 

 

The output generated is a below:

 

GFG
09-12-2016
prtkagarwal@geeksforgeeks

Checkout Python Tutorials

 

More Variables and Printing

 

Now let's continue with doing more typing of variables and printing them out. This time we'll use the concept of “format string." Whenever you put " (double-quotes) around a piece of text, it results in the formation of a string. We can do a lot with strings. We can print strings, we can save strings to files, we can also send strings to web servers, and many other things.

Strings are very handy, and in this exercise, we will teach you how to make strings that have variables embedded in them. With the help of specialized format sequences we can embed variables inside a string. And by putting these variables at the end of this sequence with a special syntax that communicates to Python that it is a format string and the variables need to be put here. 

Though it's difficult to completely understand at this point of time, just type this in. You'll get clarity once you see the output. 

 

my_name = 'Zed A. Shaw'
my_age = 35 # not a lie
my_height = 74 # inches
my_weight = 180 # lbs
my_eyes = 'Blue'
my_teeth = 'White'
my_hair = 'Brown'


print "Let's talk about %s." % my_name
print "He's %d inches tall." % my_height
print "He's %d pounds heavy." % my_weight
print "Actually that's not too heavy."
print "He's got %s eyes and %s hair." % (my_eyes, my_hair)
print "His teeth are usually %s depending on the coffee." % my_teeth


# this line is tricky, try to get it exactly right
print "If I add %d, %d, and %d I get %d." % (
    my_age, my_height, my_weight, my_age + my_height + my_weight)
A point to remember is to put # -*- coding: utf-8 -*- at the top in case you notice non-ASCII characters and face an encoding.

 

This is the expected output:

 

$ python ex5.py

 

Let's talk about Zed A. Shaw.

he's 74 inches tall.
He's 180 pounds heavy.
Actually that's not too heavy.
He's got Blue eyes and Brown hair.
His teeth are usually White depending on the coffee.
If I add 35, 74, and 180 I get 289.

We would like to challenge you with a couple of exercises. Try them out yourself. 

  • Try to rename all the variables so that there is no my_ in the beginning of each one. You should be sure that you changed the name everywhere, not just at the point where you used = to set them.
  • Try to name and use some variables that convert the inches and pounds to centimeters and kilograms or convert Celsius to Fahrenheit. We suggest you to not just type in the measurements but also work out the math present in Python.
  • Make a note of all the Python format characters.
  • Try using more format characters. One of the useful ones is %r which says "print this no matter what."

 

 MindMajix YouTube Channel

We expect you to face some roadblocks and hurdles too. So we have compiled a set of frequently asked questions.

  • Can I name a variable in this format: 1 = 'Zed Shaw'?
    • No, you cannot. 1 is not considered a valid variable name. Variables need to start with a character, so a1 would be working well, but 1 will not.
  • What does %s, %r, and %d do again?
    • These are called formatters and you'll be learning more about this as you progress. 
  • You might be wondering what a “formatter” is. The hurdle with teaching programming is that to understand many of the descriptions one needs to already know a bit of programming. 
    • The approach we take is to make you do something, and then we explain the concept behind it later. Whenever you run into any kinds of questions, write them down. 
  • How to round off a floating point number?
    • The round() function can be used to round off a floating point number like this: round(1.7333).
  • I face this error TypeError: 'str' object is not callable.
    • This might arise because you might have forgot the % between the string and the list of variables.

Python print without Newline

Whenever people switch from C/C++ to Python, they wonder how to print two or more variables or statements without progressing onto a new line in python, since, by default, the python print() function ends with newline. Python provides you with a predefined format wherein if you use print(a_variable) then it will go to the next line automatically.

 

Let us look at the following example:

 

print("geeks") 
print("geeksforgeeks") 

 

will generate this

 

geeks
geeksforgeeks

 

But in case you would like to print on the same line, what can we do?

 

Input : print("geeks") print("geeksforgeeks")
Output : geeks geeksforgeeks

Input : a = [1, 2, 3, 4]
Output : 1 2 3 4 

One thing to be noted is that the solution which has been discussed is totally dependent on the python version being used. 

 

Print without newline in Python 2.x

 

# Python 2 code for printing 
# on the same line printing 
# geeks and geeksforgeeks  
# in the same line 
  
print("geeks"), 
print("geeksforgeeks") 
  
# array 
a = [1, 2, 3, 4] 
  
# printing a element in same 
# line 
for i in range(4): 
    print(a[i]),  

Output:

 

geeks geeksforgeeks
1 2 3 4

Print without newline in Python 3.x

 

# Python 3 code for printing 
# on the same line printing  
# geeks and geeksforgeeks  
# in the same line 
  
print("geeks", end =" ") 
print("geeksforgeeks") 
  
# array 
a = [1, 2, 3, 4] 
  
# printing a element in same 
# line 
for i in range(4): 
    print(a[i], end =" ")  
Copy CodeRun on IDE

Output:

 

geeks geeksforgeeks
1 2 3 4

With the Python 3.0 version, the python print() statement has changed from being a statement to a function. With more flexibility at its disposal python print() can help you do amazing things. We hope this article has given you the base on which you can master!!

If you are interested learn python and build a career in it ? Then checkout our python training near your cities

Python Training Chennai  Python Training New York  Python Training in Bangalore  Python Training in Dallas

These courses are incorporated with Live instructor-led training, Industry Use cases, and hands-on live projects. This training program will make you an expert in Microsoft Azure and help you to achieve your dream job.

 

Explore Python Sample Resumes! Download & Edit, Get Noticed by Top Employers!Download Now!

 

Job Support Program

Online Work Support for your on-job roles.

jobservice

Our work-support plans provide precise options as per your project tasks. Whether you are a newbie or an experienced professional seeking assistance in completing project tasks, we are here with the following plans to meet your custom needs:

  • Pay Per Hour
  • Pay Per Week
  • Monthly
Learn MoreGet Job Support
Course Schedule
NameDates
Python TrainingNov 19 to Dec 04View Details
Python TrainingNov 23 to Dec 08View Details
Python TrainingNov 26 to Dec 11View Details
Python TrainingNov 30 to Dec 15View Details
Last updated: 03 Apr 2023
About Author

Anjaneyulu Naini is working as a Content contributor for Mindmajix. He has a great understanding of today’s technology and statistical analysis environment, which includes key aspects such as analysis of variance and software,. He is well aware of various technologies such as Python, Artificial Intelligence, Oracle, Business Intelligence, Altrex, etc. Connect with him on LinkedIn and Twitter.

read less
  1. Share:
Python Articles