Home  >  Article  >  Backend Development  >  Python common errors and solutions, recommended to collect!

Python common errors and solutions, recommended to collect!

WBOY
WBOYforward
2023-04-13 19:04:013431browse

Python common errors and solutions, recommended to collect!

Text

Hello everyone, I am Python Artificial Intelligence Technology

If you say what you are most afraid of when writing code, it is undoubtedly Bugs. For novices who have just come into contact with programming, when they enjoy the sense of accomplishment of writing code, they are often confused by various bugs.

Python common errors and solutions, recommended to collect!

Today, we will share an issue about common Python errors to save your code!

1. Indentation Error (IndentationError)

In Python, all code is arranged with correct spaces. So, whether there are extra spaces or missing spaces, the entire code will not run and only an error function will be returned.

Python code follows the PEP8 whitespace specification, using 4 spaces for each level of indentation.

Error example

a=1
b=2
if a<b:
print a

Correction

a=1
b=2
if a<b:
 print a

2. Mixing of Tab and spaces (TabError)

This type of error is due to the use of tabs and spaces at the same time Due to encoding, the tab key is essentially a tab character, not an indent character. Since the width of the space represented by the tab character in different text editors varies, it is recommended to use spaces.

3. SyntaxError (SyntaxError)

The reasons for syntax errors include the following three types:

1. Invalid syntax (invalid syntax)

Punctuation marks Omissions, mixed use of Chinese and English symbols, spelling errors, keywords used in variable names or function names.

2. There are invalid characters in the identifier (invalid character in identifier) ​​

There are unrecognizable characters in the code. Check whether there are redundant characters or Chinese characters.

3. Incomplete string detected (EOL while scanning string litera)

In many cases it is due to inconsistent quotation marks on both sides of the string. In addition, search the public account Linux to learn how to reply "git books" in the background and get a surprise gift package.

Error example

print( 'hello', 'world')

Error reason: The comma is a Chinese comma

Error message: SyntaxError: invalid character inidentifier

result = (1024+(512*2)/128

Error reason: The parentheses are not completed The

error message appears: SyntaxError: unexpected EOF whileparsing

if name =="A"
print("hello")

Cause of error: Forgot to add colon

# at the end of statements such as if/elif/else/while/for/def/class etc. ##Error message: SyntaxError:invalid syntax

4. Variable name error (NameErro)

Variable name error is the most common and most commonly encountered type of built-in error, which often appears in In Python variable naming, if the variable cannot be found, NameError will be raised. Regarding the rules for variable names, you need to keep in mind the following:

    Variable names can only contain letters, numbers, and underscores, and cannot start with numbers;
  • Variable names cannot contain spaces, but Underscores can be used to separate words;
  • Do not use Python keywords and function names as variable names, such as print;
  • Variable names should be short and descriptive;
  • Use the lowercase letter l and the uppercase letter O with caution, as they can easily be mistaken for the numbers 1 and 0.
If a variable name error occurs, you can check whether the variable is assigned a value, whether the case is inconsistent or the variable name is written incorrectly, and correct it after finding it.

Error example

message = "Hello!"
print(mesage)

Cause of error: The variable name is spelled incorrectly, massage is mistakenly spelled as masge

Error message: NameError: name 'mesage' is not defined

5. IndexError (IndexError)

The index is the position of the item in the array or list. When we try to access an element from the list or access a tuple from an index that does not exist in the list, it This exception occurs.

For example, if you have a list of 10 elements with indices between 0 and 9, if you try to access an element with index 10 or 11 or more, an IndexError will be raised.

Error example

a = [1,2,3]
print(a[3])

Cause of error: The 4th index does not exist in list a, and the index of the list starts from 0

Error message: IndexError: string index out of range

6. KeyError (KeyError)

When reading the key and value in the dictionary, if the key does not exist, a KeyError error will be triggered.

Error example

d = {'a':1,'b':2}
print(d['f'])

Cause of error: Key 'f' does not exist

Error message: KeyError: 'f'

7. TypeError (TypeError )

This error is raised when an incorrect or unsupported object type is used in the program. This error is also raised if an attempt is made to call a non-callable object or to iterate through a non-iterable identifier.

Error example

age=18
print("我的年龄是"+age)

Cause of error: When using " " for splicing, you must use a string, or convert the number into a string using the str() function

Error message: TypeError: can only concatenate str(not "int")to str

8. Attribute error (AttributeError)

Attribute error will be raised when attribute reference and assignment fail.

The reason for this type of error is an attempt to access unknown object properties. In other words, the properties of the corresponding object cannot be found. You can check whether the constructor __init__() in the class is written correctly, with two underlines on the left and right sides.

The above is the detailed content of Python common errors and solutions, recommended to collect!. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:51cto.com. If there is any infringement, please contact admin@php.cn delete