Python print()
Function
The print() function is one of the most commonly used built-in functions in Python. It displays the given message or values on the screen (standard output).
Syntax
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
Parameters:
*objects
– One or more expressions to be printed.sep
– String inserted between values. Default is a space.end
– String added after the last value. Default is newline'\n'
.file
– Where to print. Default is the console (standard output).flush
– Whether to forcibly flush the stream. Default isFalse
.
Basic Example
print("Hello, World!")
Hello, World!
Example: Printing Multiple Values
print("Name:", "Alice", "Age:", 25)
Name: Alice Age: 25
Example: Using sep
and end
print("apple", "banana", "cherry", sep=", ", end=".")
apple, banana, cherry.
Use Case: Printing in Loops
for i in range(3):
print("Line", i)
Line 0
Line 1
Line 2
Print with Formatting
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")
My name is Alice and I am 25 years old.
Print to a File
with open("output.txt", "w") as f:
print("Writing to file", file=f)
Common Mistakes
- Using
print
without parentheses in Python 3 (works in Python 2 only) - Expecting
print()
to return a value – it returnsNone
Interview Tip
print()
is often used for debugging. Knowing how to format outputs and print in loops can help during problem solving rounds.
Summary
print()
sends output to the screen.- You can customize output using
sep
,end
, andfile
. - Supports f-strings and multiple arguments.
Practice Problem
Write a Python program that asks for your name and prints: Hello, <your name>!
name = input("Enter your name: ")
print("Hello,", name + "!")