Common Python errors and their solutions

This article organizes some common Python errors and their solutions.

insert image description here

1、SyntaxError: invalid syntax

Explanation: Invalid syntax is one of the most common errors, usually due to writing code that violates Python's syntax rules. possible reason:

  1. Forget to write colons after statements such as if, while, foretc., or write colons as semicolons or other symbols. Solution: Change to English half-width colon.
  2. There may be incorrectly closed parentheses in your code, or incorrectly matched quotes used in strings. Solution: check the brackets, quotes.
  3. An equal sign (=) appears in a conditional expression. Solution: Change it to a comparison operator (==).
  4. Parentheses are not added when defining a function with no parameters. Solution: Add parentheses.

Check the error message, which usually indicates the line number and location of the error. A proper code editor will also flag syntax errors in the code.

2、Syntax Error: non-default argument follows default argument

Explanation: The parameters defined are not in the correct order. Possible situations:

The default value parameter is not placed at the end of all parameters. Solution: Change the order of the parameters.

3、SyntaxError : invalid character in identifier

Description: There are invalid characters in the identifier, usually caused by using invalid characters in the identifier (variable name, function name, class name, etc.). In Python, identifiers must follow certain naming rules, cannot contain special characters or spaces, can only contain letters, numbers, and underscores, and must start with a letter (or underscore) _. possible reason:

  1. The identifier contains special characters that are not recognized by Python, such as @, #, $, %and so on.
  2. Identifier contains spaces or tabs.
  3. Identifiers start with a number.
  4. The identifier conflicts with a Python reserved word or keyword.

4、TypeError: can only concatenate str (not “XXX”) to str

Explanation: Strings can only be concatenated with other strings. possible reason:

Attempt to concatenate a string with a non-string data type such as an integer, float, boolean, or sequence object. Solution: Use the function to convert the data types before concatenating str().

5、TypeError: f() takes exactly 2 arguments (1 given)

Description: Not enough arguments were supplied to the function. possible reason:

Defines a function with two parameters, but provides only one parameter when called. Solution: Supply the missing parameters to complete the function call.

6、TypeError: ‘tuple’ object does not support item assignment

Description: Tuple elements cannot be modified. possible reason:

Attempts to modify tuple elements by index. Solution: convert the tuple to a list or remove the modify operation.

7、ValueError: could not convert string to float:‘12.2s’

Description: Could not convert string to float. Possible cause:
float()The function accepted a non-float string data type. Solution: Modify to float string.

8、ValueError: invalid literal for int() with base 10

Explanation: int()An invalid parameter was passed to the function. possible reason:

  1. String contains non-numeric characters. Solution: Make sure the string contains only numeric characters. You can use str.isdigit()the method to check whether a string contains only numeric characters.
  2. Trying to convert a string containing a decimal point to an integer. Solution: If the string may contain floating point numbers, use float()the function to convert it to a floating point number and then convert it to an integer.
  3. Number too large or too small: An attempt was made to convert a string of numbers beyond the range that an integer can represent to an integer. Solution: The number is too large or too small to exceed the range of Python's integer representation, use float()or other data types to handle very large values.

9、ValueError: substring not found

Explanation: While trying to find a substring, the substring was not found in the target string. This error may be triggered when using string's index(), find(), rfind()etc. methods. Solution: Check before searching.

10、ZeroDivisionError: division by zero

Note: 0 cannot be used as a divisor. Possible cause: When performing a division, integer division, or remainder operation, 0 was used as the divisor. Solution: Before performing division, check whether the divisor is zero; use a conditional statement to avoid division by zero.

11、AttribteError: ‘module’ object has no attribute xxx’

Explanation: The module has no associated attributes. possible reason:

  1. Spelling error: The property or method name you are trying to access is misspelled. Solution: Check your spelling to make sure you are using the correct property or method name.
  2. .pyUse Python reserved words or the same as the module name when naming the file. Solution: modify the file name
  3. Module renaming: If you import a module and use an alias, you need to use the alias to access the module's properties or methods. Solution: Use the correct alias to access the property or method.

12、AttributeError: ‘Obj’ object has no attribute ‘attr’

Explanation: The object has no associated properties. possible reason:

  1. Spelling error: The property or method name you are trying to access is misspelled. Solution: Check your spelling to make sure you are using the correct property or method name.
  2. If a property or method is private ( __starting with a double underscore), it cannot be accessed directly. Solution: If you want to access a private property or method, you can use a single underscore _or access it through a method of the class.
  3. Object type error: Sometimes, you may call a method on an object that should be a class, or try to call an object method on a non-object. Solution: Make sure to use object methods and class methods in the correct way. Object methods need to be called on the object while class methods need to be called on the class

13、FileExistsError: [Errmo 17] File exists

Explanation: The file already exists. Solution: first check if the file exists, if it exists, don't create it again.

14、FileNotFoundError: [Ermo 2] No such file or directory

Explanation: The requested file or directory does not exist. Solution: Check that the path to the file or directory is correct

15、IndentationError: expected an indented block

Explanation: Indented blocks are required. possible reason:

  1. There is no indentation when defining a function or class. Solution: add indentation
  2. There is no indentation under the construct of ifthe , foror whilestatement. Solution: add indentation

16、IndentationError: unexpected indent

Description: Indentation error. Possible cause: In addition to indentation, extra spaces appear before the code. Solution: Remove extra spaces.

17、IndentationError: unindent does not match any outer indentation level

Explanation: Indentation problem. possible reason:

  1. Code blocks at the same level use different indentation rules (code misalignment). Solution: Adjust the indentation.
  2. Invisible content with illegal characters or other formatting. Solution: Remove illegal characters.

18、IndexError: list index out of range

Explanation: List index out of range, possible reasons:

  1. The index value specified when fetching an element exceeds the length of the list. Solution: Modify the index value
  2. List is empty, error getting element. Solution: Check if it is not null before getting it.

19、DirectoryError: [Ermo 21] Is a directory

Description: An operation was attempted on a file but a directory was provided. Possible cause: Operating a directory as a file, eg if "test" is a directory, using os.remove(test)will result in an error. Solution: add the corresponding filename

20、KeyError: ‘age’

Description: Key error. possible reason:

  1. When getting the value of a dictionary based on a key, the specified key does not exist. Solution: Modify to an existing key.
  2. Keys that do not exist are deleted. Solution: Check if it exists before deleting.

21、ModuleNotFoundError: No module named‘pymysql’

Explanation: Module does not exist. possible reason:

  1. Misspelled module name. Solution: correct spelling
  2. Module is not imported. Solution: importImport the module using the statement.
  3. Environment issues: Sometimes, although a module is installed, it cannot be found in the environment in which the code is running. This may be because it is not installed in the environment being used. Solution: Make sure the modules used are installed in the virtual environment.
  4. Some modules may not support the Python version used. Solution: Make sure that the version of Python used is compatible with the imported module. Check the module documentation to see which versions of Python it supports.

22、NameError:name test’ is not defined

Description: An attempt was made to use an undefined or nonexistent variable or name ('test') in the code, or the name could not be found in the current scope. possible reason:

  1. Variable or name is undefined. Solution: Before using, define the variable or name.
  2. A variable may be defined in a different scope (e.g. inside a function or inside a conditional block) while trying to access it outside that scope. Solution: If you need to use the variable outside the function or in a different scope, define it in the global scope.

23、RecursionEror:maximum rcusion depth exceded in comprison

Description: Maximum recursion depth exceeded. Solution: Disable infinite recursion and set the recursion depth.

24、Timeout error [WinError 10060] No response or response from host after a period of time. Connection attempt failed.

Description: The connection timed out. possible reason:

  1. The database connection timed out. Solution: Check whether the database connection configuration information is correct.
  2. The request URL timed out. Solution: Check that the URL is correct and accessible.
  3. Connection to FTP server timed out. Solution: Check that the parameters used to connect to FTP are correct.

Guess you like

Origin blog.csdn.net/a2360051431/article/details/132384972