Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Ten Classical mistakes of Python3 and their Solutions

2025-02-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the ten classic mistakes and solutions of Python3. The content is very detailed. Interested friends can use it for reference. I hope it will be helpful to you.

I have come into contact with many Python enthusiasts, including beginners and pedestrians. No matter what the purpose of learning Python is, in short, it is great to learn the code written in the early days of Python without reporting errors. Below, Yan Xiaoer lists the ten classic mistakes and solutions of Python3 for you to learn from.

1. SyntaxError syntax error

(1) quotation marks do not appear in pairs

Error message:

SyntaxError:EOL while scanning string literal

Example of error:

String = 'hello world

Solution:

Remember to put the string in quotation marks. Single quotation marks and double quotation marks don't matter. When a string contains single or double quotation marks, it is easy to mismatch quotation marks.

(2) parentheses do not appear in pairs.

Error message:

SyntaxError:unexpected EOF while parsing

Error example 1:

Result = (1024 + (512.2) / 128

Error example 2:

Print ('hello world'

Solution:

Make parentheses appear in pairs. This problem is often encountered when writing complex expressions or calling functions.

(3) incorrect use of the self-operation operator + + or--, etc.

Error message:

SyntaxError:invalid syntax

Example of error:

V = 64 vault +

Solution:

In Python, there are no self-operating operators such as + or-- in C. The use of a similar function is the + = or-= operator. For example, use the following code to increment the variable v by 1.

V + = 1

(4) try to use the equal sign (=) to judge whether the two operations are equal.

Error message:

SyntaxError:invalid syntax

Example of error:

If vs. 64 hello world' 2 print ('hello world')

Solution:

In Python, two equal signs (= =) are used as relational operators to determine whether two operands are equal, and the equal sign (=) is the assignment operator.

(5) incorrect use of Python keywords as variable names

Error message:

SyntaxError: Can`t assign to keyword

Example of error:

False= 1

Solution:

Do not use Python language keywords as variable names, function names, class names, and so on. In the Python Shell window, use the help ('keywords') instruction to view a list of keywords for the Python language.

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

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 (:) at the end of statements such as if/elif/else/while/for/def/class. Remember the grammar rules and practice and tap the code a lot.

(7) incorrect use of Chinese punctuation

Error message:

SyntaxError: invalid character in identifier

Error example 1:

Print ('hello','world') # error cause: comma is Chinese punctuation mark

Error example 2:

For i in range (10): # error cause: colon is a Chinese punctuation mark

Solution:

Except that there can be Chinese in the string, all other cases are edited with English status.

2. IndentationError indentation error message: IndentationError:unindent does not match any outer indentation level IndentationError:expected an indented block

Example of error:

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

Solution:

The code indentation in the body of the while statement in the above code is not aligned. Use indented typesetting codes correctly. This error is more common when the code is copied and pasted from somewhere else.

3. Wrong name of NameError

Name errors occur when a variable name, function name, or class name is miswritten, or when a function is called before it is defined. 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') # error cause: print misspelling

Error example 2:

Sayhi () def sayhi (): pass # error cause: call the function before the function definition.

Error example 3:

Pd.read_excel (ringing file. Xlsx') # error cause: the pandas library was not imported or aliased as pd before calling the pandas method.

Solution:

Correctly write the variable name, function name or class name, assign the value before using the variable, put the definition of the function before the function call, import, switch the package before using the third-party library, and so on. That is, to ensure that a name (identifier) exists before it can be used.

4. Wrong type of TypeError

(1) Integer and string cannot be concatenated

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:

Use the str () function to convert an integer, floating-point, or Boolean value to a string type before concatenating it with a string.

(2) the number of parameters is incorrect or no parameters are passed when calling the function.

Error message:

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

Error example 1:

Input ('enter name', 'age') # error reason: an attempt was made to provide a second argument to the input () function.

Error example 2:

Def say (words): print (words) say () # error cause: no arguments were passed when the function was called.

Solution:

Remember the function usage, understand the parameter definition of the function, and use the correct method to call the function.

5. KeyError key error

This error occurs when you access an element in the dictionary with a key name that does not exist. Error message:

KeyError:'c'

Example of error:

D = {'axiaqizhuang 1 print (d [' c'])

Solution:

When accessing elements in a dictionary, first use the in keyword to detect the existence of the key name to be accessed, or use the dictionary and the get () method to access the dictionary elements securely.

VI. IndexError index error

An index error occurs when the index of the access list is out of range of the list. Error message:

IndexError: list index out of range

Example of error:

A = [1, 2, 3] print (a [3]) # cause of error: the fourth index does not exist in list a. The index of the list is numbered from 0.

Solution:

Get the length of the list through the len () function, and then determine whether the index to be accessed is out of range of the list.

7. UNboundLocalError uninitialized local variable error

In the function, you will encounter this error if you modify an undeclared global variable. Error message:

UnboundLocalError: local variable's referenced before assignment

Example of error:

S = 1 def test (): s + = 1 print (s) test () # error cause: the undeclared global variable s is incremented within the function. # Python treats the variable s as a local variable, but it is not initialized.

Solution:

When using global variables within a function, you can declare them using the global keyword.

8. AttributeError attribute error

Error message:

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

Error example 1:

T = (1) t.append (4) # cause of error: Yuanzu is immutable.

Error example 2:

Df = pd.read_excel (rroomdata.xlsx') df.col # error reason: DataFrame does not have a col attribute, it should be columns.

Solution:

Write the property name of the class correctly and do not make a writing error. Deep understanding of meta-ancestors, the difference between lists, you can convert meta-ancestors into lists to add elements.

IX. ModuleNotFoundError module does not exist

Error message:

ModuleNotFoundError: No module named 'pandas'

Error example 1:

Import pandas as pd # failed to import, the error is reported above.

Solution:

This kind of error report is common in two scenarios: first, the module is not downloaded or installed; second, the path of the module to be called is not consistent with that of the called module. In the first case, you can download and install it directly. In cmd, in the second case of pip install xxx;, there may be multiple versions of Python on your computer. It is recommended to keep a commonly used one.

10. FileNotFoundError file does not exist

Error message:

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

Example of error:

Pd.read_csv ('E:\ test\ test_data.csv') # error cause: the path contains'\ t 'and the system mistakenly thinks it is a tab.

Solution:

After ensuring that the written file does exist under this path, add 'rread' before the read file path to indicate read-only and read as the file path, or use the double slash'\\'to escape, such as'E:\\ test\\ test_data.csv'. Occasionally, the file name and path are indeed miswritten, and some low-level mistakes are made.

It is not terrible to report a mistake, it is an opportunity to learn. Now the search engine is so developed, as long as the error information is put in, a search will come out a variety of solutions.

This is the end of the ten classic mistakes and solutions about Python3. I hope the above content can be helpful to you and learn more knowledge. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report