Understanding the print()
function and escape sequences is essential for writing readable and interactive Python programs. Let's explore these features in detail.
The print()
function is used to display output to the screen. Its basic syntax is:
print(object(s), sep=separator, end=end, file=file, flush=flush)
' '
).'\n'
).write
method. Default is sys.stdout
.True
, forces the output stream to be flushed immediately. Default is False
.print("Hello, World!")
Output:
Hello, World!
name = "Alice"
age = 25
print("Name:", name, "Age:", age)
Output:
Name: Alice Age: 25
sep
and end
print("Hello", "World", sep="-", end="!")
Output:
Hello-World!
The sep
parameter specifies the separator between objects, and the end
parameter specifies what is printed at the end.
Escape sequences are used to include characters in a string that cannot be typed directly. They start with a backslash (\
) followed by a specific character.
\n
: Newline\t
: Tab\\
: Backslash\'
: Single quote\"
: Double quoteprint("Hello\nWorld!") # Prints on two lines
print("Path:\\Python\\Scripts") # Prints the backslash
print("Hello\tPython Learners!") # Adds a tab space
Output:
Hello
World!
Path:\Python\Scripts
Hello Python Learners!
Ensure that escape sequences are used properly to avoid syntax errors.
The print()
function supports advanced formatting to create well-structured outputs.
name = "Alice"
age = 25
print(f"Name: {name}, Age: {age}") # f-string formatting
Output:
Name: Alice, Age: 25
print(f"{'Name':<10} {'Age':>5}")
print(f"{'Alice':<10} {25:>5}")
print(f"{'Bob':<10} {30:>5}")
Output:
Name Age
Alice 25
Bob 30
Objective: Use escape sequences and advanced print features to create formatted outputs.
Write a Script:
Create a Python script print_practice.py
to experiment with escape sequences and print formatting.
Use Escape Sequences:
\n
.\\
.Experiment with Formatting:
Example:
# Using escape sequences
print("Hello\nPython\nLearners")
# Using formatted print
print(f"{'Name':<10} {'Age':>5}")
print(f"{'Alice':<10} {25:>5}")
print(f"{'Bob':<10} {30:>5}")
With a solid understanding of the print()
function and escape sequences, you are now ready to create structured and interactive outputs in Python. Let’s continue to build your Python expertise!