2.7 The print() Function (BT101CO)
The print() function is the primary way to output data to the standard output device (usually the screen). In Python, it is a versatile tool that can display text, numbers, variables, and the results of expressions.
1. Basic Syntax
The simplest form of the print() function is:
print(value1, value2, ..., sep=' ', end='\n')
- Values: You can pass one or multiple items (strings, integers, etc.) separated by commas.
- Comma Separation: When you use a comma to separate multiple items, Python automatically adds a space between them.
Example:
name = "Ashok"
age = 25
print("Name:", name, "Age:", age)
# Output: Name: Ashok Age: 25
2. Standard Arguments: sep and end
Python provides two special "keyword arguments" that allow you to control how the output is formatted.
The sep (Separator) Argument
By default, sep is a space (' '). You can change it to any string, such as a hyphen, a slash, or even a newline.
print("12", "05", "2026", sep="-")$\rightarrow$ 12-05-2026
The end Argument
By default, print() adds a newline (\n) at the end of the output, meaning the next print() statement will start on a new line. You can change this to stay on the same line.
print("Hello", end=" ")print("World")$\rightarrow$ Hello World (on one line)
Example: Custom Layouts
# Using 'sep' to create a date format
print("Date", "03", "31", "2026", sep="/")
# Output: Date/03/31/2026
# Using 'end' to keep output on the same line (like a loading bar)
print("Loading", end="...")
print(" [||||||||||]", end=" ")
print("100% Complete")
# Output: Loading... [||||||||||] 100% Complete
3. Printing Expressions
You don't just have to print variables; you can perform calculations or logic directly inside the parentheses.
print("Result:", 10 * 5 + 2)$\rightarrow$ Result: 52print("Is 10 > 5?", 10 > 5)$\rightarrow$ Is 10 > 5? True
4. Formatted Output (f-strings)
While there are older ways to format strings (like % or .format()), modern Python uses f-strings (formatted string literals). They are highly readable and efficient.
Example:
price = 49.99
print(f"The total cost is ${price}")
# Output: The total cost is $49.99
5. Escape Sequences
To print special characters that are otherwise hard to type (like a tab or a quote), you use a backslash (\) followed by a specific character.
| Escape Sequence | Result |
|---|---|
\n |
Newline (starts a new line) |
\t |
Horizontal Tab (adds space) |
\' |
Single Quote |
\" |
Double Quote |
\\ |
Backslash |
Summary Table
| Feature | Description |
|---|---|
| Purpose | To display output on the screen. |
| Multiple Items | Separated by commas; adds a space by default. |
| Default End | Automatically moves to a new line (\n). |
| Flexibility | Can print literals, variables, and expressions. |
The print() function is the "voice" of your program, allowing it to communicate results, status updates, and errors to the user.