Parameters
Let's discuss the parameters of the print() function in more detail:
*objects
-
The *objects parameter allows you to pass multiple objects or values to the print() function.
-
You can pass any valid Python object, such as strings, numbers, variables, expressions, etc.
-
If multiple objects are provided, they are separated by commas.
- The objects are printed in the order they are passed.
Example
Python
name = "Rekha"
age = 25
print("My name is", name, "and I am", age, "years old.")

You can also try this code with Online Python Compiler
Run Code
Output:
My name is Rekha and I am 25 years old.
sep
-
The sep parameter specifies the separator between the objects being printed.
-
By default, it is a space character (' ').
- You can change the separator to any desired string.
Example
Python
print("apple", "banana", "cherry", sep=", ")

You can also try this code with Online Python Compiler
Run Code
Output:
apple, banana, cherry
end
-
The end parameter specifies the character(s) to be printed at the end of the output.
-
By default, it is a newline character ('\n'), which moves the cursor to the next line.
- You can change the end character to any desired string.
Example
Python
print("Hello", end=" ")
print("World")

You can also try this code with Online Python Compiler
Run Code
Output:
Hello World
file
-
The file parameter specifies the file object where the output will be written.
-
By default, it is sys.stdout, which represents the standard output (usually the console).
- You can redirect the output to a file by passing a file object.
Example
with open("output.txt", "w") as file:
print("Hello, World!", file=file)
This will write "Hello, World!" to the file "output.txt".
flush
-
The flush parameter specifies whether the output should be immediately flushed to the file.
-
By default, it is False, meaning the output is buffered and may not be immediately written to the file.
- Setting flush to True ensures that the output is immediately written to the file.
Example:
print("Important message", flush=True)
This will immediately flush the output "Important message" to the console or file.
Return Type
The print() function in Python does not have a return value. It simply outputs the specified objects to the console or a file and returns None. This means that you cannot assign the result of the print() function to a variable or use it in expressions.
Example:
Python
result = print("Hello")
print(result)

You can also try this code with Online Python Compiler
Run Code
Output:
Hello
None
In this example, we assign the result of print("Hello") to the variable result. However, since print() doesn't return a value, result is assigned the value None. When we print result, it outputs None.
It's important to note that the print() function is used for displaying information to the user and not for returning values. If you need to store or manipulate the output, you should use other methods, such as string concatenation or string formatting.
Example
Python
name = "Rahul"
age = 30
city = "New Delhi"
print("My name is", name)
print("I am", age, "years old")
print("I live in", city)

You can also try this code with Online Python Compiler
Run Code
Output:
My name is Rahul
I am 30 years old
I live in New Delhi
In this example:
We define three variables: name, age, and city.
We use the print() function to display the values of these variables along with some accompanying text.
The print() function automatically separates the objects with a space and moves to the next line after each print statement.
You can also use string concatenation or string formatting to achieve the same result:
print("My name is " + name)
print("I am " + str(age) + " years old")
print("I live in " + city)
or using string formatting:
print(f"My name is {name}")
print(f"I am {age} years old")
print(f"I live in {city}")
Both string concatenation and string formatting allow you to combine text and variables in a single print statement.
The print() function is versatile and can handle various types of objects, making it a convenient way to display information in Python programs.
How print() works in Python?
The print() function in Python is a built-in function that is used to display output on the console or write it to a file. When you call the print() function, it takes one or more objects as arguments and outputs them in a human-readable format.
Let’s see how the print() function works:
Argument Evaluation
-
Python evaluates each argument passed to the print() function from left to right.
-
If the argument is a variable, Python retrieves its value.
- If the argument is an expression, Python evaluates the expression and uses its result.
String Conversion
-
Python converts each argument to a string representation.
-
For objects that have a string representation (such as strings, numbers, and certain data types), Python uses their built-in string conversion methods.
- If an object doesn't have a string representation, Python uses its str() or repr() method to convert it to a string.
Separator Insertion
-
After converting the arguments to strings, Python inserts the separator (specified by the sep parameter) between each argument.
- By default, the separator is a space character (' ').
End Character
-
After concatenating the string representations of the arguments and the separators, Python appends the end character (specified by the end parameter) at the end of the output.
- By default, the end character is a newline character ('\n'), which moves the cursor to the next line.
Output
-
Finally, Python writes the resulting string to the specified file or the standard output (usually the console).
-
If the file parameter is provided, Python writes the output to the specified file.
- If the flush parameter is set to True, Python immediately flushes the output buffer, ensuring that the output is written immediately.
For example :
Python
name = "Harsh"
age = 25
print("My name is", name, "and I am", age, "years old.", sep=" ", end="\n")

You can also try this code with Online Python Compiler
Run Code
Output:
My name is Harsh and I am 25 years old.
In this example:
-
Python evaluates the arguments: "My name is", name, "and I am", age, "years old.".
-
Python converts each argument to a string: "My name is", "Harsh", "and I am", "25", "years old.".
-
Python inserts the separator (a space character) between each argument.
-
Python appends the end character (a newline character) at the end of the output.
- Python writes the resulting string to the standard output (console).
Python print() Function with Examples
Now, let's see some examples that demonstrate the different functionalities and use cases of the print() function in Python.
Printing a single object
Python
print("Hello, World!")

You can also try this code with Online Python Compiler
Run Code
Output:
Hello, World!
Printing multiple objects
Python
name = "Gaurav"
age = 25
print("My name is", name, "and I am", age, "years old.")

You can also try this code with Online Python Compiler
Run Code
Output
My name is Gaurav and I am 25 years old.
Using the sep parameter
Python
print("apple", "banana", "cherry", sep=", ")

You can also try this code with Online Python Compiler
Run Code
Output:
apple, banana, cherry
Using the end parameter
Python
print("Hello,", end=" ")
print("World!")

You can also try this code with Online Python Compiler
Run Code
Output
Hello, World!
Printing formatted strings
Python
name = "Sanjana"
age = 30
print(f"My name is {name} and I am {age} years old.")

You can also try this code with Online Python Compiler
Run Code
Output:
My name is Sanjana and I am 30 years old.
Printing variables of different data types
Python
name = "Sinki"
age = 25
height = 1.75
print("Name:", name)
print("Age:", age)
print("Height:", height)

You can also try this code with Online Python Compiler
Run Code
Output
Name: Sinki
Age: 25
Height: 1.75
Printing a list
Python
fruits = ["apple", "banana", "cherry"]
print(fruits)

You can also try this code with Online Python Compiler
Run Code
Output:
['apple', 'banana', 'cherry']
Printing a dictionary
Python
person = {"name": "Ravi", "age": 25, "city": "New Delhi"}
print(person)

You can also try this code with Online Python Compiler
Run Code
Output
{'name': 'Ravi', 'age': 25, 'city': 'New Delhi'}
Printing to a file
with open("output.txt", "w") as file:
print("Hello, World!", file=file)
This will write "Hello, World!" to the file "output.txt".
Flushing the output
Python
import time
print("Processing...", end="", flush=True)
time.sleep(2) # Simulating some processing time
print("Done!")

You can also try this code with Online Python Compiler
Run Code
Output
Processing...Done!
These examples showcase different scenarios where the print() function can be used effectively. You can mix and match the parameters and arguments to achieve the desired output formatting and behavior.
Remember, the print() function is a versatile tool for displaying information, debugging, and providing output to the user. By understanding its various features and examples, you can utilize it effectively in your Python programs.
Python Input
The input() function in Python is used to accept user input from the keyboard. It prompts the user to enter a value and returns the entered value as a string. Here's an example:
Python
name = input("Enter your name: ")
print("Hello, " + name + "!")

You can also try this code with Online Python Compiler
Run Code
Output
Enter your name: Rinki
Hello, Rinki!
In this example, the input() function prompts the user with the message "Enter your name: " and waits for the user to enter a value. The entered value is then stored in the name variable as a string. Finally, the print() function is used to display a greeting message with the user's name.
You can also convert the input to a specific data type using type casting:
Python
age = int(input("Enter your age: "))
print("You are", age, "years old.")

You can also try this code with Online Python Compiler
Run Code
Output
Enter your age: 25
You are 25 years old.
Here, the input() function prompts the user to enter their age, and the entered value is converted to an integer using int() before storing it in the age variable.
Flush parameter in Python with print() function
The flush parameter in the print() function is used to control whether the output buffer is immediately flushed or not. By default, it is set to False, meaning the output is buffered and may not be immediately written to the console or file. Here's an example:
Python
import time
print("Processing...", end="", flush=True)
time.sleep(2) # Simulating some processing time
print("Done!")

You can also try this code with Online Python Compiler
Run Code
Output:
Processing...Done!
In this example, the flush parameter is set to True, which ensures that the output
"Processing..." is immediately written to the console, without waiting for a newline character or the buffer to be filled. The time.sleep(2) statement simulates some processing time, and then the "Done!" message is printed.
If flush were set to False (or omitted), the output might not appear immediately, especially if the program is terminated or the buffer is not flushed automatically.
Python "sep" parameter in print():
The sep parameter in the print() function specifies the separator between the objects being printed. By default, it is a space character (' '). Here's an example:
Python
print("apple", "banana", "cherry")
print("apple", "banana", "cherry", sep=", ")

You can also try this code with Online Python Compiler
Run Code
Output:
apple banana cherry
apple, banana, cherry
In the first print() statement, the default separator (space) is used between the objects. In the second print() statement, the sep parameter is set to ", ", so the objects are separated by a comma and a space.
You can use any string as the separator, depending on your desired output formatting.
File Argument in Python print():
The file argument in the print() function specifies the file object where the output will be written. By default, it is sys.stdout, which represents the standard output (usually the console). Here's an example:
with open("output.txt", "w") as file:
print("Hello, World!", file=file)
In this example, the print() function writes the string "Hello, World!" to the file "output.txt" instead of the console. The with statement is used to open the file in write mode ("w") and automatically close it after the block of code is executed.
You can use the file argument to redirect the output to any file-like object, such as a file, a StringIO object, or even a network socket.
Writing to a File with Python's print() Function:
To write to a file using the print() function, you can specify the file argument as shown in the previous example. Here's another example that demonstrates appending to a file:
with open("log.txt", "a") as file:
print("Error: Division by zero", file=file)
print("Timestamp: 2023-06-08 10:30:00", file=file)
In this example, the print() function is used to write error messages and timestamps to a log file named "log.txt". The file is opened in append mode ("a"), which means that the new output will be added to the end of the file, preserving its existing content.
Each print() statement writes a separate line to the file, and the file is automatically closed when the with block ends.
By using the print() function with the file argument, you can easily write output to files, which is useful for logging, saving results, or generating reports.
Frequently Asked Questions
How do you print without a newline in Python?
To print without a newline in Python, you can use the end parameter in the print() function and set it to an empty string (end="").
Can you print multiple variables in a single print statement?
Yes, you can print multiple variables in a single print statement by separating them with commas. The print() function will automatically add spaces between the variables.
How do you print to a file instead of the console?
To print to a file instead of the console, you can use the file parameter in the print() function and specify the file object to write to.
Conclusion
In this article, we explored the print() function in Python, a fundamental tool for displaying output. We learned about its syntax, parameters, and various examples that demonstrate its functionality. The print() function allows you to display messages, variables, and results, control output formatting, and write to files. By understanding and applying the concepts covered in this article, you can effectively use the print() function in your Python projects for debugging, informing users, and generating output.
You can refer to our guided paths on Code 360. You can check our course to learn more about DSA, DBMS, Competitive Programming, Python, Java, JavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure andAlgorithms, Competitive Programming, Operating Systems, Computer Networks, DBMS, System Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry.