Python code that makes people scream

Python is a beautifully designed interpreted high-level language that provides many features that make programmers feel comfortable. But sometimes, some output results of Python may not seem so obvious to beginners.

If you are a more experienced Python programmer, you can try the challenge to see if you can see the result of the operation at a glance.

only run once?

How many times will the following code run?

for i in range(4):
    print(i)
    i = 10

After running, output:

0
1
2
3

What? Isn't it output  0 ?

Principle analysis:

  • Due to the way loops work in Python, the assignment statement i = 10 does not affect the iterative loop, before each iteration starts, the next element produced by the iterator (range(4) in this case) is unpacked and assigned to the target The variable of the list (here i).

trick-or-treating hash

some_dict = {}
some_dict[5.5] = "Ruby"
some_dict[5.0] = "JavaScript"
some_dict[5] = "Python"
print(some_dict[5.5])
print(some_dict[5.0])
print(some_dict[5])

Output after running:

Ruby
Python
Python

Principle analysis:

  • Python dictionaries determine if two keys are the same by checking if the key values ​​are equal and comparing the hash values.

  • When the statement some_dict[5] = "Python" is executed, the existing value "JavaScript" is overwritten by "Python" because Python recognizes 5 and 5.0 as the same key in some_dict

return everywhere

def some_func():
    try:
        return 'from_try'
    finally:
        return 'from_finally'

print(some_func())

Output after running:

from_finally

Isn't it  from_try ?

Principle analysis:

  • The finally clause is still executed when return, break or continue is executed in the try of a "try...finally" statement.

  • The return value of the function is determined by the last executed return statement. Since the finally clause will definitely be executed, the return in the finally clause will always be the last executed statement.

neither nor nor

print('something' is not None)
print('something' is (not None))

operation result:

True
False

Principle analysis:

  • is not is a separate binary operator, as opposed to using is and not separately.

  • The result of is not is False if the variables on both sides of the operator point to the same object, otherwise the result is True.

From existence to nothing

some_list = [1, 2, 3]
some_dict = {
    "key_1": 1,
    "key_2": 2,
    "key_3": 3
}
some_list = some_list.append(4)
some_dict = some_dict.update({"key_4": 4})
print(some_dict)
print(some_list)

operation result:

None
None

Principle analysis:

  • Most methods that modify sequence/map objects, such as list.append, dict.update, list.sort, etc., modify the object in place and return None.

Same person different life

Let's first look at a program fragment:

a = [1, 2, 3, 4]
b = a
a = a + [5, 6, 7, 8]
print(a)
print(b)

Result after running:

[1, 2, 3, 4, 5, 6, 7, 8]
[1, 2, 3, 4]

Let's look at another program fragment:

a = [1, 2, 3, 4]
b = a
a += [5, 6, 7, 8]
print(a)
print(b)

Result after running:

[1, 2, 3, 4, 5, 6, 7, 8]
[1, 2, 3, 4, 5, 6, 7, 8]

According to conventional understanding, the results returned by these two program fragments should be the same?

Principle analysis:

  • a += b It's not always the  a = a + b same as the representation, the way the class implements the operator operator  = may be different, and that's what lists do.

  • The expression  a = a + [5,6,7,8] produces a new list and makes a  a reference to this new list, while leaving it  b unchanged.

  • The expression  a += [5,6,7,8] is actually using the "extend" function, so the  a sum  b still points to the same list that has been modified.

Summarize

After reading the running results of these codes, did you call WC directly? Give it a thumbs up if you have one!

Even a Python veteran is likely to be fascinated by this code, it is difficult to be completely right. These codes are like logic questions in the line tests, and it is easy to be confused by the surface! But after running, look at the principle, it is also very helpful for us to learn Python!

Here I would like to recommend the Python learning Q group I built by myself: 831804576. Everyone in the group is learning Python. If you want to learn or are learning Python, you are welcome to join. Everyone is a software development party and shares dry goods from time to time ( Only related to Python software development),
including a copy of the latest Python advanced materials and zero-based teaching in 2021 that I have compiled by myself. Welcome to the advanced middle and small partners who are interested in Python! 

Guess you like

Origin blog.csdn.net/BYGFJ/article/details/124140392