Common SyntaxError errors in Python


In Python, SyntaxError is one of the most common errors, usually due to syntax errors in the code. Here are ten common SyntaxError errors:

Spelling errors: Misspelled variable or function names.

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

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

exception information

NameError: name ‘pritn’ is not defined

Missing colons: Missing colons in code blocks, conditional statements, or loops.

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

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

exception information

if x > 10

         ^

SyntaxError: invalid syntax

Indentation errors: Mixing spaces and tabs or incorrect indentation when indenting a code block.

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

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

exception information

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

Unclosed brackets, square brackets, or curly braces: A bracket is missing or not matched correctly.

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

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

exception information

^
SyntaxError: unexpected EOF while parsing

Missing quotes: The string is not properly surrounded by quotes.

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

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

exception information

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

Missing code blocks: There are no corresponding code blocks after conditional statements such as if, else, elif, etc.

# 错误示例
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")

Incorrect comment: The comment symbol is used incorrectly.

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

# 正确示例
# This is a comment

Keyword Error: A Python keyword was used as a variable name.

# 错误示例
def = 10

# 正确示例
my_def = 10

Mismatched quotes: Mismatched quotes were used.

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

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

Format String Error: Wrong use of placeholders in format string.

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

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

subscription time

To learn Python, you must subscribe to the following three columns (10,000+ people have learned the entire network)
"Python Crawler 120" https://blog.csdn.net/hihell/category_11079529.html
"Crawler 100 Example Tutorial" https://blog.csdn.net/hihell/category_9280209.html
"Snowball Learning Python" https: //blog.csdn. net/hihell/ category_10573584.html

在这里插入图片描述

Guess you like

Origin blog.csdn.net/hihell/article/details/131856798