A SyntaxError
(1) Quotes don’t come in pairs
Error message:
-
1SyntaxError:EOL while scanning string literal
Examples of errors:
-
1string = ‘hello world
Solution: The string must be enclosed in quotation marks. Single or double quotation marks do not matter. When a string contains either single or double quotation marks, it is easy to have quotation marks mismatched.
(2) Parentheses do not appear in pairs
Error message:
-
1SyntaxError:unexpected EOF while parsing
Error Example 1:
-
1result = (1024+(512*2)/128
Error Example 2:
-
1print(‘hello world’
Solution: Pair the parentheses. This problem is often encountered when writing complex expressions or calling functions.
(3) error using the operator ++ or — etc
Error message:
-
1SyntaxError:invalid syntax
Examples of errors:
-
1v = 64
-
2v++
Solution: In Python, there are no self-operating operators like C’s ++ or –. A similar use of this functionality is the += or -= operators. For example, use the following code to increment v by 1.
-
1v += 1
(4) Try to use equal sign (=) to judge whether two operations are equal
Error message:
-
1SyntaxError:invalid syntax
Examples of errors:
-
1if v=64:
-
2 print(‘hello world’)
Solution: Use two equal signs (==) in Python as relational operators to determine whether two operations are equal, and the equal sign (=) is the assignment operator.
(6) Error using Python keyword as variable name
Error message:
-
1SyntaxError: can`t assign to keyword
Examples of errors:
-
1False= 1
Solution: Do not use Python keywords for variable names, function names, or class names. In the Python Shell window, use the help(‘keywords’) directive to view a list of keywords for the Python language.
(7) forget in the if/elif/else/while/for/def/class statement at the end add a colon (:)
Error message:
-
1SyntaxError:invalid syntax
Error Example 1:
-
1a = ‘12345’
-
2for i in a
-
3 print(i)
Error Example 2:
-
1def sayhi()
-
2 print(‘Hi’)
Solution: the if/elif/else/while/for/def/class statement at the end add a colon (:). Remember the rules of grammar, practice and code.
(8) Incorrect use of Chinese punctuation marks
Error message:
-
1SyntaxError: invalid character in identifier
Error Example 1:
-
1 print (‘ hello ‘, ‘world’)
-
2# Reason for error: A comma is a Chinese punctuation mark
Error Example 2:
-
1for I in range(10) :
-
2# Reason for error: The colon is a Chinese punctuation mark
Solution: Use the English state for editing in any case except that the string can contain Chinese characters.
IndentationError IndentationError
Error message:
-
1IndentationError: Unindent does not match any outer indentation level
-
2IndentationError: Expected an indented block
Examples of errors:
-
1a = 2
-
2while a < 0:
-
3 print(‘hello’)
-
4 a -= 1
-
5else:
-
6 print (‘ 0.0 ‘)
Solution: The indentation inside the while statement in the above code is not aligned. Use indentation properly. This error is more common when code is copied and pasted from somewhere else.
NameError
Name errors occur when a variable name, function name, or class name is incorrectly written, or when a function is called before it is defined. The Python tutorial is designed to help you learn more about Python
Error message:
-
1NameError: name ‘pirnt’ is not defined
-
2NameError: name ‘sayhi’ is not defined
-
3NameError: name ‘pd’ is not defined
Error Example 1:
-
1pirnt(‘hello world’)
-
2# error: print is misspelled.
Error Example 2:
-
1sayhi()
-
2
-
3def sayhi():
-
4 pass
-
5# Cause of error: calling a function before its definition.
Error Example 3:
-
1pd.read_excel(r’file.xlsx’)
-
2# Error: The library was not imported before the pandas method was called, or the alias was not pd.
Solution: Write variable, function, or class names correctly, assign values before using variables, place function definitions before function calls, import, swap, and so on before using third-party libraries. That is, ensure that a name (identifier) exists before it can be used.
TypeError TypeError
(1) Integers and strings cannot be connected
Error message:
-
1TypeError: Can`t convert ‘int’ object to str implicitly
-
2TypeError: unsupported operand type(s) for + : ‘float’ and ‘str’
Error Example 1:
-
1print(‘score:’+100)
Error Example 2:
-
1 print (9.8 + ‘seconds’)
Solution: Before concatenating an integer, floating point, or Boolean to a string, use the STR () function to convert it to a string.
(2) The number of parameters is not correct when the function is called, or parameters are not passed
Error message:
-
1TypeError: input expected at most 1 arguments,got 2
-
2TypeError: say() missing 1 required positional argument:’words’
Error Example 1:
-
1input(‘ Enter name ‘,’ age ‘)
-
2# Error cause: Attempted to supply input() with a second argument.
Error Example 2:
-
1def say(words):
-
2 print(words)
-
3
-
4say()
-
5# Cause of error: The function was called without passing arguments.
Solution: Remember the function usage, understand the function parameter definition, use the correct method to call the function.
5. The KeyError key is incorrect
This error occurs when a dictionary element is accessed with a nonexistent key name.
Error message:
-
1KeyError: ‘c’
Examples of errors:
-
1d = {‘a’:1,’b’:2}
-
2print(d[‘c’])
Workaround: When accessing a dictionary element, use the in keyword to check for the presence of the key to access, or use the dictionary and get() methods to safely access the dictionary element.
IndexError indicates an IndexError
An index error occurs when an index accessing a list is outside the range of the list.
Error message:
-
1IndexError: list index out of range
Examples of errors:
-
1 a = [1, 2, 3]
-
2print(a[3])
-
3# Error cause: a fourth index does not exist in list A. The index of the list is numbered from 0.
Workaround: Len () gets the length of the list, and then determines if the index to be accessed is out of the list.
UNboundLocalError Uninitialized local variable error
This error occurs when you modify an undeclared global variable in a function.
Error message:
-
1UnboundLocalError: local variable ‘s’ referenced before assignment
Examples of errors:
-
1s = 1
-
2
-
3def test():
-
4 s += 1
-
5 print(s)
-
6
-
7test()
-
8# error cause: increment of undeclared global variable s inside function.
-
9# Python treats the variable s as a local, but uninitialized, variable.
Solution: When using a global variable in a function, declare it using the global keyword.
The AttributeError attribute is incorrect
Error message:
-
1AttributeError: ‘tuple’ object has no attribute ‘append’
-
2AttributeError: ‘DataFrame’ object has no attribute ‘col’
Error Example 1:
-
1 t = (1, 2, 3)
-
2t.append(4)
-
3# Error cause: The ancestor is immutable.
Error Example 2:
-
1df = pd.read_excel(r’data.xlsx’)
-
2df.col
-
Error: DataFrame does not have col attribute and should be columns.
Solution: Write the property name of the class correctly without writing errors. A deep understanding of the difference between a meta-ancestor and a list can convert a meta-ancestor into a list to add elements.
The ModuleNotFoundError module does not exist
Error message:
-
1ModuleNotFoundError: No module named ‘pandas’
Error Example 1:
-
1import pandas as pd
-
2# Failed to import the file.
Solution: This error is common in two scenarios. First, the module is not downloaded or installed. Second, the called module path is inconsistent with the called module path, etc. PIP install XXX; In the second case, there may be multiple versions of Python on the computer. It is recommended to keep the one that is commonly used.
The FileNotFoundError file does not exist
Error message:
-
1FileNotFoundError: File b’E:\test\test_data.csv’ does not exist
Examples of errors:
-
1pd.read_csv(‘E:\test\test_data.csv’)
-
2# Cause of error: The path contains ‘\t’, which the system mistakenly thinks is a TAB character.
Solution: After ensuring that the written file exists in the path, add ‘r’ to the front of the path to read the file. Or use a double slash ‘\ ‘to escape, such as: ‘E:\ \test\ \test_data.csv’. Occasionally also can happen file name, path really write wrong, make some low-level mistakes.
conclusion
Error reporting is not scary, it is a learning opportunity. Nowadays, search engines are so advanced that if you put the wrong information in, you can find all kinds of solutions.