Getting Started with Python "ten sins" (classic case of error)

Foreword

The following is a beginner Python errors and solutions when too easy to make.

A, SyntaxError Syntax Error

(1) no quotation marks in pairs

Error message:

SyntaxError:EOL while scanning string literal

Examples of errors:

string = 'hello world

Solution:
String remember to put quotes, single quotes, double quotes does not matter. When a string comprising a single or double quotation, quotation unpaired situation prone.

(2) no parenthesis in pairs

Error message:

SyntaxError:unexpected EOF while parsing

Error Example 1:

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

Error Example 2:

print('hello world'

Solution:
the parenthesis in pairs. When writing a complex expression or function call you will often encounter this problem.

(3) from the operator using operator error or ++ - like

Error message:

SyntaxError:invalid syntax

Examples of errors:

v = 64
v++

Solution:
In Python language, no similar language C ++, or the - like from the operating operator. Similarly function or usage is = + - = operator. For example, the following code so that the variable v is incremented by one for operation.

v += 1

(4) tries to use the equal sign (=) is determined two computation are equal

Error message:

SyntaxError:invalid syntax

Examples of errors:

if v=64:
    print('hello world')

Solution:
Use two equal sign (==) is determined as the operation amount is equal to two relational operators, the equal sign (=) is the assignment operator in Python language.

(6) the error using the Python language keywords as variable names

Error message:

SyntaxError: can`t assign to keyword

Examples of errors:

False= 1

Solution:
Do not use the Python language keywords as variable names, function names or class names. In the Python Shell window, use the help ( 'keywords') instructions can view a list of keywords Python language.

(7) forget to add a colon at the end if / elif / else / while / for / def / class statements such as (:)

Error message:

SyntaxError:invalid syntax

Error Example 1:

a = '12345'
for i  in a
    print(i)

Error Example 2:

def sayhi()
    print('Hi')

Solution:
Add a colon (:) to the if / elif / else / while / for / def / class statements and other end. Keep in mind the rules of grammar, practice a lot to knock a lot of code.

(8) the incorrect use of the Chinese punctuation

Error message:

SyntaxError: invalid character in identifier

Error Example 1:

print('hello''world')
# 错误原因:逗号是中文标点符号

Error Example 2:

for i in range(10)# 错误原因:冒号是中文标点符号

Solution:
In addition to the string can be Chinese, no other cases are in English state for editing.

Two, IndentationError indentation errors

Error message:

IndentationError:unindent does not match any outer indentation level
IndentationError:expected an indented block

Examples of errors:

a = 2
while a < 0:
      print('hello')
    a -= 1
else:
    print('0.0')

Solution:
The above code in the body of code indentation while statement are not aligned. Proper use of indentation code. When the code is copied and pasted from other parts of the more common mistakes.

Three, NameError name wrong

When the case of variable names, function names or class names such as clerical error, or a function is called before definition, etc., it can lead to erroneous name.
Error message:

NameError: name 'pirnt' is not defined
NameError: name 'sayhi' is not defined
NameError: name 'pd' is not defined

Error Example 1:

pirnt('hello world')
# 错误原因:print拼写错误。

Error Example 2:

sayhi()

def sayhi():
    pass
# 错误原因:在函数定义之前对函数进行调用。

Error Example 3:

pd.read_excel(r'file.xlsx')
# 错误原因:在调用pandas方法前并未导入pandas库或者并未起别名为pd。

Solution:
correct writing variable names, function names or class names such as first assignment prior to use variables, function calls will be placed before, prior to use third-party libraries to import, transfer package and so-defined functions. Which is to ensure a name (identifier) to exist in order to be used.

Four, TypeError type error

(1) is not an integer and string connection operation

Error message:

TypeError: Can`t convert 'int' object to str implicitly
TypeError: unsupported operand type(s) for + : 'float' and 'str'

Error Example 1:

print('score:'+100)

Error Example 2:

print(9.8 + 'seconds')

Solution:
Before connecting operation integer, floating point, string, or Boolean values, used to str () function to convert it to a string type.

(2) function is called the number of parameters is not correct, or not transmitted parameters

Error message:

TypeError: input expected at most 1 arguments,got 2
TypeError: say() missing 1 required positional argument:'words'

Error Example 1:

input('输入姓名','年龄')
# 错误原因:试图给input()函数提供第2个参数。

Error Example 2:

def say(words):
    print(words)

say()
# 错误原因:调用函数时未传递参数。

Solution:
Remember function usage, understand the parameters defined function, use the correct method to call the function.

Five, KeyError key error

Key name to access the dictionary that does not exist in the elements, this error will occur.
Error message:

KeyError: 'c'

Examples of errors:

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

Solution:
When accessing elements of the dictionary, first detected in the keyword you want to access the key name exists, or use a dictionary and get () method to securely access the dictionary elements.

Six, IndexError index error

When the index exceeds list access list range, the index will be mistakes.
Error message:

IndexError: list index out of range

Examples of errors:

a = [1,2,3]
print(a[3])
# 错误原因:列表a中不存在第4个索引。列表的索引从0开始编号。

Solution:
by len () function to get the length of the list, then the index is determined to be accessed is beyond the scope of the list.

Seven, UNboundLocalError uninitialized local variable error

In the function, if you make changes to a global variable is not declared, will encounter this error.
Error message:

UnboundLocalError: local variable 's' referenced before assignment

Examples of errors:

s = 1

def test():
    s += 1
    print(s)

test()
# 错误原因:在函数内对未声明的全局变量s进行了自增操作。
# Python将变量s视为一个本地的局部变量,但该变量未初始化。

Solution:
When using global variables within a function, use the global keyword can be declared.

Eight, AttributeError property error

Error message:

AttributeError: 'tuple' object has no attribute 'append'
AttributeError: 'DataFrame' object has no attribute 'col'

Error Example 1:

t = (1,2,3)
t.append(4)
# 错误原因:元组不可变。

Error Example 2:

df = pd.read_excel(r'data.xlsx')
df.col
# 错误原因:DataFrame没有col属性,应该为columns。

Solution:
attribute name is correct writing class, clerical errors do not occur. A deep understanding of tuples, the difference of the list, can be converted to a tuple is added to the list of elements.

Nine, ModuleNotFoundError module does not exist

Error message:

ModuleNotFoundError: No module named 'pandas'

Error Example 1:

import pandas as pd
# 没有导入成功,报上面错误。

Solution:
This error is common in both scenarios, the first, is not to download, install the module; second, called the module with the module path is called the path and inconsistent. The first case can download and install directly in the cmd, pip install xxx; there may be multiple versions of the Python computer in the second case, it is recommended to keep a commonly used.

Ten, FileNotFoundError file does not exist

Error message:

FileNotFoundError: File b'E:\test\test_data.csv' does not exist

Examples of errors:

pd.read_csv('E:\test\test_data.csv')
# 错误原因:路径中包含'\t',系统错误地认为是制表符。

Solution:
the existence of files written to ensure that the path in front of the read file path plus 'r', for read-only, read as a file path; or double slash '\' to escape to form such as: 'E: \ \ test \ \ test_data.csv'. Occasionally occurs file name, path did wrong, make some stupid mistake.

Author | Yan small for gestational age
Source | Statistics and Data Analysis combat

Published 29 original articles · won praise 19 · views 1307

Guess you like

Origin blog.csdn.net/s1156605343/article/details/104958720