Common errors for beginners in Python
- Forget the colon
- The misuse of =
- Error tighten
- Variable not defined
- Error caused by Chinese and English input method
- Concatenation of different data types
- Index position problem
- Use keys that do not exist in the dictionary
- Forget the brackets
- The leakage parameters
- Missing dependent library
- Python pairs of keywords are used
- Coding problem
Forget to write a colon
Forget to add after the if, elif, else, for, while, def statements:
age = 42
if age == 42
print('Hello! ')
File "<ipython-input-19-4303141d6f97>", line 2
if age == 42
^
SyntaxError: invalid syntax
Copy the code
2. Misuse=
"Have a problem and no one to answer it? We have created a Python learning QQ group: 857662006 to find like-minded friends and help each other. There are also good video tutorials and PDF e-books in the group. ' ' '= 'is an assignment, and' == gender = 'is used to determine whether two values are equal'male'
if gender = 'male':
print('Man')
File "<ipython-input-20-191d01f95984>", line 2
if gender = 'male':
^
SyntaxError: invalid syntax
Copy the code
3. Wrong indentation
Python uses indentation to distinguish blocks of code. Common errors:
print('Hello! ')
print('Howdy! ')
File "<ipython-input-9-784bdb6e1df5>", line 2
print('Howdy! ')
^
IndentationError: unexpected indent
num = 25
if num == 25:
print('Hello! ')
File "<ipython-input-21-8e4debcdf119>", line 3
print('Hello! ')
^
IndentationError: expected an indented block
Copy the code
4. Variables are not defined
"Have a problem and no one to answer it? We have created a Python learning QQ group: 857662006 to find like-minded friends and help each other. There are also good video tutorials and PDF e-books in the group. ''' if city in ['New York', 'Bei Jing', 'Tokyo']: print('This is a mega city') --------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-22-a81fd2e7a0fd> in <module> ----> 1 if city in ['New York', 'Bei Jing', 'Tokyo']: 2 print('This is a mega city') NameError: name 'city' is not definedCopy the code
5. Errors caused by Chinese and English input methods
- In English the colon
- English parentheses
- A comma in English
- Single and double quotation marks in English
If 5>3: print('5 >3 ') File "<ipython-input-46-47f8b985b82d>", line 1 if 5>3: ^ SyntaxError: invalid character in identifier if 5>3: Print ('5 larger than 3 ') File "<ipython-input-47-4b1df4694a8d>", line 2 print('5 larger than 3 ') ^ SyntaxError: Invalid character in identifier spam = [1, 2] File "<ipython-input-45-47a5de07f212>", line 1 spam = [1, 2, 3] ^ SyntaxError: invalid character in identifier if 5>3: Print ('5 larger than 3 ') File "<ipython-input-48-ae599f12badb>", line 2 print('5 larger than 3 ') ^ SyntaxError: EOL while scanning string literalCopy the code
6. Splicing of different data types
String/list/tuple concatenation is supported
Dictionary/collection concatenation is not supported
"Have a problem and no one to answer it? We have created a Python learning QQ group: 857662006 to find like-minded friends and help each other. There are also good video tutorials and PDF e-books in the group. ''' 'I have ' + 12 + ' eggs.' #'I have {} eggs.'.format(12) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-29-20c7c89a2ec6> in <module> ----> 1 'I have ' + 12 + ' eggs.' TypeError: can only concatenate str (not "int") to str ['a', 'b', 'c']+'def' --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-31-0e8919333d6b> in <module> ----> 1 ['a', 'b', 'c']+'def' TypeError: can only concatenate list (not "str") to list ('a', 'b', 'c')+['a', 'b', 'c'] --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-33-90742621216d> in <module> ----> 1 ('a', 'b', 'c')+['a', 'b', 'c'] TypeError: can only concatenate tuple (not "list") to tuple set(['a', 'b', 'c'])+set(['d', 'e']) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-35-ddf5fb1e6c8c> in <module> ----> 1 set(['a', 'b', 'c'])+set(['d', 'e']) TypeError: unsupported operand type(s) for +: 'set' and 'set' grades1 = {'Mary':99, 'Henry':77} grades2 = {'David':88, 'Unique':89} grades1+grades2 --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-36-1b1456844331> in <module> 2 grades2 = {'David':88, 'Unique':89} 3 ----> 4 grades1+grades2 TypeError: unsupported operand type(s) for +: 'dict' and 'dict'Copy the code
7. Index location problem
spam = ['cat', 'dog', 'mouse'] print(spam[5]) --------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-38-e0a79346266d> in <module> 1 spam = ['cat', 'dog', 'mouse'] ----> 2 print(spam[5]) IndexError: list index out of rangeCopy the code
8. Use keys that don’t exist in the dictionary
To access a key in a dictionary object, use [],
But if this key does not exist, this results in: KeyError: ‘Zebra’
"Have a problem and no one to answer it? We have created a Python learning QQ group: 857662006 to find like-minded friends and help each other. There are also good video tutorials and PDF e-books in the group. ''' spam = {'cat': 'Zophie', 'dog': 'Basil', 'mouse': 'Whiskers'} print(spam['zebra']) --------------------------------------------------------------------------- KeyError Traceback (most recent call last) <ipython-input-39-92c9b44ff034> in <module> 3 'mouse': 'Whiskers'} 4 ----> 5 print(spam['zebra']) KeyError: 'zebra'Copy the code
To avoid this, use the GET method
spam = {'cat': 'Zophie'.'dog': 'Basil'.'mouse': 'Whiskers'}
print(spam.get('zebra'))
None
Copy the code
If key does not exist, get returns None by default
9. Forget the parentheses
It is easy to omit parentheses when a function or method is passed in
"Have a problem and no one to answer it? We have created a Python learning QQ group: 857662006 to find like-minded friends and help each other. There are also good video tutorials and PDF e-books in the group. ' ' '
spam = {'cat': 'Zophie'.'dog': 'Basil'.'mouse': 'Whiskers'}
print(spam.get('zebra')
File "<ipython-input-43-100a51a7b630>", line 5
print(spam.get('zebra')
^
SyntaxError: unexpected EOF while parsing
Copy the code
10. Parameters are missed
def diyadd(x, y, z):
return x+y+z
diyadd(1, 2)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-44-7184f3f906ca> in <module>
2 return x+y+z
3
----> 4 diyadd(1, 2)
TypeError: diyadd() missing 1 required positional argument: 'z'
Copy the code
11. Missing the dependency library
There is no relevant library on the computer
12. Use python keywords
Such as try, except, def, class, object, None, True, False, etc
"Have a problem and no one to answer it? We have created a Python learning QQ group: 857662006 to find like-minded friends and help each other. There are also good video tutorials and PDF e-books in the group. ''' try = 5 print(try) File "<ipython-input-1-508e87fe2ff3>", line 1 try = 5 ^ SyntaxError: invalid syntax def = 6 print(6) File "<ipython-input-2-d04205303265>", line 1 def = 6 ^ SyntaxError: invalid syntaxCopy the code
13. File coding problem
import pandas as pd
df = pd.read_csv('Data/Twitter sentiment analysis dataset. CSV')
df.head()
Copy the code
Encoding Is passed to UTF-8, GBK
df = pd.read_csv('Data/Twitter sentiment analysis dataset. CSV', encoding='utf-8')
df.head()
Copy the code
Both encoding is not UTF-8 or GBK, but is not common encoding. We need to pass the correct encoding to run the program.
Python has a chardet library for detecting code.
import chardet
binary_data = open('Data/Twitter sentiment analysis dataset. CSV'.'rb').read()
chardet.detect(binary_data)
{'encoding': 'Windows-1252'.'confidence': 0.7291192008535122.'language': ' '
Copy the code