Python Fancy Bug collection (long-term update)

Source: Internet
Author: User

Python is a flexible, fun, and versatile language. In recent years, more and more attention has been received. There are more and more people to learn the language.

So, the problem, for beginners, often in the process of writing code, there are such or such errors, resulting in a program run error. These errors are simple, complex, or bizarre, or magical, or scratching, either to make people angry or to be unforgettable. However, in the process of learning programming, it is these mistakes let us grow, let us gradually from the mining pit and then climb the pit, the process of feeling the charm of programming.

What are the errors, please see De8ug brought you the "Python Fancy Error Collection", if you encounter a Python development errors, search for keywords from this article and resolved, it is my pleasure.

Syntax error Chapter indentation Indentationerror

This is a frequent error when copying and pasting code, or unfamiliar with the Python code structure. Code blocks in Python that require the same logic use the same indentation (typically 4 spaces).

Look at this paragraph:

def test():    a = 1    b = 2   return a + b

After running, immediately error

  File "<ipython-input-1-515579e6247e>", line 4    return a + b                ^IndentationError: unindent does not match any outer indentation level

The solution, very simple, is to adjust the indentation to a uniform 4 spaces just fine.

Punctuation SyntaxError

The situation here is more, common for

    • Colon error
    • Comma error
    • Parentheses missing or mismatched

Take a look at the specific error style

 def Test (): Pass File "<ipython-input-2-b5cadef232ad>", line 1 def test (): ^syntaxerror:i Nvalid character in Identifierprint (1,2,3,4,5,6) File ' <ipython-input-3-be45856da7c7> ', line 1 print (1,2,3,4,5,6 ) ^syntaxerror:invalid character in Identifierdef test_a (a): return a * 2def Test_b (b): return B + 3 def test_c (c): Return c-4x = 5test_c (Test_b (test_a)) TypeError Traceback (most recent Call last) <ipython-input-4-af8d9c054419> in <module> () 9 x = 5---> Test_c (test_b (test_a)) &L T;ipython-input-4-af8d9c054419> in Test_b (b) 3 4 def test_b (b):----> 5 return B + 3 6 7 de F Test_c (c): typeerror:unsupported operand type (s) for +: ' function ' and ' int ' # may also be so Test_c (Test_b (Test_a ()) File "<ip Ython-input-5-eab78f53d59a> ", line one Test_c (Test_b (Test_a ()) ^syntaxerror:unexpected EOF While parsing 

Modify the way is very simple, the punctuation in the code is English, there are grammatical errors to check the width of punctuation, my simple notation is the Chinese are relatively fat, English are thin. In addition, the question of parentheses, first of all to English, and secondly, when writing, to develop a kind of first to put into pairs () to write a good habit, and then fill in the content.

Variable Application Naming error

The most need to prohibit is to use Python's own keywords to name, such as list,dict, will cause type errors.

a = (2,5,8)a_list = list(a)  # 第一次可以用list转换list = list(a)  # 如果把list当作变量名,会引起后续代码再用list转换时候报错b = (3,5,7)b_list = list(b)TypeError                                 Traceback (most recent call last)<ipython-input-12-70adb4cffa4f> in <module>()      1 b = (3,5,7)----> 2 b_list = list(b)TypeError: ‘list‘ object is not callable
2b = c  File "<ipython-input-7-9b1de15aaa88>", line 1    2b = c     ^SyntaxError: invalid syntaxa-2 = 1  File "<ipython-input-8-ac5315177c02>", line 1    a-2 = 1           ^SyntaxError: can‘t assign to operator

When naming, it is recommended to use the underscore _ hyphen, or thename, or thename the initial capitalization of the Hump method.
Also, it is not recommended to use 0 (number 0) or L (lowercase l) to name it, otherwise it is easy to use the following error.

Use error

The most common here is the use of easily confusing letters to name, resulting in a time when it seems to be wrong, or when using the wrong variable.

name_l = ‘de8ug‘print(name_1)NameError                                 Traceback (most recent call last)<ipython-input-13-cfee4c383b1a> in <module>()      1 name_l = ‘de8ug‘----> 2 print(name_1)NameError: name ‘name_1‘ is not definedname_0 = ‘de8ug‘print(name_o)---------------------------------------------------------------------------NameError                                 Traceback (most recent call last)<ipython-input-14-7b351863596a> in <module>()      1 name_0 = ‘de8ug‘----> 2 print(name_o)name = ‘de8ug‘print(f‘name‘)print(f‘{de8ug}‘)print(f‘{name}‘)NameError                                 Traceback (most recent call last)<ipython-input-17-22b546a709ce> in <module>()      1 name = ‘de8ug‘      2 print(f‘name‘)----> 3 print(f‘{de8ug}‘)      4 print(f‘{name}‘)NameError: name ‘de8ug‘ is not defined
Coding Error Chapter

Python3, the most common coding error is in a network application, sometimes the data is bytes, but we actually need str, this time we need to convert the code.

It is important to note the conversion of bytes and STR, which encoding=‘utf-8‘ is the default parameter

name = "de8ug"print(type(name))  # strprint(type(name.encode()))  # bytes, S.encode(encoding=‘utf-8‘, errors=‘strict‘) -> bytesname = b"de8ug"print(type(name))  # bytesprint(type(name.decode()))  # str, decode(encoding=‘utf-8‘, errors=‘strict‘) --> str
Import Module Chapter
    • No advance Import

This situation often occurs when using certain modules, but the Py file header forgets to import

json.loads(‘{"name":"de8ug", "city":"beijing"}‘)NameError                                 Traceback (most recent call last)<ipython-input-41-fd9b6a45da38> in <module>()----> 1 json.loads(‘{"name":"de8ug", "city":"beijing"}‘)NameError: name ‘json‘ is not defined

This situation often appears in the learning of some new content, learning (Chao) after the code began to run, found what what did not defined, this time need to check is not import the first problem.

When you join import json , you get the right results{‘name‘: ‘de8ug‘, ‘city‘: ‘beijing‘}

    • Error modulenotfounderror:no module named ' xxx ' when running py file

This is generally the case that the py file you are running needs to import other modules that you define.
But at this point the system does not know which modules exist, the solution is to run the first py file header, add the following code:
This kind of situation applies to have a project item, inside and Bin,conf,app and so on the directory, when the bin inside the py file needs to introduce the module of Conf,app and so on, need to let the system itself know project this directory exists, first have grandfather, then can have grandson Ah.

import osimport sysBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))sys.path.append(BASE_DIR)
function Use Chapter
    • Scope issues

When Python uses variables in functions, it looks for variables in the order of LEGB (local), enclosing (closed), Global (global), built-in (built-in)). If you have an assignment (to a variable of the same name), you need to make sure that the variable already exists under the current scope. Because at this time Python thinks that the function inside and outside has the same name variable, will put the outer shield.

name = ‘de8ug‘def say_name():    print(f‘name is: {name}‘)say_name()  # 这时候正常, name is: de8ugname = ‘de8ug‘def say_name():    name = name.capitalize()  # 把名字大写,并赋值给name    print(f‘name is: {name}‘)say_name()---------------------------------------------------------------------------UnboundLocalError                         Traceback (most recent call last)<ipython-input-37-05a0d34cba37> in <module>()      4     print(f‘name is: {name}‘)      5 ----> 6 say_name()<ipython-input-37-05a0d34cba37> in say_name()      1 name = ‘de8ug‘      2 def say_name():----> 3     name = name.capitalize()  # 把名字大写,并赋值给name      4     print(f‘name is: {name}‘)      5 UnboundLocalError: local variable ‘name‘ referenced before assignment这时候提示错误,name作为局部变量,在赋值前被引用了。因为和外部变量同名,此时name.capitalize()引用name的时候,在函数内部还没有name这个变量的具体内容,所以报错。

How to modify:
Directly referencing an external variable, using the appropriate method, or using a different variable name

print(f‘name is: {name.capitalize() }‘) #  直接打印或cap_name = name.capitalize()

Similarly, this is += equivalent to two operations, = + but, if the function internal variables and functions are the same, there will be a similar error. You feel it:

n = 10def add():    n += 8    print(n)add()---------------------------------------------------------------------------UnboundLocalError                         Traceback (most recent call last)<ipython-input-46-8215b717b8ed> in <module>()      4     print(n)      5 ----> 6 add()<ipython-input-46-8215b717b8ed> in add()      1 n = 10      2 def add():----> 3     n += 8      4     print(n)      5 UnboundLocalError: local variable ‘n‘ referenced before assignment
Summary

OK, at the end of the summary, there are a few common mistakes,

    • Syntax error
    • Variable application
    • Encoding error
    • Import Module
    • function scope

Have you ever made a mistake?

At the end of the conversation, did you solve some of the mistakes you learned in Python? Or, have you encountered any interesting mistakes? Welcome message discussion, chat together.

(starting at the public number < 8th brother Comparisonof time, reprint please indicate the source)

Python Fancy Bug collection (long-term update)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.