The Wayback Machine - https://web.archive.org/web/20240828150404/https://www.geeksforgeeks.org/python-output-using-print-function/
Open In App

Python | Output using print() function

Last Updated : 25 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Python print() function prints the message to the screen or any other standard output device. In this article, we will cover about print() function in Python as well as it’s various operations.

Python print() Function Syntax 

Syntax : print(value(s), sep= ‘ ‘, end = ‘\n’, file=file, flush=flush)

Parameters: 

  • value(s): Any value, and as many as you like. Will be converted to a string before printed
  • sep=’separator’ : (Optional) Specify how to separate the objects, if there is more than one.Default :’ ‘
  • end=’end’: (Optional) Specify what to print at the end.Default : ‘\n’
  • file : (Optional) An object with a write method. Default :sys.stdout
  • flush : (Optional) A Boolean, specifying if the output is flushed (True) or buffered (False). Default: False

Return Type: It returns output to the screen.

Though it is not necessary to pass arguments in the print() function, it requires an empty parenthesis at the end that tells Python to execute the function rather than calling it by name. Now, let’s explore the optional arguments that can be used with the print() function.

Example

In this example, we have created three variables integer, string and float and we are printing all the variables with print() function in Python.

Python
name = "John"
age = 30

print("Name:", name)
print("Age:", age)

Output
Name: John
Age: 30


How print() works in Python?

You can pass variables, strings, numbers, or other data types as one or more parameters when using the print() function. Then, these parameters are represented as strings by their respective str() functions. To create a single output string, the transformed strings are concatenated with spaces between them.

In this code, we are passing two parameters name and age to the print function.

Python
name = "Alice"
age = 25

print("Hello, my name is", name, "and I am", age, "years old.")

Output
Hello, my name is Alice and I am 25 years old.


Python print() Function with Examples

Python String Literals

String literals in Python’s print statement are primarily used to format or design how a specific string appears when printed using the print() function.

  • \n: This string literal is used to add a new blank line while printing a statement.
  • “”: An empty quote (“”) is used to print an empty line.

Example

This code uses \n to print the data to the new line.

Python
print("GeeksforGeeks \n is best for DSA Content.")

Output
GeeksforGeeks 
 is best for DSA Content.


Python “end” parameter in print()

The end keyword is used to specify the content that is to be printed at the end of the execution of the print() function. By default, it is set to “\n”, which leads to the change of line after the execution of print() statement.

Example

In this example, we are using print() with end and without end parameters.

Python
# This line will automatically add a new line before the
# next print statement
print ("GeeksForGeeks is the best platform for DSA content")

# This print() function ends with "**" as set in the end argument.
print ("GeeksForGeeks is the best platform for DSA content", end= "**")
print("Welcome to GFG")

Output
GeeksForGeeks is the best platform for DSA content
GeeksForGeeks is the best platform for DSA content**Welcome to GFG


Print Concatenated Strings

In this example, we are concatenating strings inside print() function in Python.

Python
print('GeeksforGeeks is a Wonderful ' + 'Website.')

Output
GeeksforGeeks is a Wonderful Website.


Output formatting

In this example, we are formatting our output to make it look more attractive by using str.format() function.

Python
a,b,=10,1000
print('The value of a is {} and b is {}'.format(a,b))

Output
The value of a is 10 and b is 1000


Python Input

In this example, we are using print() and input() in Python to take user input and print it in the output.

Python
n = input('Enter the Number: ')

print('Number Entered by User:',n)

print(type(n))

Output

Enter the Number: 20
Number Entered by User: 20
<class 'str'>

Flush parameter in Python with print() function

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

Imagine you are building a countdown timer, which appends the remaining time to the same line every second. It would look something like below:

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

The initial code for this would look something like below as follows: 

Python
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')

So, the above code adds text without a trailing newline and then sleeps for one second after each text addition. At the end of the countdown, it prints Start and terminates the line. If you run the code as it is, it waits for 3 seconds and abruptly prints the entire text at once. This is a waste of 3 seconds caused due to buffering of the text chunk as shown below :

Image

Though buffering serves a purpose, it can result in undesired effects as shown above. To counter the same issue, the flush argument is used with the print() function. Now, set the flush argument as true and again see the results.

Python
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

Image

Python print() flush argument

Python “sep” parameter in print()

The print() function can accept any number of positional arguments. To separate these positional arguments, the keyword argument “sep” is used.

Note: As sep, end, flush, and file are keyword arguments their position does not change the result of the code. 

Example

This code is showing that how can we use the sep argument for multiple variables.

Python
a=12
b=12
c=2022
print(a,b,c,sep="-")

Output
12-12-2022


Example

Positional arguments cannot appear after keyword arguments. In the below example 10, 20 and 30 are positional arguments where sep=’ – ‘ is a keyword argument.

Python
print(10, 20, sep=' - ', 30)

Output

  File "0b97e8c5-bacf-4e89-9ea3-c5510b916cdb.py", line 1
print(10, 20, sep=' - ', 30)
^
SyntaxError: positional argument follows keyword argument

File Argument in Python print()

Contrary to popular belief, the print() function doesn’t convert messages into text on the screen. These are done by lower-level layers of code, that can read data(message) in bytes. The print() function is an interface over these layers, that delegates the actual printing to a stream or file-like object. By default, the print() function is bound to sys.stdout through the file argument. 

With IO Module

This code creates a dummy file using the io module in Python. It then adds a message “Hello Geeks!!” to the file using the print() function and specifies the file parameter as the dummy file.

Python
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
print(dummy_file.getvalue())

Output
Hello Geeks!!



Writing to a File with Python’s print() Function

This code is writing the data in the print() function to the text file. 

Python
print('Welcome to GeeksforGeeks Python world.!!', file=open('Testfile.txt', 'w'))

Output

Output

Image

Python Print()

Python | Output using print() function – FAQs

What Are the Different Parameters of print()?

The print() function in Python has several parameters that allow you to control its behavior:

  1. objects: One or more objects to be printed. Multiple objects are separated by spaces by default.
  2. sep: A string inserted between objects. Default is a single space.
  3. end: A string appended after the last object. Default is a newline ('\n').
  4. file: An object with a write method, like sys.stdout (default) or a file object.
  5. flush: A boolean specifying whether to forcibly flush the stream. Default is False.

Syntax:

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

How to Format Output with print() in Python?

You can format output in several ways:

  1. Using the format() method:
  2. Using f-strings (Python 3.6+):
  3. Using the % operator:
name = "Alice"
age = 30
print("Name: {}, Age: {}".format(name, age))
name = "Alice"
age = 30
print(f"Name: {name}, Age: {age}")
name = "Alice"
age = 30
print("Name: %s, Age: %d" % (name, age))

How to Print Without a Newline in Python?

To print without a newline, you can set the end parameter to an empty string or any other string of your choice.

Example:

print("Hello", end="")
print("World")

Output:

HelloWorld

How to Use ‘end' and ‘sep' Parameters in print()?

Using the end Parameter

The end parameter specifies what to print at the end of the output. The default is a newline character.

Example:

print("Hello", end=" ")
print("World")

Output:

Hello World

Using the sep Parameter

The sep parameter specifies the separator between multiple objects. The default is a space.

Example:

print("Hello", "World", sep=", ")

Output:

Hello, World

Combined Example

Example using both sep and end parameters:

print("Hello", "World", sep=", ", end="!")

Output:

Hello, World!


Previous Article
Next Article

Similar Reads

Program to print its own name as output
Ever thought about writing a script which prints its own name when you execute it. It's pretty simple. You must have noticed programs in which the main function is written like this int main(int argc, char** argv) and you must have wondered what these 2 arguments mean. Well the first one argc is the number of arguments passed in to your program.The
2 min read
Click response on video output using Events in OpenCV – Python
OpenCV is a computer vision library that contains various functions to perform operations on Images or videos. OpenCV library can be used to perform multiple operations on videos. In this article, we will create a program with a click response on video output using events in OpenCV Python library. We will be using “cv2.EVENT_LBUTTONDOWN” in case wh
3 min read
Print powers using Anonymous Function in Python
Prerequisite : Anonymous function In the program below, we have used anonymous (lambda) function inside the map() built-in function to find the powers of 2. In Python, anonymous function is defined without a name. While normal functions are defined using the def keyword, in Python anonymous functions are defined using the lambda keyword. Hence, ano
2 min read
How to generate basic HTML output using CGI scripts?
In this article, we will explore the process of generating basic HTML output using CGI scripts. Specifically, we will focus on creating a simple HTML web page using Python. The objective is to provide a step-by-step walkthrough, detailing the entire process of creating and utilizing CGI scripts to generate HTML content within a web environment. Wha
3 min read
Output of Python Programs | Set 22 (Loops)
Prerequisite: Loops Note: Output of all these programs is tested on Python3 1. What is the output of the following? mylist = ['geeks', 'forgeeks'] for i in mylist: i.upper() print(mylist) [‘GEEKS’, ‘FORGEEKS’]. [‘geeks’, ‘forgeeks’]. [None, None]. Unexpected Output: 2. [‘geeks’, ‘forgeeks’] Explanation: The function upper() does not modify a string
2 min read
Output of Python Programs | Set 24 (Dictionary)
Prerequisite : Python-Dictionary 1. What will be the output? dictionary = {&quot;geek&quot;:10, &quot;for&quot;:45, &quot;geeks&quot;: 90} print(&quot;geek&quot; in dictionary) Options: 10 False True Error Output: 3. True Explanation: in is used to check the key exist in dictionary or not. 2. What will be the output? dictionary ={1:&quot;geek&quot;
2 min read
Generate two output strings depending upon occurrence of character in input string in Python
Given an input string str[], generate two output strings. One of which consists of that character that occurs only once in the input string and the second consists of multi-time occurring characters. Output strings must be sorted. Examples: Input : str = "geeksforgeeks" Output : String with characters occurring once: "for". String with characters o
4 min read
Output of Python Programs | (Dictionary)
Prerequisite: Dictionary Note: Output of all these programs is tested on Python3 1.What is the output of the following of code? a = {i: i * i for i in range(6)} print (a) Options: a) Dictionary comprehension doesn’t exist b) {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6:36} c) {0: 0, 1: 1, 4: 4, 9: 9, 16: 16, 25: 25} d) {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5
2 min read
Python | Testing Output to stdout
Testing is a critical part of development as there is no compiler to analyze the code before Python executes it. Given a program that has a method whose output goes to standard Output (sys.stdout). This almost always means that it emits text to the screen. One likes to write a test for the code to prove that, given the proper input, the proper outp
2 min read
Python | Logging Test Output to a File
Problem - Writing the results of running unit tests to a file instead of printed to standard output. A very common technique for running unit tests is to include a small code fragment (as shown in the code given below) at the bottom of your testing file. Code #1 : import unittest class MyTest(unittest.TestCase): ... if __name__ == '__main__': unitt
2 min read
Python VLC MediaPlayer – Getting Audio Output Devices
In this article we will see how we can get list of output devices of the MediaPlayer object in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. MediPlyer object is the basic object in vlc module for playing the video. Audio o
2 min read
Python VLC Instance - Enumerate the defined audio output devices
In this article we will see how we can get the enumerate audio output devices from the Instance class in the python vlc module. VLC media player is a free and open-source portable cross-platform media player software and streaming media server developed by the VideoLAN project. Instance act as a main object of the VLC library with the Instance obje
3 min read
Output of Python Program - Dictionary (set 25)
Prerequisite: Dictionaries in PythonThese question sets will make you conversant with Dictionary Concepts in Python programming language. Question 1: Which of the following is true about Python dictionaries? A. Items are accessed by their position in a dictionary. B. All the keys in a dictionary must be of the same type. C. Dictionaries are mutable
3 min read
How to write the output to HTML file with Python BeautifulSoup?
In this article, we are going to write the output to an HTML file with Python BeautifulSoup. BeautifulSoup is a python library majorly used for web scraping but in this article, we will discuss how to write the output to an HTML file. Modules needed and installation: pip install bs4 Approach: We will first import all the required libraries.Make a g
2 min read
Writing Scrapy Python Output to JSON file
In this article, we are going to see how to write scrapy output into a JSON file in Python. Using scrapy command-line shell This is the easiest way to save data to JSON is by using the following command: scrapy crawl &lt;spiderName&gt; -O &lt;fileName&gt;.json This will generate a file with a provided file name containing all scraped data. Note tha
2 min read
Output of Python Program | Set 1
Predict the output of following python programs: Program 1: r = lambda q: q * 2 s = lambda q: q * 3 x = 2 x = r(x) x = s(x) x = r(x) print (x) Output: 24 Explanation : In the above program r and s are lambda functions or anonymous functions and q is the argument to both of the functions. In first step we have initialized x to 2. In second step we h
3 min read
Output of Python program | Set 5
Predict the output of the following programs: Program 1: C/C++ Code def gfgFunction(): &amp;quot;Geeksforgeeks is cool website for boosting up technical skills&amp;quot; return 1 print (gfgFunction.__doc__[17:21]) Output: cool Explanation: There is a docstring defined for this method, by putting a string on the first line after the start of the fun
3 min read
Output of Python programs | Set 7
Prerequisite - Strings in Python Predict the output of the following Python programs. These question set will make you conversant with String Concepts in Python programming language. Program 1 var1 = 'Hello Geeks!' var2 = &quot;GeeksforGeeks&quot; print &quot;var1[0]: &quot;, var1[0] # statement 1 print &quot;var2[1:5]: &quot;, var2[1:5] # statemen
3 min read
Output of Python programs | Set 8
Prerequisite - Lists in Python Predict the output of the following Python programs. Program 1 Python Code list = [1, 2, 3, None, (1, 2, 3, 4, 5), ['Geeks', 'for', 'Geeks']] print len(list) Output: 6Explanation: The beauty of python list datatype is that within a list, a programmer can nest another list, a dictionary or a tuple. Since in the code th
3 min read
Output of Python programs | Set 9 (Dictionary)
Prerequisite: Dictionary 1) What is the output of the following program? C/C++ Code dictionary = {'GFG' : 'geeksforgeeks.org', 'google' : 'google.com', 'facebook' : 'facebook.com' } del dictionary['google']; for key, values in dictionary.items(): print(key) dictionary.clear(); for key, values in dictionary.items(): print(key) del dictionary; for ke
3 min read
Output of Python programs | Set 10 (Exception Handling)
Pre-requisite: Exception Handling in Python Note: All the programs run on python version 3 and above. 1) What is the output of the following program? data = 50 try: data = data/0 except ZeroDivisionError: print('Cannot divide by 0 ', end = '') else: print('Division successful ', end = '') try: data = data/5 except: print('Inside except block ', end
3 min read
Output of python program | Set 13(Lists and Tuples)
Prerequisite: Lists and Tuples 1) What is the output of the following program? C/C++ Code List = [True, 50, 10] List.insert(2, 5) print(List, &quot;Sum is: &quot;, sum(List)) a) [True, 50, 10, 5] Sum is: 66 b) [True, 50, 5, 10] Sum is: 65 c) TypeError: unsupported operand type(s) for +: 'int' and 'str' d) [True, 50, 5, 10] Sum is: 66 Ans. (d) Expla
3 min read
Output of python program | Set 15 (Modules)
Prerequisite: Regular Expressions Note: Output of all these programs is tested on Python3 1) Which of the options below could possibly be the output of the following program? C/C++ Code from random import randrange L = list() for x in range(5): L.append(randrange(0, 100, 2)-10) # Choose which of outputs below are valid for this code. print(L) a) [-
3 min read
Output of Python program | Set 15 (Loops)
Prerequisite - Loops in Python Predict the output of the following Python programs. 1) What is the output of the following program? x = ['ab', 'cd'] for i in x: i.upper() print(x) Output: ['ab', 'cd'] Explanation: The function upper() does not modify a string in place, but it returns a new string which here isn’t being stored anywhere. So we will g
2 min read
Output of Python Programs | Set 18 (List and Tuples)
1) What is the output of the following program? C/C++ Code L = list('123456') L[0] = L[5] = 0 L[3] = L[-2] print(L) a) [0, '2', '3', '4', '5', 0] b) ['6', '2', '3', '5', '5', '6'] c) ['0', '2', '3', '5', '5', '0'] d) [0, '2', '3', '5', '5', 0] Ans. (d) Explanation: L[0] is '1' and L[5] is '6', both of these elements will be replaced by 0 in the Lis
3 min read
Output of Python Programs | Set 19 (Strings)
1) What is the output of the following program? C/C++ Code str1 = '{2}, {1} and {0}'.format('a', 'b', 'c') str2 = '{0}{1}{0}'.format('abra', 'cad') print(str1, str2) a) c, b and a abracad0 b) a, b and c abracadabra c) a, b and c abracadcad d) c, b and a abracadabra Ans. (d) Explanation: String function format takes a format string and an arbitrary
3 min read
How to Disable Output Buffering in Python
Output buffering is a mechanism used by the Python interpreter to collect and store output data before displaying it to the user. While buffering is often helpful for performance reasons there are situations where you might want to disable it to ensure that output is immediately displayed as it is generated especially in the interactive or real-tim
3 min read
Python | Output Formatting
In Python, there are several ways to present the output of a program. Data can be printed in a human-readable form, or written to a file for future use, or even in some other specified form. Users often want more control over the formatting of output than simply printing space-separated values. Output Formatting in PythonThere are several ways to f
7 min read
Retrieving the output of subprocess.call() in Python
The subprocess.call() function in Python is used to run a command described by its arguments. Suppose you need to retrieve the output of the command executed by subprocess.call(). In that case, you'll need to use a different function from the subprocess module, such as subprocess.run(), subprocess.check_output(), or subprocess.Popen(). Introduction
4 min read
Input and Output in Python
Understanding input and output operations is fundamental to Python programming. With the print() function, you can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Python Basic Input and OutputIn this introductory guide, we'll explore the essentials of Python's
8 min read
Article Tags :
Practice Tags :