Ten knowledge points of Python grammar

Time:2020-7-29

Python is a language representing simple ideas. Its syntax is relatively simple and easy to use. However, it would be a big mistake to belittle the subtlety and profundity of Python syntax. This paper carefully selects the ten knowledge points that can show the best Python syntax, and attaches the detailed example code. If we can understand and use it flexibly in actual combat, it will certainly make the code more refined and efficient. At the same time, it will greatly improve the code B grid, making it look more sophisticated and elegant to read.

1. for – else

what? Isn’t if and else the original? No, you may not know that else is a two legged guy, and for and else are a couple, and they are legal. B grammar, for – else is definitely the south of the bay! If you don’t believe it, please see:

>>> for i in [1,2,3,4]:
	print(i)
else:
	Print (I, 'I'm else')
	
1
2
3
4
I'm else

If there is a third if interposition between for and else, the relationship between for and else will not be affected. Because the level of for is higher than if, else is a guy who clings to power, and doesn’t care whether there is an if and whether a statement satisfying the if condition is executed. Else’s eyes are only for. As long as the for is successfully implemented, else will run again and again

>>> for i in [1,2,3,4]:
	if i > 2:
		print(i)
else:
	Print (I, 'I'm else')

3
4
I'm else

So, how to break up for and else? The else statement is skipped only if the for loop is interrupted by a break statement:

>>> for i in [1,2,3,4]:
	if i>2:
		print(i)
		break
else:
	Print (I, 'I'm else')

3

2. One star (*) and two stars (* *)

Have you found that star (*) is really a magic symbol! Think about it, without it, what is the fun of C language? Similarly, because of it, python will be so graceful, graceful and charming! Python functions support default parameters and variable parameters. One star represents an unlimited number of single valued parameters, and two stars represent unlimited number of key value pair parameters.

Let’s give an example: design a function to return the sum of multiple input values. Although we can make a list of these input values and pass them to the function, this method is far less elegant than using the variable parameters of a star


>>> def multi_sum(*args):
	s = 0
	for item in args:
		s += item
	return s

>>> multi_sum(3,4,5)
12

Python functions allow fixed parameters, default parameters, single value (one star) variable parameters and key value pair (two stars) variable parameters at the same time, which must be written in the above order.

>>> def do_ Something (name, age, gender ='male ', * args, * * kwds):
	Print ('name: s, age: D, gender: s'% (name, age, gender))
	print(args)
	print(kwds)

>>> do_ Something ('xulive ', 50,' male ', 175, 75, math = 99, English = 90)
Name: xuvive, age: 50, gender: Male
(175, 75)
{'math': 99, 'english': 90}

In addition, one star and two stars can also be used to unpack lists, tuples and dictionaries, which look more like C language


>>> a = (1,2,3)
>>> print(a)
(1, 2, 3)
>>> print(*a)
1 2 3
>>> b = [1,2,3]
>>> print(b)
[1, 2, 3]
>>> print(*b)
1 2 3
>>> c = {'name':'xufive', 'age':51}
>>> print(c)
{'name': 'xufive', 'age': 51}
>>> print(*c)
name age
>>> print('name:{name}, age:{age}'.format(**c))
name:xufive, age:51

3. Ternary expression

Programmers familiar with C / C + + will miss the classic ternary operators when they first start python, because it seems more troublesome to write in Python if they want to express the same idea. For example:

>>> y = 5
>>> if y < 0:
	Print ('y is a negative number ')
else:
	Print ('y is a non negative number ')

Y is a nonnegative number

In fact, python supports ternary expressions, but it’s a little weird. It’s similar to Shandong people’s speech. For example, Shandong people like to use inversion sentence: play ball, if it doesn’t rain; if it rains, we’ll go to the study room. It is translated into a ternary expression

If it doesn’t rain, else go to the study room

Let’s take a look at the specific use of ternary expressions:

>>> y = 5
>>>Print ('y is a negative number 'if y < 0 else' y is a non negative number ')
Y is a nonnegative number

Python’s ternary expression can also be used to assign values:


>>> y = 5
>>> x = -1 if y < 0 else 1
>>> x
1

4. with – as

The word with is not difficult to translate in English, but I can’t think of how to translate it in Python syntax. It’s basically a context management protocol. As a beginner, do not pay attention to the various methods and mechanisms of with, just need to understand its application scenarios. The with statement is suitable for some tasks that need to be prepared in advance and need to be processed afterwards, such as file operation, which needs to open the file first and close the file after the operation is completed. If you don’t use with, file operations are usually like this:


fp = open(r"D:\jb51\Column\temp\mpmap.py", 'r')
try:
 contents = fp.readlines()
finally:
 fp.close()

If you use with – as, it is much more elegant:


>>> with open(r"D:\jb51\Column\temp\mpmap.py", 'r') as fp:
	contents = fp.readlines()

5. List derivation

In all kinds of strange syntax, list derivation should be the most frequently used, and the effect of code simplification is also very obvious. For example, to find the square of each element in the list, it should be written as follows (of course, there are other writing methods, such as using the map function)


>>> a = [1, 2, 3, 4, 5]
>>> result = list()
>>> for i in a:
	result.append(i*i)

>>> result
[1, 4, 9, 16, 25]

If you use the list derivation, it looks much more comfortable:


>>> a = [1, 2, 3, 4, 5]
>>> result = [i*i for i in a]
>>> result
[1, 4, 9, 16, 25]

In fact, derivations support not only lists, but also objects such as dictionaries, sets, tuples, etc. If you are interested, you can study it yourself. I have a blog post, “what kind of insanity can a line of Python code do?”? 》The examples in it are all implemented by list derivation.

6. Various operations of list index

Python introduces negative integers as indexes of arrays, which is definitely a big rush. Think about it. In C / C + +, if you want the last element of an array, you must first get the length of the array, subtract one and then do the index, which seriously affects the consistency of thinking. The success of Python language, I personally think, among many factors, the convenience of list operation can not be ignored. Take a look at:


>>> a = [0, 1, 2, 3, 4, 5]
>>> a[2:4]
[2, 3]
>>> a[3:]
[3, 4, 5]
>>> a[1:]
[1, 2, 3, 4, 5]
>>> a[:]
[0, 1, 2, 3, 4, 5]
>>> a[::2]
[0, 2, 4]
>>> a[1::2]
[1, 3, 5]
>>> a[-1]
5
>>> a[-2]
4
>>> a[1:-1]
[1, 2, 3, 4]
>>> a[::-1]
[5, 4, 3, 2, 1, 0]

If you are familiar with these things and use them frequently, you will feel amazing in the following usage:


>>> a = [0, 1, 2, 3, 4, 5]
>>> b = ['a', 'b']
>>> a[2:2] = b
>>> a
[0, 1, 'a', 'b', 2, 3, 4, 5]
>>> a[3:6] = b
>>> a
[0, 1, 'a', 'a', 'b', 4, 5]

7. Lambda function

Lambda sounds very tall, but actually it is anonymous function (students who know JS must be familiar with anonymous function). What are the scenarios for anonymous functions? It is only used in the place where anonymous functions are defined, which can not be used in other places, so there is no need to give it a cat and dog name. The following is an anonymous function for summation. There are two input parameters, X and Y. the body of the function is x + y, and the return keyword is omitted.

>>> lambda x,y: x+y
<function <lambda> at 0x000001B2DE5BD598>
>>>(lambda x, Y: x + y) (3,4) ා because the anonymous function has no name, it should be enclosed in brackets

Generally, anonymous functions are not used alone, but cooperate with other methods to provide built-in algorithms or judgment conditions for other methods. For example, when sorting a multidimensional array or dictionary using the sorting function sorted, you can specify the collation.

>>> a = [{'name':'B', 'age':50}, {'name':'A', 'age':30}, {'name':'C', 'age':40}]
>>>Sorted (a, key = lambda x: x ['name '])
[{'name': 'A', 'age': 30}, {'name': 'B', 'age': 50}, {'name': 'C', 'age': 40}]
>>>Sorted (a, key = lambda x: x ['age '])
[{'name': 'A', 'age': 30}, {'name': 'C', 'age': 40}, {'name': 'B', 'age': 50}]

Let’s take another example of square of array elements. This time, we use the map function:


>>> a = [1,2,3]
>>> for item in map(lambda x:x*x, a):
	print(item, end=', ')

1, 4, 9, 

8. Yield and generators and iterators

The word yield is not easy to translate. It’s useless to turn to a dictionary. I might as well read it as “one love”, which is a foreign word. To understand yield, you need to know the generator first. To understand a generator, you need to know an iterator. Ha ha ha ha, are you dizzy? Forget it. I’ll just talk in vernacular.

In the py2 era, range() returns a list, but if range (10000000) is used, it will consume a lot of memory resources. Therefore, py2 creates an xrange() to solve this problem. PY3 only retains xrange (), but writes range(). What xrange () returns is an iterator that can be traversed like a list, but does not take up much memory. Generator is a kind of special iterator, which can only be traversed once. When the traversal is finished, it will disappear automatically. In short, both iterators and generators are designed to avoid using lists, thus saving memory. So, how do you get iterators and generators?

Python has built-in iterator function ITER, which is used to generate iterators


>>> a = [1,2,3]
>>> a_iter = iter(a)
>>> a_iter
<list_iterator object at 0x000001B2DE434BA8>
>>> for i in a_iter:
	print(i, end=', ')

1, 2, 3,

Yield is used to construct generators. For example, we want to write a function that returns the square of all integers from 0 to a positive integer. The traditional code writing method is as follows:


>>> def get_square(n):
	result = list()
	for i in range(n):
		result.append(pow(i,2))
	return result

>>> print(get_square(5))
[0, 1, 4, 9, 16]

However, if you calculate the square of all integers within 100 million, the memory cost of this function will be very high. This is yield, and you can show your skill


>>> def get_square(n):
	for i in range(n):
		yield(pow(i,2))

>>> a = get_square(5)
>>> a
<generator object get_square at 0x000001B2DE5CACF0>
>>> for i in a:
	print(i, end=', ')

0, 1, 4, 9, 16, 

If you traverse it again, there is no output.

9. Decorator

Just to understand iterators and generators, here comes another decorator. Why are there so many Python devices? Indeed, python provides us with a lot of weapons, and decorators are one of the most powerful weapons. Decorators are very powerful. I try to use a simple example to illustrate the usage and manufacturing process of decorators from the perspective of demand.

If we need to define many functions and display the running time of each function, there are many solutions. For example, read the time stamp of each function before and after the end of each function. However, these two methods are not as simple and elegant as decorators. The following example shows this very well.

>>> import time
>>> def timer(func):
	def wrapper(*args,**kwds):
		t0 = time.time()
		func(*args,**kwds)
		t1 = time.time()
		Print ('time consuming% 0.3f '% (t1-t0,))
	return wrapper

>>> @timer
def do_something(delay):
	Print ('function do_ Something starts')
	time.sleep(delay)
	Print ('function do_ Something ends')

	
>>> do_something(3)
Function do_ Something begins
Function do_ Something over
Time consuming 3.077

Timer () is our defined decorator function, which can be attached to any function (such as do) by using @_ Before the definition, it is equivalent to taking the newly defined function as the input parameter of decorator function. Run do_ The function of something() can be interpreted as the execution of timer (do)_ something) 。 Although the details are complex, but this understanding will not deviate too much, and it is easier to grasp the manufacture and use of decorators.

10. Clever use of assertion assert

The so-called assertion means that the Boolean value of an expression must be true, otherwise an assertion error exception will be triggered. Strictly speaking, assert is a debugging method, which should not be used in the production environment. However, it does not affect the realization of some specific functions by assertions, such as the format of input parameters, type verification, etc.

>>> def i_want_to_sleep(delay):
	Assert (isinstance (delay, (int, float)),'function parameter must be integer or floating point number '
	Print ('Start sleeping ')
	time.sleep(delay)
	Print ('wake up ')

	
>>> i_want_to_sleep(1.1)
Start sleeping
I wake up
>>> i_want_to_sleep(2)
Start sleeping
I wake up
>>> i_want_to_sleep('2')
Traceback (most recent call last):
 File "<pyshell#247>", line 1, in <module>
 i_want_to_sleep('2')
 File "<pyshell#244>", line 2, in i_want_to_sleep
 Assert (isinstance (delay, (int, float)),'function parameter must be integer or floating point number '
Assertionerror: function argument must be an integer or floating-point number

This is the ten knowledge points about Python syntax. I hope you can support developpaer more.