When learning Python, you might wonder, “Is there no println function?” If you’re used to programming languages like Java, having a standard output mechanism like System.out.println() feels natural. However, Python doesn’t have a println() function; instead, you use the print() function. In this article, we’ll explain in detail how to use Python’s print() function, discuss the differences from Java’s println(), and also cover some advanced uses of the print() function.
2. Python’s print() function
When performing standard output in Python, you use the print() function. This function outputs the given data and, by default, adds a newline at the end.
Basic usage of the print() function
The simplest way is to pass a string to the print() function to display it on the screen.
print("Hello, World!")
Output
Hello, World!
Printing multiple strings at once
The print() function can take multiple arguments, which are automatically separated by spaces in the output.
print("Hello", "Python", "World")
Output
Hello Python World
Output using variables
It is also easy to output using variables.
name = "Alice"
age = 25
print("Name:", name, "Age:", age)
Output
Name: Alice Age: 25
Features of the print() function
Can display strings and numbers to standard output.
When multiple arguments are passed, they are separated by spaces.
By default, it adds a newline (configurable).
3. Differences between Java’s println() and Python’s print()
If you’ve studied Java, you’ll feel that Python’s print() function is similar to Java’s System.out.println(). However, there are subtle differences.
How to use Java’s println()
In Java, you use System.out.println() for standard output. When written as below, it displays “Hello, World!” on the screen and ends with a newline.
System.out.println("Hello, World!");
Also, if you want to output without a newline, use System.out.print().
Python’s print() function also adds a newline by default, but you can prevent the newline by using the end argument.
print("Hello", end="")
print(" World")
Output
Hello World
Thus, in Java you use println() and print() separately, but in Python you can achieve the same by using the end option of print().
Comparison table of standard output in Java and Python
Language
Standard output function
With newline
Method without newline
Python
print("text")
Yes
print("text", end="")
Java
System.out.println("text")
Yes
System.out.print("text")
Thus, Python’s print() can be flexibly customized, making it possible to replicate the behavior of Java’s println() almost exactly.
4. print() Function Applications
Python’s print() function not only displays text on the screen, but also allows more flexible output by leveraging various options. This section explains advanced usage of the print() function in detail.
4.1 Outputting Multiple Values with print()
With the print() function, you can pass multiple values using commas (,). Values separated by commas are output separated by spaces by default.
Example</4>
print("Python", "is", "awesome")
Output
Python is awesome
You can also mix numbers and strings in the output.
age = 25
print("I am", age, "years old")
Output
I am 25 years old
4.2 String Formatting with <codeprint()
In Python, there are several ways to format strings for output.
(1) Using the format() method
name = "Alice"
age = 25
print("Name: {}, Age: {}".format(name, age))
Output
Name: Alice, Age: 25
(2) f-strings (recommended for Python 3.6 and later)
name = "Alice"
age = 25
print(f"Name: {name}, Age: {age}")
Output
Name: Alice, Age: 25
✅ Using f-strings improves readability and makes the code more intuitive!
4.3 Preventing Newlines with print()
By default, the print() function adds a newline after output. However, you can control this by using the end parameter to avoid a newline.
Example
print("Hello", end="")
print(" World")
Output
Hello World
✅ Using end="" is handy when you want to output stringsively!
4.4 Changing the Separator with print()
Normally, when print() outputs multiple arguments, they are separated by spaces. However, you can customize this using the sep parameter.
Example
print("Python", "Java", "C++", sep=", ")
Output
Python, Java, C++
✅ Useful when you want to separate data with commas, slashes, etc!
4.5 Outputting to a File with print()
Using the file parameter of print(), you can write output to a file instead of the screen.
Example
with open("output.txt", "w") as f:
print("This will be written to the file.", file=f)
✅ By specifying file=f, the output of print() can be written to a file!
4.6 Unbuffered (Real-Time) Output with print()
Normally, Python’s print() function buffers output (writes in chunks), but specifying flush causes immediate real-time output.
Example
import time
for i in range(5):
print(i, end=" ", flush=True)
time.sleep(1)
Output (displayed every second)
0 1 2 3 4
✅ Handy when you want to see output in real time!
4.7 Capturing print() Output into a Variable (using sys.stdout)
Normally, the output of print() goes to the screen, but using sys.stdout you can capture the output into a variable.
Python’s print() function is extremely convenient and easy to use, but if not used properly it can lead to performance degradation and debugging difficulties. This section explains the cautions of the print() function and best practices for using it more effectively.
5.1 Cautions When Using the print() Function
(1) Large amounts of output can degrade performance
Using the print() function heavily can slow down program execution. This is because print() performs I/O (input/output) operations, and writing to the console or logs takes time.
❌ Code to Avoid
for i in range(1000000):
print(i) # Very slow because it writes to standard output each time
✅ Improved Approach
output = "n".join(str(i) for i in range(1000000))
print(output)
✅ Using join() allows efficient bulk output of large data!
(2) Don’t overuse print() for debugging
During development, using print() for debugging is common, but using dedicated debugging tools is more effective.
❌ Code to Avoid
print("Debug message: variable x =", x)
✅ Using the logging Module
import logging
logging.basicConfig(level=logging.DEBUG)
x = 10
logging.debug(f"Debug message: variable x = {x}")
✅ Using logging instead of print() enables log management by level!
(3) Explicitly Manage the Destination of print() Output
Normally, the print() function displays data to standard output (the console), but you can change the destination using the file parameter.
Saving Logs to a File
with open("log.txt", "w") as f:
print("This log will be saved to a file", file=f)
✅ Writing output to a file instead of the console makes log management easier!
5.2 Best Practices for the print() Function
(1) Leverage f-strings
Since Python 3.6, formatting with f-strings is recommended. This improves readability and simplifies string formatting.
❌ Code to Avoid
print("Name: " + name + ", Age: " + str(age))
✅ Improved Approach
print(f"Name: {name}, Age: {age}")
✅ Using f-strings results in more intuitive and concise code!
(2) Use the end Parameter to Prevent Unnecessary Newlines
By default, the print() function adds a newline after output, but using the end parameter can suppress the newline for continuous output.
❌ Code to Avoid
print("Processing...")
print("Done!")
✅ Improved Approach
print("Processing...", end="")
print("Done!")
Output
Processing...Done!
✅ Reduces unnecessary newlines for cleaner output!
(3) Use the sep Parameter to Set Custom Separators
By default, arguments to print() are separated by spaces, but using sep lets you set any delimiter.
Example: comma-separated
print("Apple", "Banana", "Cherry", sep=", ")
Output
Apple, Banana, Cherry
✅ Handy when you want to format data!
(4) Real-Time Output Processing (flush=True)
Normally, print() output is buffered and may be emitted in batches. To output in real time, specify flush=True to force immediate output.
Example
import time
for i in range(3):
print(f"Processing {i+1}/3...", end="r", flush=True)
time.sleep(1)
In this section, we explained the cautions and best practices for the print() function.
⚠ print() Function Cautions
Large amounts of output can lead to performance degradation (using join() speeds it up)
Don’t overuse it during debugging (using logging is easier to manage)
Be aware of the output destination (you can use the file parameter to output to a file)
✅ print() Function Best Practices
Use f-strings to simplify formatting
Use end to prevent unnecessary newlines
Use sep to customize output
Use flush=True for real-time output
By mastering the proper use of the print() function, you can handle Python’s standard output more efficiently.
6. Frequently Asked Questions (FAQ) about the print() function
Python’s print() function is simple and easy to use, but there are points where beginners often stumble. Here we have compiled common questions and their answers.
Q1: Does Python have a println function?
A1: No, Python does not have a println() function. Use the print() function instead.
The behavior of adding a newline after output, as in Java’s System.out.println(), is the default behavior of Python’s print() function.
Python example
print("Hello, World!") # Prints a newline by default
Java example
System.out.println("Hello, World!"); // Prints a newline by default
➡ Python’s print() performs the same behavior as Java’s println() by default!
Q2: How to prevent a newline with the print() function?
A2: You can prevent a newline by using the end parameter of the print() function.
Example
print("Hello", end="")
print(" World")
Output
Hello World
➡ Using end="" allows output without a newline!
Q3: Can you reproduce exactly the same behavior as Java’s println() in Python?
A3: Yes, in Python you can achieve exactly the same behavior as Java’s println() by using the end option of print().
➡ By specifying end="n", you achieve the same behavior as Java’s println()!
Q4: How to output multiple variables with print()?
A4: By separating with commas (,), you can output multiple variables at once.
Example
name = "Alice"
age = 25
print("Name:", name, "Age:", age)
Output
Name: Alice Age: 25
If you want to format the output, using f-strings is convenient.
print(f"Name: {name}, Age: {age}")
➡ Using f-strings makes it more intuitive and readable!
Q5: How to write print() output to a file?
A5: By using the file parameter, you can save the output of print() to a file.
Example
with open("output.txt", "w") as f:
print("This is the content that will be saved to the file", file=f)
✅ If you want to output to a file, just specify file=f!
Q6: How to write to standard output without using print()?
A6: By using sys.stdout.write(), you can write to standard output without print().
Example
import sys
sys.stdout.write("Hello, World!n")
➡ Using sys.stdout.write() gives you finer control than print()!
Q7: Why do errors occur when using print()?
A7: Here are the main errors that occur when using print() and how to address them.
(1) TypeError: can only concatenate str (not "int") to str
Cause: Occurs when trying to concatenate a string and a number with + in print(). Example (error)
print("Age: " + 25) # Error!
Solution: Convert the number to a string with str().
print("Age: " + str(25)) # Correct usage
(2) SyntaxError: Missing parentheses in call to 'print'
Cause: Happens when running Python 2 code in Python 3. Example (error)
print "Hello, World!" # Python 2 syntax
Solution: In Python 3 you need to add ().
print("Hello, World!") # Correct usage
✅ In Python 3, you must always include () with print!
Q8: How to debug without using print()?
A8: It is recommended to use the logging module instead of print().
Example
import logging
logging.basicConfig(level=logging.DEBUG)
x = 42
logging.debug(f"Value of variable x: {x}")
➡ Using logging lets you manage debug information properly!
7. Summary
In this article, we covered everything from the basics to advanced usage of Python’s print() function, the differences with Java’s println(), how to use handy options, best practices, and frequently asked questions (FAQ). Let’s review the key points.
7.1 Basics of Python’s print() function
Python does not have a println() function; instead, you use the print() function.
print() outputs with a newline by default.
print("Hello, World!") # newline after output
Can output multiple values at once (space-separated)
print("Python", "is", "awesome")
7.2 Differences between Java’s println() and Python’s print()
Language
Standard output function
Newline
How to avoid newline
Python
print("text")
Yes
print("text", end="")
Java
System.out.println("text")
Yes
System.out.print("text")
✅ Python’s print() has functionality equivalent to Java’s println() ✅ Covers everything from basic usage to advanced applications of print()
7.3 Advanced uses of the print() function
Feature
Method
Code example
Prevent newline
Use end
print("Hello", end="")
Custom separator
Use sep
print("Python", "Java", sep=", ")
String formatting
f-strings are recommended
print(f"Name: {name}, Age: {age}")
Output to a file
file parameter
print("record log", file=open("log.txt", "w"))
Real-time output
Use flush=True
print("Processing...", flush=True)
✅ Using print() options enables more flexible output!
7.4 Caveats of the print() function
Large amounts of output can affect performance
output = "n".join(str(i) for i in range(1000000))
print(output) # speed up by bulk output
When outputting elsewhere than standard output, use sys.stdout
import sys
sys.stdout.write("Hello, World!n")
✅ Choosing the appropriate method lets you write more efficient code!
7.5 FAQ Summary
Question
Answer
Does Python have a println()?
No, Python uses print().
How to prevent a newline?
Use print("Hello", end="").
How to achieve the same behavior as Java’s println()?
Use print(text, end="n").
How to output to a file?
print("content", file=open("file.txt", "w"))
Error handling (e.g., TypeError)
Convert numbers to strings using str().
Should you use print() for debugging?
Use logging.
✅ Resolving common questions lets you use print() more smoothly!
7.6 Related topics to learn next
After understanding Python’s print() function, here are important topics to learn next.
Log management using the logging module
import logging
logging.basicConfig(level=logging.INFO)
logging.info("This is an INFO log")
Standard I/O (sys.stdin, sys.stdout, sys.stderr)
import sys
sys.stdout.write("Hello, World!n")
File I/O (how to use open())
with open("output.txt", "w") as f:
f.write("example of file output")
Python debugging techniques
import pdb; pdb.set_trace() # set breakpoint here
✅ Learning these topics lets you control Python’s output more freely!
7.7 Summary
✅ Python’s print() has functionality equivalent to Java’s println() ✅ Covers everything from basic usage to advanced applications of print() ✅ Using end and sep enables flexible output ✅ Considering debugging and performance, choosing the right method is important