python process control

1. Comparison operation

For the python language, all objects support comparison operations, which can be used to test equality, relative size, etc. If it is a conforming object (such as: tuple, list), python will check all its parts, including automatically traversing all levels of nested objects until the final result can be obtained. Test operators only need '==' and 'is'.

The '==' operator tests the equality of values

The 'is' expression tests the consistency of the object

Combination condition test: and and operation; or or operation; not non-operation

In [1]: a= 123
In [2]: b=123
In [3]: a==b            #Tests whether the values ​​of a and b are equal
Out[3]: True
In [10]: type(a)is int  #Tests whether a is of type int
Out[10]: True

There are mainly the following ways to represent true and false in python:

1. Any non-zero number and non-empty object are true

2. Number 0, empty object and special object None are false

3. The return value of logical judgment is True or False

2. Selection and loop expressions

  • if statement

if boolean_expression1:
elif boolean_expression2:
elif The statement is optional and can be used when it is only used as a placeholder and does not write related statements pass
  • ternary expression

A = X if Y else Z    Equivalent to  expression1 if bool_expression else expression2
if Y:
  • while loop

while bool_expression:
  • for loop

for expression1 in iterable:

Loop control method:

break: jump out of the innermost loop

continue: jump out of the beginning of the nearest layer loop

else code block: it will be executed when the loop terminates normally, if the loop termination is caused by a break jump out, then the else will not be executed

for i in a:
    if i==3:
        continue    #Jump out of this loop and execute the traversal directly backward
else:                      #The else statement gets executed after the loop ends
[1, 2, 3, 4, 5, 6, 7]

for i in a:
    if i==3:
        break              #break jumps out of the loop and does not perform subsequent traversal
else:                      #else statement is not executed

3. Iterators and list comprehensions

  • For iteration, use the iter() function to create an iterator, and use the __next__() function to take values ​​from the iterator one by one.

An iterator is a way of accessing the elements of a collection. Iterator objects are accessed from the first element of the collection until all elements have been accessed. Iterators can only go forward and not backward. In addition, an advantage of having more iterators is that it is not required to prepare all elements in the entire iteration process in advance. The iterator only calculates an element when it iterates to it, and before or after that, the element does not exist or is destroyed.


The visitor does not need to care about the internal structure of the iterator, but only needs to continuously fetch the next content through the next() method

A value in the collection cannot be accessed randomly, but can only be accessed sequentially from beginning to end

Cannot go back halfway through the visit

It is convenient to loop relatively large data sets and save memory

List comprehension: An application in the python iteration mechanism, which is often used to create a new list, so it is placed in [].

grammar:[expr for iter_var in iterable if cond_expr]
In [1]: range(22,101,2)    #Even numbers from 22 to 101
In [5]: [ x for x in range(1,101) if x%2==0 and x>=20 ]   #Equivalent to range(22,101,2)
In [6]: L = [ x**2 for x in range(9)]   #Squared value from 1 to 9
In [7]: list(L)
Out[7]: [0, 1, 4, 9, 16, 25, 36, 49, 64]

Comparison of range() and xrange():

The range() function returns a continuous list of integers at one time; the xrange() function generates one data at a time, which is more space-saving than range. The xrange() function has been removed in python3.x.

>>> l = range(9)
>>> l
[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> L=xrange(9)
>>> L
>>> list(L)
[0, 1, 2, 3, 4, 5, 6, 7, 8]
  • There are two main types of generators in python: generator functions and generator expressions.

  Generator function: When a function is called and returns an iterator, then this function is called a generator (generator). If this function contains yield syntax, then this function will become a generator; the main function of yield is to make the function Interrupt and save the interrupt status; after the interrupt, the code can continue to execute, and after a while, this function can be called again, starting from the next sentence of the last yield.

def my_range(first=0,last=10,step=1):
    number =first
    while number <last:
        yield number     #yield generator, when number<last, generate number and return output
        number +=step
ranger=my_range(1, 6)        #ranger is the generator object
for x in ranger:
    print(x)                      #After outputting the value obtained from yielded, continue to return to function execution

Generator expressions: Similar to list comprehensions, but generator returns produce an object on demand, rather than building a resulting list one at a time. It is very simple to create a generator expression, just change the [] of the list generation expression to (), you can create a generator expression, and you can get the next return value of the generator expression through the next() function. However, when traversing to the last element, an exception will be thrown when there is no element, so it is generally iterated with a for loop.

In [14]: squ=(x**2 for x in range(4))
In [15]: squ
Out[15]: <generator object <genexpr> at 0x7fb403bc98e0>
In [16]: next(squ)
Out[16]: 0
In [17]: next(squ)
Out[17]: 1
In [18]: next(squ)
Out[18]: 4
In [19]: next(squ)
Out[19]: 9
In [26]: next(squ)
StopIteration                             Traceback (most recent call last)
<ipython-input-26-10dd268618a2> in <module>()
----> 1 next(squ)

4. Decorator

When writing code, follow the principle of openness and closure. Although this principle is used in object-oriented development, it is also applicable to functional programming. It stipulates that the implemented functional code is not allowed to be modified, but it can be extended. which is:

Closed: the implemented function code is fast

Open: external expansion development

The so-called decorator itself is a function used to decorate other functions, and its function is to enhance the function being decorated.

#The function document_it() defines a decorator whose function is:
#Print out the name of the function and the value of the parameter
#print function with parameters
#printout result
#return the modified function

def document_it(func):
    def new_function(*args,**kwargs):
        print('running function:',func.__name__)
        print('positionnal argument:',args)
        print('keyword arguments:',kwargs)
        return result
    return new_function
#Whatever the function func of document_it() is, the decorator returns a new function. This includes the extra statements added by the function. The decorator does not need to execute the code in the function func, just the return result of the function document_it() calling the function func and the additional code result before the end.

There are two main ways to use decorators:

def add_ints(a,b):      #Define a function to find the sum of two numbers
    return a+b

cooler_add_ints=document_it(add_ints)   #The first method: manually assigning values ​​​​to the decorator
Output result:
running function: add_ints
positionnal argument: (3, 5)
keyword arguments: {}
result: 8

@document_it                            #The second method: add the decorator name directly in front of the function to be decorated
def add_ints(a,b):
    return a+b
c=add_ints(3, 5)
Output result:
running function: add_ints
positionnal argument: (3, 5)
keyword arguments: {}
result: 8

5. Enumeration and recursion

  • enumerate

range can be used in incomplete traversal to generate indexes instead of elements at offsets; if you need cheap indexes and elements at the same time, you can use the enumerate() function. This built-in Hansu returns a generator object.

In [3]: for i in range(5):     #Only generate the value of the element
   ...:     print(i)

In [4]: for index,i in enumerate(range(5)):   #generate index and element at the same time
   ...:     print(index,i)
0 0
1 1
2 2
3 3
4 4

In [7]: for index,i in enumerate(a):    #When traversing a list, generate indices and elements
   ...:     print(index,i)
0 1
1 2
2 5
3 67
4 3
5 54
6 756
7 8
8 9
9 35
  • Recursion: A recursive algorithm is a process that directly or indirectly calls its own algorithm

Features: A recursive algorithm is to call itself in a procedure or function. When using the recursive strategy, there must be a clear recursive end condition, which is called the recursive exit; recursive algorithms are usually very simple to solve problems, but their operating efficiency is low. During the process of recursive calls, the system returns Points and local variables open up a stack for storage. Too many recursions can easily cause stack overflow and so on.

#Use a recursive algorithm to find n!
def factorial(n):
    if n==1 or n==0:
        return 1
    else :
        return n*factorial(n-1)
Output result:
This article is reposted from the 51CTO blog of Dreaming into a Daniel, the original link:, if you need to reprint, please contact the original author

Tags: Python

Posted by dream25 on Mon, 09 Jan 2023 10:39:00 +0300