Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python print() Function

Python print() Function

Python3 Built-in Functions Python3 built-in function


print() is a built-in function in Python used to output information.

print() is one of the most commonly used functions in Python programming; it writes content to standard output (usually the console). It can output data of various types and supports a rich set of formatting options.

Word meaning: print 意为"打印",用于输出信息。


Basic syntax and parameters

Syntax format

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

Parameter Description

Function description


Example

Example 1: basic usage

Example

# Output a string
print("Hello, World!")

# Output a number
print(42)
print(3.14159)

# Output multiple objects (separated by commas)
print("My name is", "Tom")
# Output: My name is Tom

# Output variables
name = "Alice"
age = 25
print(name, "is", age, "years old")
# Output: Alice is 25 years old

Expected output:

Hello, World!
42
3.14159
My name is Tom
Alice is 25 years old

Code analysis:

  1. It can output strings, numbers, variables and many other objects.
  2. Multiple objects are separated by commas and printed with a space between them.

Example 2: the sep and end parameters

Example

# Use sep to customize the separator
print("a", "b", "c", sep="-")  # Output: a-b-c
print("1", "2", "3", sep=" -> ")  # Output: 1 -> 2 -> 3

# Use end to customize the ending character
print("Hello", end=" ")
print("World")  # Output: Hello World (no newline)

# No newline with a custom separator
for i in range(5):
    print(i, end=" ")
# Output: 0 1 2 3 4

Expected output:

a-b-c
1 -> 2 -> 3
Hello World
0 1 2 3 4

Code analysis:

Example 3: output to a file

Example

# Output to a file
with open("output.txt", "w") as f:
    print("Hello, File!", file=f)

# Read back to verify
with open("output.txt", "r") as f:
    print(f.read())  # Output: Hello, File!

# Output to standard error
import sys
print("Error message", file=sys.stderr)

# Flush the output immediately
print("Loading", end="", flush=True)
import time
time.sleep(1)
print("Done!")

Expected output:

Content can be written to a file or to the standard error stream.

print() is the most basic tool for debugging and printing information.


Python3 Built-in Functions Python3 built-in function