Home Backend Development Python Tutorial Summary of several mistakes that Python novices often make

Summary of several mistakes that Python novices often make

Apr 20, 2017 am 09:11 AM
python Beginner'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
Copy after login

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
Copy after login

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和==好像是一样的
Copy after login

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,看二者不一样了吧
Copy after login

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,看二者不一样了吧
Copy after login

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
Copy after login

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
Copy after login

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)]
Copy after login

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
Copy after login
  • 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 of this Website
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

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

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1670
14
PHP Tutorial
1274
29
C# Tutorial
1256
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Golang vs. Python: Performance and Scalability Golang vs. Python: Performance and Scalability Apr 19, 2025 am 12:18 AM

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

See all articles