Python 简明教程

Python - Syntax Errors

Python Syntax Errors

在 Python 中,语法错误是最常见的程序员错误,特别是刚接触这门语言的程序员。本教程将帮助你理解什么是语法错误,如何识别语法错误以及如何修复它们。

In Python, syntax errors are among the most common errors encountered by programmers, especially those who are new to the language. This tutorial will help you understand what syntax errors are, how to identify them, and how to fix them.

What is a Syntax Error?

Python(或任何编程语言)中的语法错误是在代码不遵循该语言的语法规则时发生的错误。语法错误在解析代码时由解释器或编译器检测,并且会阻止代码被执行。

A syntax error in Python (or any programming language) is an error that occurs when the code does not follow the syntax rules of the language. Syntax errors are detected by the interpreter or compiler at the time of parsing the code, and they prevent the code from being executed.

发生这些错误的原因是编写的代码不符合 Python 的语法规则,导致解释器无法理解和执行这些命令。

These errors occur because the written code does not conform to the grammatical rules of Python, making it impossible for the interpreter to understand and execute the commands.

Common Causes of Syntax Errors

以下是语法错误的常见原因 −

Following are the common causes of syntax errors −

# Error: Missing colon (:) after the if statement
if True
   print("This will cause a syntax error")
# Error: The print statement is not correctly indented
def example_function():
print("This will cause a syntax error")
# Error: 'print' is misspelled as 'prnt'
prnt("Hello, World!")
# Error: The closing parenthesis is missing.
print("This will cause a syntax error"

How to Identify Syntax Errors

有时识别 Python 的语法错误很容易,尤其是在你可以从解释器那里获得清晰的错误信息时。然而,在其他时候,识别错误可能有些棘手。以下提供几种方法,可以帮助你有效识别并解决语法错误 −

Identifying syntax errors in Python can sometimes be easy, especially when you get a clear error message from the interpreter. However, other times, it can be a bit tricky. Here are several ways to help you identify and resolve syntax errors effectively −

Reading Error Messages

运行 Python 脚本时,如果解释器遇到语法错误,它将停止执行并显示错误消息。因此理解如何读取这些错误消息非常重要。

When you run a Python script, the interpreter will stop execution and display an error message if it encounters a syntax error. Understanding how to read these error messages is very important.

Example Error Message

Example Error Message

File "script.py", line 1
   print("Hello, World!"
                        ^
SyntaxError: EOL while scanning string literal

该错误消息可分解为以下几部分 −

This error message can be broken down into parts −

  1. File "script.py": Indicates the file where the error occurred.

  2. line 1: Indicates the line number in the file where the interpreter detected the error.

  3. print("Hello, World!": Shows the line of code with the error.

  4. ^: Points to the location in the line where the error was detected.

Using an Integrated Development Environment (IDE)

IDE 有助于识别语法错误,因为它们通常会提供实时反馈。以下是一些有助于识别语法错误的 IDE 功能 −

IDEs are helpful in identifying syntax errors as they often provide real-time feedback. Here are some features of IDEs that helps in identifying syntax errors −

  1. Syntax Highlighting: IDEs highlight code syntax in different colors. If a part of the code is incorrectly colored, it may indicate a syntax error.

  2. Linting: Tools like pylint or flake8 check your code for errors and stylistic issues.

  3. Error Underlining: Many IDEs underline syntax errors with a red squiggly line.

  4. Tooltips and Error Messages: Hovering over the underlined code often provides a tooltip with a description of the error.

具有这些功能的流行 IDE 包括 PyCharm、Visual Studio Code 和 Jupyter Notebook。

Popular IDEs with these features include PyCharm, Visual Studio Code, and Jupyter Notebook.

Running Code in Small Chunks

如果您有一个较大的脚本,那么以较小的片段运行代码可能很有用。这样可以帮助找出导致语法错误的代码部分。

If you have a large script, it can be useful to run the code in smaller chunks. This can help isolate the part of the code causing the syntax error.

例如,如果您有一个带有多个函数的脚本,并且遇到了语法错误,请尝试独立运行每个函数以缩小错误发生位置的范围。

For example, if you have a script with multiple functions and you get a syntax error, try running each function independently to narrow down where the error might be.

Using Version Control

Git 等版本控制系统可以帮助您跟踪代码中的更改。如果您遇到语法错误,您可以将当前版本的代码与以前的版本进行比较,以查看哪些更改可能导致了该错误。

Version control systems like Git can help you track changes to your code. If you encounter a syntax error, you can compare the current version of the code with previous versions to see what changes might have introduced the error.

Fixing Syntax Errors

修复 Python 中的语法错误涉及了解解释器提供的错误消息,识别代码中的确切问题,然后进行必要的更正。以下是有关如何系统地处理和修复语法错误的详细指南 −

Fixing syntax errors in Python involves understanding the error message provided by the interpreter, identifying the exact issue in the code, and then making the necessary corrections. Here is a detailed guide on how to systematically approach and fix syntax errors −

Read the Error Message Carefully

Python 的错误消息非常具有信息性。它们指出了文件名、行号和语法错误类型 −

Python’s error messages are quite informative. They indicate the file name, line number, and the type of syntax error −

Example Error Message

Example Error Message

假设我们编写的 print 语句如下 −

Assume we have written a print statement as shown below −

print("Hello, World!"

以下消息表明第 1 行存在语法错误,表明代码中某个位置的括号未闭合,导致语法错误。

The following message indicates that there is a syntax error on line 1, showing that somewhere in the code, a parenthesis was left unclosed, which leads to a syntax error.

File "/home/cg/root/66634a37734ad/main.py", line 1
    print("Hello, World!"
         ^
SyntaxError: '(' was never closed

若要修复此错误,你需要确保每个左括号都有与之相对应的右括号。以下是已更正的代码: -

To fix this error, you need to ensure that every opening parenthesis has a corresponding closing parenthesis. Here is the corrected code −

print("Hello, World!")

Locate the Error

若要找到错误,你需要转到错误消息中提到的行号。此外,不仅要检查指定的行,还要检查周围的行,因为有时问题可能源自前几行。

To locate the error, you need to go to the line number mentioned in the error message. Additionally, check not only the indicated line but also the lines around it, as sometimes the issue might stem from previous lines.

Understand the Nature of the Error

若要理解错误的本质,你需要确定它是哪种类型的语法错误(例如,缺少括号、缩进不正确、缺少冒号等)。另外,请参阅常见的语法错误及其模式。

To understand the nature of the error, you need to identify what type of syntax error it is (e.g., missing parenthesis, incorrect indentation, missing colon, etc.). Also, refer to common syntax errors and their patterns.

Correct the Syntax

基于错误类型修复代码。

Based on the error type, fix the code.