search
HomeBackend DevelopmentPython TutorialSummary of several mistakes that Python novices often make

Summary of several mistakes that Python novices often make

Apr 20, 2017 am 09:11 AM
pythonBeginner's guide

There are some small pitfalls in the python language, which are particularly easy to confuse and make mistakes. Beginners can easily fall into pitfalls if they are not careful. Below I will give you an in-depth analysis of some of these pitfalls. I hope it will be helpful to beginners. , friends in need can refer to it, let’s take a look below.

Preface

This article mainly summarizes several common mistakes that novices who learn Python make. There are four mistakes in total. Make a mistake, let’s take a look at the detailed introduction below.

1. i+=1 is not equal to ++i

If beginners don’t know much about Python language, and they happen to have c++, java With the language background, it is easy to confuse ++i and i+=1

Let’s look at a small example first:


i=0
mylist=[1,2,3,4,5,6]
while i <len(mylist):
 print(mylist[i])
 ++i

This code will take it for granted that there is no problem. It is a loop output, i keeps +1, which is quite right. In fact, it is not, this code will always output 1, Infinite loop . Because the Python interpreter will operate ++i as +(+i) . + represents a positive sign, and the same is true for --i.


print(+1)
>>>1
print(++1)
>>>1
print(+++1)
>>>1

Now I understand that although ++i is legal in Python syntax, it is not an operation of incrementing as we understand it.

2. Clearly distinguish the usage of == and is

When judging whether strings are equal, beginners especially will confuse is and ==, resulting in such a result The program behaves differently under different circumstances:

For example, let’s look at a simple example:


a=&#39;Hi&#39;
b=&#39;Hi&#39;
print(a is b)
>>>True
print(a==b)
>>>True #看起来is和==好像是一样的

We Look at the second example:


str1=&#39;Wo shi yi ge chi huo&#39;
str2=&#39;Wo shi yi ge chi huo&#39;
print(str1 is str2)
>>>False#is的结果是False
print(str1==str2)
>>>True #==的结果为True,看二者不一样了吧

The third example


str3=&#39;string&#39;
str4=&#39;&#39;.join([&#39;s&#39;,&#39;t&#39;,&#39;r&#39;,&#39;i&#39;,&#39;n&#39;,&#39;g&#39;])
print(str3)
>>>string
print(str3 is str4)
>>>False #is的结果是False
print(str3==str4)
>>>True #==的结果为True,看二者不一样了吧

This is where it is easy to confuse beginners. It feels very strange. Why are sometimes the output of is and == are the same, and sometimes they are different. Let’s find out:

We use the built-in id()This function is used to return the memory address of the object. If you check it, it will be clear.

Summary of several mistakes that Python novices often make

is is the identifier of the object. Use To compare whether the memory spaces of two objects are the same and whether they use the same space address, and == is to compare the contents of two objects Equal.

3. When connecting strings, especially large-scale strings, it is best to use join rather than +

string processing. At times, the most commonly used one is connection. Strings in Python are a little different from other languages. They are immutable objects and cannot be changed once created. This feature will directly affect the efficiency of string connection in Python.

Use + to connect strings:


str1,str2,str3=&#39;test&#39;,&#39;string&#39;,&#39;connection&#39;
print(str1+str2+str3)
>>>test string connection

Use join to connect strings


str1,str2,str3=&#39;test &#39;,&#39;string &#39;,&#39;connection&#39;
print(&#39;&#39;.join([str1,str2,str3]))
>>>test string connection

But if you are connecting large-scale strings, for example, when you want to connect about 100,000 strings, the join method will be much faster (even a hundred times different). For example The following 100,000 string connections.


long_str_list=[&#39;This is a long string&#39; for n in range(1,100000)]

The reason is because you want to connect strings: S1+S2+S3+....+SN, because the string is For an immutable object, a new memory must be applied for once it is executed. In this case, during the process of connecting N strings, N-1 intermediate results will be generated. Each time an intermediate result is generated, a memory must be applied for. This will be serious. Affects execution efficiency.

But join is different. It applies for the total memory at one time, and then copies each element in the string to the memory, so join will be much faster.

Therefore, for string connection,

especially for large string processing, it is best to use join

4. Do not write else blocks after for and while loops

Python provides a feature that many programming languages ​​do not support, that is, you can write an else block directly after the statement block inside the loop. For example:


for i in range(3):
 print(&#39;Loop %d&#39;%i)
else:
 print(&#39;Else block&#39;)
>>>Loop 0
>>>Loop 1
>>>Loop 2
>>>Else block

  • This else block will run

    immediately after the entire loop is executed. If so, why is it called else? Why not call it and? In the if/else statement, else means: if the previous if block is not executed, then the else block is executed.

  • The same is true for try/except/else. The meaning of else in this structure is: if the previous try block does not fail, then execute the else block.
  • try/finally is also very intuitive. Finally here means: after executing the previous try block, the finally block is always executed no matter what.
  • Here comes the problem. Programmers who are new to Python may interpret the else block in the for/else structure as:
If the loop is not executed normally, then execute else piece

.

In fact, just the opposite - Using the break statement in the loop to jump out early will cause the program not to execute the else block , which is a bit confusing. For those who are not familiar with for/else, it will It is quite confusing for people who read the code.

Summary

The above is the detailed content of Summary of several mistakes that Python novices often make. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Merging Lists in Python: Choosing the Right MethodMerging Lists in Python: Choosing the Right MethodMay 14, 2025 am 12:11 AM

TomergelistsinPython,youcanusethe operator,extendmethod,listcomprehension,oritertools.chain,eachwithspecificadvantages:1)The operatorissimplebutlessefficientforlargelists;2)extendismemory-efficientbutmodifiestheoriginallist;3)listcomprehensionoffersf

How to concatenate two lists in python 3?How to concatenate two lists in python 3?May 14, 2025 am 12:09 AM

In Python 3, two lists can be connected through a variety of methods: 1) Use operator, which is suitable for small lists, but is inefficient for large lists; 2) Use extend method, which is suitable for large lists, with high memory efficiency, but will modify the original list; 3) Use * operator, which is suitable for merging multiple lists, without modifying the original list; 4) Use itertools.chain, which is suitable for large data sets, with high memory efficiency.

Python concatenate list stringsPython concatenate list stringsMay 14, 2025 am 12:08 AM

Using the join() method is the most efficient way to connect strings from lists in Python. 1) Use the join() method to be efficient and easy to read. 2) The cycle uses operators inefficiently for large lists. 3) The combination of list comprehension and join() is suitable for scenarios that require conversion. 4) The reduce() method is suitable for other types of reductions, but is inefficient for string concatenation. The complete sentence ends.

Python execution, what is that?Python execution, what is that?May 14, 2025 am 12:06 AM

PythonexecutionistheprocessoftransformingPythoncodeintoexecutableinstructions.1)Theinterpreterreadsthecode,convertingitintobytecode,whichthePythonVirtualMachine(PVM)executes.2)TheGlobalInterpreterLock(GIL)managesthreadexecution,potentiallylimitingmul

Python: what are the key featuresPython: what are the key featuresMay 14, 2025 am 12:02 AM

Key features of Python include: 1. The syntax is concise and easy to understand, suitable for beginners; 2. Dynamic type system, improving development speed; 3. Rich standard library, supporting multiple tasks; 4. Strong community and ecosystem, providing extensive support; 5. Interpretation, suitable for scripting and rapid prototyping; 6. Multi-paradigm support, suitable for various programming styles.

Python: compiler or Interpreter?Python: compiler or Interpreter?May 13, 2025 am 12:10 AM

Python is an interpreted language, but it also includes the compilation process. 1) Python code is first compiled into bytecode. 2) Bytecode is interpreted and executed by Python virtual machine. 3) This hybrid mechanism makes Python both flexible and efficient, but not as fast as a fully compiled language.

Python For Loop vs While Loop: When to Use Which?Python For Loop vs While Loop: When to Use Which?May 13, 2025 am 12:07 AM

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Python loops: The most common errorsPython loops: The most common errorsMay 13, 2025 am 12:07 AM

Pythonloopscanleadtoerrorslikeinfiniteloops,modifyinglistsduringiteration,off-by-oneerrors,zero-indexingissues,andnestedloopinefficiencies.Toavoidthese:1)Use'i

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),