Printing output is one of the most basic and essential operations in Python. The print()
function allows you to display information on the screen, making it useful for debugging, displaying results, or providing user feedback. Here’s everything you need to know:
Basic Usage of print()
The simplest form of print()
outputs text or data to the console.
print("Hello, World!")
This will output:
Hello, World!
Printing Multiple Items
You can print multiple items at once, separating them with commas.
name = "Chandra"
age = 30
print("Name:", name, "Age:", age)
This will output:
Name: Chandra Age: 30
Using String Concatenation
You can also concatenate (combine) strings using the +
operator inside print()
.
greeting = "Hello"
name = "Chandra"
print(greeting + ", " + name + "!")
This will output:
Hello, Chandra!
Escape Characters
Certain characters, like quotes, tabs, and newlines, require escape sequences:
- Newline (
\n
): Moves the text to the next line. - Tab (
\t
): Adds a tab space. - Escape (
\\
): Allows you to use a backslash in a string.
print("Hello,\nWorld!") # Outputs Hello on one line and World on the next.
print("Name:\tChandra") # Adds a tab space between 'Name:' and 'Chandra'.
print("This is a backslash: \\")
Formatted Strings (f-strings)
Introduced in Python 3.6, f-strings allow you to embed expressions inside string literals, using {}
braces.
name = "Chandra"
age = 30
print(f"My name is {name} and I am {age} years old.")
This will output:
My name is Chandra and I am 30 years old.
Using sep
and end
Parameters
sep
(separator): Defines how to separate multiple items inprint()
. By default, it’s a space.end
: Defines what to append at the end of the output. By default, it’s a newline (\n
).
print("Hello", "World", sep=", ") # Changes separator to ', '
print("First line", end=". ") # Changes the ending to '. ' instead of a new line
print("Second line")
This will output:
Hello, World
First line. Second line
Summary
The print()
function is highly flexible and crucial for both basic and advanced programming tasks. It helps display information in various ways, from simple strings to formatted text.