These holes in Python are early to avoid.

This is enough to cover the pits encountered in Python

Do not use lists when passing parameters

def foo(num,age=[]):
    age.append(num)
    print("num",num)
    return age
print(foo(1))
print(foo(2))
print(foo(3))
Copy the code

The output from the above code is not what we expected, printing three arrays [1],[2],[3]. It’s going to look like this.

num 1
[1]
num 2
[1, 2]
num 3
[1, 2, 3]
Copy the code

The reason for this is that the age argument is a list, which is a mutable object, and when used as a function argument, it acts as a global variable, allocating memory during the function preprocessing. So how do we fix it? None is given as a list by default. If the object is null, define it as a list.

def foo(num, age=None):
    if not age:
        age = []
    age.append(num)
    print("num", num)
    return age
print(foo(1))
print(foo(2))
print(foo(3))
Copy the code

The for… Else usage scenarios

Pythontip: pythontip: pythontip: pythontip: pythontip: pythontip: pythontip: pythontip Print all primes up to 100, separated by a space (note that there is no space after the last number).

# In the general field, if the positive integer n is divided by all integers between 2 and the square root of n, it cannot be divisible, then n is prime.
import math

num = [] # store primes between 1 and 100
for i in range(2, 100):
    for j in range(2, int(math.sqrt(i)) + 1):
        if i % j == 0:
            break
    else:
        num.append(i) # Join if none of them works by definition
for index, i in enumerate(num):
    if index == len(num) - 1:
        print(i)
    else:
        print(i, end="")
Copy the code

According to the key statement “if all integers are divided and cannot be divisible, n is a prime number, also known as a prime number. To the program, which means that all the numbers are looped out before they’re prime, and that else at the end, shows that. A. for B. for C. for D. for Else is pretty important.

The dictionary assignment

Look at the following code and guess the output:

a = {}
a[1] = "A"A = [1.0]"B"
a[2] = "C"
print(a)
Copy the code

If you didn’t know that the keys in the dictionary were related to hash, you wouldn’t know that the result would look like this

{1: 'B', 2: 'C'}
Copy the code

Why is that? Because dictionaries in Python determine whether two keys are the same by checking for equality and hash values. Immutable objects with the same value always have the same hash value in Python. Hash (1)==hash(1.0) since 1=1.0. Similarly we know that true is equal in Python, so if we try to compute the hash value we can see that hash(1)==hash(true). From this we can get the following equation:

hash(1) = =hash= = (1.0)hash(True)
Copy the code

Since only immutable objects have hash values, hash([]) does not exist. We can also infer that

hash= = (0)hash(False) == hash("")
Copy the code

According to article 6 of the Review section of PEP285, bool is actually inherited from int.

print(isinstance(True, int))
Copy the code

The correct way to write the if judgment condition

Python3 0=[]=()={}=None=False=””, so we don’t use a==None when we’re trying to determine if a list or dictionary string is empty.

a=[]
b={}
c=""
if not a:
   print("A is not empty")
if not b:
   print("B is not empty")
if not c:
   print("C is not empty")
Copy the code

Write less of the same code

In general, when we write if judgments, we write them like this:

if type= ="A":
    print(1)
elif type= ="B":
    print(2)
Copy the code

We need to write a lot of repetitive code programs like this, this time to consider whether to optimize, for this case we can give priority to the dictionary.

my_dict = {"A": 1,"B"2} :#etc
print(my_dict[type])
Copy the code

In addition, when we use the attribute assignment to the object

class A():
    def __init__(self,dicts):
        self.name=dicts["name"]
        self.age=dicts["age"]
        self.sex=dicts["sex"]
        self.hobby=dicts["hobby"]
if __name__ == '__main__':
     dicts={"name":"lisa"."age": 23."sex":"women"."hobby":"hardstyle"}
     a=A(dicts)
Copy the code

We see that we need to exchange each key value of the dictionary passed in and create a property with the same name as the key value. Here we only have 4 keys. How w is still such an assignment dare not think dare not think, somebody else has written the code, you are still assigning a value. In fact, the original piece of code already provides the answer, but if it doesn’t, it doesn’t matter, so let’s start with Pythonic python. To solve this problem. The above code is simplified as:

class A():
    def __init__(self,dicts):
        self.__dict__.update(dicts)
        print(self.__dict__)

if __name__ == '__main__':
     dicts={"name":"lisa"."age": 23."sex":"women"."hobby":"hardstyle"}
     a=A(dicts)
Copy the code

Beware of holes in closures, lazy computation in Python

Let’s look at the following code

ls = []
for x in range(5):
    ls.append(lambda: x**2)
print(ls[0]())
print(ls[1]())
print(ls[2]())
Copy the code

We thought it would print [0],[1],[4].

16
16
16
Copy the code

What the hell is this? It has to do with lazy evaluation in Python. Lazy evaluation, or lazy evaluation, is when an expression is not evaluated immediately after it is bound to a variable, but when it is used. X is not really in the scope of lambda. Only when lambda is called will the value of x be passed to it. In the last loop x is 4,ls[1],ls[1],ls[2],ls[3] are actually 16. At the same time, this is a common interview test point, I hope you keep in mind. This question examines closures.

Execute file path and current path

Execute file path and current path These are two concepts that can be used to get the current path of a file

import os
os.getcwd()
Copy the code

However, it is best not to use this method when obtaining the execution path of the file that needs to be executed. Generally, the following approach is used to obtain the path dynamically

import sys
sys.path[0]
Copy the code

You can’t have a 0 before a number when using eval

eval(".")
Copy the code

An error occurs:

Traceback (most recent call last):
  File "/demo/1.py", line 1, in <module>
    eval(".")
  File "<string>", line 1
    02
     ^
SyntaxError: invalid token
Copy the code

While 1 is faster than While True?

Python2, thought python3 True=1 so it’s actually the same. Since True/False is not a keyword in Python2, we can assign it arbitrarily, which causes the program to check for True/False values every time through the loop; For 1, it is optimized by the program and never checked again. In Python3, since True/False is already a keyword, reassignment is not allowed, so the result is no different from while 1

Handling long strings

For long string we usually use “”,” text “more” “in the form of, but where is easy to cause error when a new line, at this time can consider to add a little outside parentheses, like this

("""Multitext""")
Copy the code

Coding questions about the Requests module

The author actually provides a code that automatically recognizes the web page code, using the following code to obtain the correct web site code before obtaining the RES (requested object) source code.

res.encoding=res.apparent_encoding
Copy the code

For more tools and python tips, please visit the public account: Python Learning and Development.

If you like my article do not prevent moving small hands forward a wave, thank you. Click to read the original article to enter my blog garden, see the code more convenient. Because the number of people is more than 100, we need to add my wechat account: Italocxa, and then pull you into the group.