Python 中常见的 SyntaxError 错误


在 Python 中,SyntaxError 是最常见的错误之一,通常是由于代码中的语法错误导致的。以下是十个常见的 SyntaxError 错误:

拼写错误: 变量名或函数名拼写错误。

# 错误示例
pritn("Hello, World!")

# 正确示例
print("Hello, World!")

异常信息

NameError: name ‘pritn’ is not defined

缺少冒号: 在代码块、条件语句或循环中缺少冒号。

# 错误示例
if x > 10
    print("x is greater than 10")

# 正确示例
if x > 10:
    print("x is greater than 10")

异常信息

if x > 10

         ^

SyntaxError: invalid syntax

缩进错误: 在缩进代码块时混用了空格和制表符或者缩进不正确。

# 错误示例
def my_function():
print("Hello, World!")

# 正确示例
def my_function():
    print("Hello, World!")

异常信息

print(“Hello, World!”)
^
IndentationError: expected an indented block

未闭合的括号、方括号或花括号: 漏掉了括号或者没有正确匹配。

# 错误示例
my_list = [1, 2, 3

# 正确示例
my_list = [1, 2, 3]

异常信息

^
SyntaxError: unexpected EOF while parsing

缺少引号: 字符串没有正确地用引号包围。

# 错误示例
message = "Hello, World!

# 正确示例
message = "Hello, World!"

异常信息

message = "Hello, World!
^
SyntaxError: EOL while scanning string literal

代码块缺失: if、else、elif 等条件语句后没有相应的代码块。

# 错误示例
if x > 10:
print("x is greater than 10")
else:
print("x is less than or equal to 10")

# 正确示例
if x > 10:
    print("x is greater than 10")
else:
    print("x is less than or equal to 10")

错误的注释: 注释符号使用错误。

# 错误示例
/* This is a comment */

# 正确示例
# This is a comment

关键字错误: 使用了 Python 中的关键字作为变量名。

# 错误示例
def = 10

# 正确示例
my_def = 10

不匹配的引号: 使用了不匹配的引号。

# 错误示例
message = 'Hello, World!"

# 正确示例
message = 'Hello, World!'

格式化字符串错误: 格式化字符串中的占位符使用错误。

# 错误示例
name = "Alice"
greeting = f"Hello, {
      
      names}!"

# 正确示例
name = "Alice"
greeting = f"Hello, {
      
      name}!"

订阅时间

学 Python,一定要订阅下述三个专栏(全网累计已有 10000+人学习)
《Python 爬虫 120》https://blog.csdn.net/hihell/category_11079529.html
《爬虫 100 例教程》https://blog.csdn.net/hihell/category_9280209.html
《滚雪球学 Python》https://blog.csdn.net/hihell/category_10573584.html

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/hihell/article/details/131856798