杰瑞科技汇

Python print结果为何显示异常?

Of course! The print() function is one of the most fundamental and frequently used functions in Python. It's used to display output to the console.

Python print结果为何显示异常?-图1
(图片来源网络,侵删)

Here's a comprehensive guide covering everything from basic usage to advanced features.

Basic Usage

The simplest way to use print() is to pass it a single value, which it will then display.

print("Hello, World!")
# Output: Hello, World!
print(42)
# Output: 42
print(3.14)
# Output: 3.14
print(True)
# Output: True

Printing Multiple Values

You can print multiple items at once by separating them with commas. print() will automatically insert a space between each item.

name = "Alice"
age = 30
print(name, age)
# Output: Alice 30
# You can mix different data types
print("The value of pi is approximately", 3.14)
# Output: The value of pi is approximately 3.14

The end Parameter (By default: \n)

By default, print() adds a newline character (\n) at the end of its output, which moves the cursor to the next line. You can change this using the end parameter.

Python print结果为何显示异常?-图2
(图片来源网络,侵删)
# Default behavior (end='\n')
print("First line.")
print("Second line.")
# Output:
# First line.
# Second line.
# Custom end parameter
print("First line.", end=" ")
print("Second line.", end=" ")
print("Third line.")
# Output: First line. Second line. Third line.
# Example: A loading animation
import time
for i in range(4):
    print(f"Loading... {i+1}/4", end="\r")
    time.sleep(1)
# Output will overwrite itself on the same line: Loading... 4/4

The sep Parameter (By default: )

The sep parameter (separator) defines the string that will be inserted between items when you print multiple values. The default separator is a single space.

# Default behavior (sep=' ')
print("apple", "banana", "cherry")
# Output: apple banana cherry
# Custom separator
print("apple", "banana", "cherry", sep=" - ")
# Output: apple - banana - cherry
# No separator
print("apple", "banana", "cherry", sep="")
# Output: applebananacherry

Printing Variables and F-Strings (Formatted String Literals)

The most common and readable way to combine text and variables is with f-strings (available in Python 3.6+). You prefix the string with an f and place variables inside curly braces .

name = "Bob"
city = "New York"
age = 25
# Using f-strings (Recommended)
print(f"My name is {name}, I live in {city}, and I am {age} years old.")
# Output: My name is Bob, I live in New York, and I am 25 years old.
# You can also perform calculations inside f-strings
print(f"In 10 years, {name} will be {age + 10} years old.")
# Output: In 10 years, Bob will be 35 years old.

Printing to a File

You can redirect the output of print() to a file instead of the console using the file parameter. The file must be opened in write ('w') or append ('a') mode.

# Open a file in write mode. 'w' will overwrite the file if it exists.
# 'a' will append to the file if it exists.
with open("output.txt", "w") as f:
    print("This line will be written to the file.", file=f)
    print("This will be on the next line in the file.", file=f)
print("Done writing to the file.")
# Check the contents of "output.txt" in your editor.

Common Pitfalls and Tips

a) Forgetting the Parentheses in Python 2

In Python 2, print was a statement, not a function. In Python 3, it's a function, so you must use parentheses.

Python print结果为何显示异常?-图3
(图片来源网络,侵删)
# Python 3 (Correct)
print("Hello")
# Python 2 (Syntax Error in Python 3)
# print "Hello"

b) Trying to Print a Non-String Without Conversion

If you try to concatenate a string and a number using , Python will raise a TypeError. You must convert the number to a string first or, better yet, use an f-string.

# Incorrect way
# message = "The result is " + 10
# TypeError: can only concatenate str (not "int") to str
# Correct way 1: Using str()
print("The result is " + str(10))
# Output: The result is 10
# Correct way 2: Using an f-string (more readable)
print(f"The result is {10}")
# Output: The result is 10

c) Printing Lists and Dictionaries

By default, print() will display a representation of the list or dictionary, which is useful for debugging.

my_list = [1, 2, 3, "hello"]
my_dict = {"name": "Charlie", "score": 95}
print(my_list)
# Output: [1, 2, 3, 'hello']
print(my_dict)
# Output: {'name': 'Charlie', 'score': 95}

Summary Table

Feature Example Description
Basic Print print("Hello") Prints a single string or value.
Multiple Items print("A", "B", "C") Prints multiple items, separated by a space.
Separator (sep) print("A", "B", sep="|") Prints items with a custom separator (A|B).
End Character (end) print("End", end="!") Prints without a newline, appending a custom character (End!).
F-Strings print(f"Value: {x}") The modern way to embed variables inside strings.
Print to File print("text", file=my_file) Writes output to a file object instead of the console.
分享:
扫描分享到社交APP
上一篇
下一篇