Python print(): Display Output in the Console

The print() function outputs text, numbers, and other values to the console. It’s useful for debugging, displaying results, and formatting output.

Example

print("Hello, World!")

Output:

Hello, World!

Displays text inside quotes.

Syntax

print(*objects, sep=" ", end="\n", file=sys.stdout, flush=False)
  • *objects → One or more values to print.
  • sep (optional) → Separator between values (default: " ").
  • end (optional) → What to print at the end (default: "\n").
  • file (optional) → Send output to a file instead of the console.
  • flush (optional) → Forces immediate printing (default: False).

1. Printing Multiple Values

print("Python", "is", "awesome")

Output:

Python is awesome

By default, values are separated by a space.

2. Changing the Separator (sep)

print("Python", "is", "awesome", sep="-")

Output:

Python-is-awesome

Useful for custom output formatting.

3. Changing the End Character (end)

print("Hello", end=" ")
print("World!")

Output:

Hello World!

Normally, print() adds a new line (\n), but end=" " prevents it.

4. Printing to a File

with open("output.txt", "w") as file:
    print("Hello, File!", file=file)

Saves output to a file instead of the console.

5. Printing Variables

name = "Alice"
age = 25
print("Name:", name, "| Age:", age)

Output:

Name: Alice | Age: 25

Prints text and variables together.

6. Using print() for Debugging

x = 10
print(f"Value of x: {x}")  # Using f-string

Output:

Value of x: 10

F-strings make debugging easier.

Key Notes

  • Prints text, numbers, and variables to the console.
  • Supports custom separators (sep) and end characters (end).
  • Can write output to a file.
  • Useful for debugging with f-strings.

By using print(), you can display messages, format output, and debug efficiently. 🚀

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top