One of the first and most-used functions in Python is the print()
function. It’s simple, powerful, and essential for displaying output to the screen. Whether you’re debugging, showing results, or interacting with users, print()
is your best friend.
In this chapter, we’ll explore everything you need to know about print()
, including its syntax, common use cases, and all the arguments it supports—with clear examples.
🔹 Basic Syntax
print(object, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
✅ 1. Printing Simple Text
print("Hello, World!")
Output:
Hello, World!
You can print strings, numbers, variables, and even expressions.
name = "Ajay"
age = 30
print("Name:", name, "Age:", age)
✅ 2. The sep
Parameter (Separator)
By default, print()
separates multiple arguments with a space. You can change this using sep
.
print("Python", "is", "awesome", sep="-")
Output:
Python-is-awesome
✅ 3. The end
Parameter
By default, print()
ends with a newline (\n
). You can change it to stay on the same line or add something else.
print("Loading", end="...")
print("Done!")
Output:
Loading...Done!
✅ 4. Printing Multiple Lines
You can use \n
to insert line breaks manually.
print("Line 1\nLine 2\nLine 3")
Output:
Line 1
Line 2
Line 3
✅ 5. Using print()
with Variables and Expressions
x = 5
y = 10
print("Sum of", x, "and", y, "is", x + y)
You can also use f-strings for cleaner formatting:
print(f"Sum of {x} and {y} is {x + y}")
✅ 6. The file
Parameter
By default, print()
outputs to the screen. You can redirect it to a file.
with open("output.txt", "w") as f:
print("This will be written to the file.", file=f)
✅ 7. The flush
Parameter
By default, output is buffered. If you want to force it to appear immediately (e.g., in real-time logging), set flush=True
.
import time
for i in range(3):
print(f"Processing {i}", end="\r", flush=True)
time.sleep(1)
🧠 Summary Table
Parameter | Description | Default |
---|---|---|
sep | Separator between values | ' ' |
end | What to print at the end | '\n' |
file | Output destination | sys.stdout |
flush | Force flush the output buffer | False |
✅ Conclusion
The print()
function may seem simple at first glance, but it’s incredibly powerful once you understand its full potential. From customizing output with sep
and end
, to redirecting it to files or flushing output in real time—print()
plays a vital role in every Python programmer’s toolkit. Mastering it early on not only boosts your confidence but also lays a strong foundation for building more complex programs.
So go ahead—experiment, mix things up, and make your code talk to you! 🧑💻🖨️