Python control process inventory and advanced usage, mysterious skills revealed!

In this article, we will give a comprehensive and in-depth introduction to Python's control flow, including key parts such as conditional statements, loop structures, and exception handling, especially advanced usages such as list comprehension, generators, and decorators. In addition, I will share some unique insights and research findings, hoping to bring you new inspiration. At the end of the article, we will have a "One More Thing" segment where I will share a very special but little known useful trick of Python control flow.

 

1. Conditional statement (If-Elif-Else)

A conditional statement in Python is a code block that is determined to be executed by the execution result (True or False) of one or more statements. The basic forms of conditional statements include if, if-else and if-elif-else.

# if 语句
x = 10
if x > 0:
    print("x is positive")

# if-else 语句
if x % 2 == 0:
    print("x is even")
else:
    print("x is odd")

# if-elif-else 语句
if x < 0:
    print("x is negative")
elif x == 0:
    print("x is zero")
else:
    print("x is positive")

 Pay attention to Python's indentation rules, which is a major feature of Python syntax. Indentation is used to distinguish code blocks, such as the code block of if-elif-else above. In addition, Python does not have curly braces {} similar to C++ and Java to control statement blocks, and relies entirely on indentation.

2. Loop structure (For and While)

There are two kinds of loops in Python, one is for loop and the other is while loop.

1 # for循环
2 for i in range(5):
3     print(i)
4 
5 # while循环
6 count = 0
7 while count < 5:
8     print(count)
9     count += 1

Python's for loop is more like a traversal loop, it will traverse each element in the sequence. In many other languages, the for loop controls the loop through conditional judgment. The range() function in Python is very useful in many situations, especially in looping structures.

3. Exception handling (Try-Except)

In Python, we can use try-except statement to handle possible errors or exceptions.

try:
    print(1 / 0)
except ZeroDivisionError:
    print("You can't divide by zero!")

Python's exception handling mechanism is a powerful tool that helps us keep our programs running when errors or exceptions occur. Not only that, Python's exception handling also supports multiple except clauses, so that we can handle different types of exceptions differently. In addition, we can also use the finally clause, regardless of whether an exception occurs, the code in the finally clause will always be executed, often used for cleanup.

 Fourth, the advanced usage of the control process!

Python's control flow is not limited to simple conditional judgments, loops, and exception handling. Python also has many advanced control flow tools that can help us write code more efficiently and concisely. Here are some common advanced control flow tools:

1. List comprehension

List comprehensions are a neat way to create lists that do things like loops and conditionals in one line of code. Here is an example of a list comprehension:

squares = [x**2 for x in range(10)]

The above code produces a list of squares from 0 to 9. The process of this list comprehension can be understood as: for each `x` in `range(10)`, calculate the square of `x`, and then add the result to the list. Compared with ordinary loop statements, list comprehension not only has more concise code, but also executes faster. This is because list comprehensions implement optimizations internally, while ordinary loop statements do not.

2. Generator expressions

A generator expression is similar to a list comprehension, but it produces a generator object instead of an actual list. A generator object is an iterable object that produces new values ​​each iteration rather than all values ​​at once. The following is an example of a generator expression:

squares = (x**2 for x in range(10))

The above code creates a generator object that produces a square number on each iteration. You can iterate over this object with the `next()` function or a `for` loop. Generator expressions are more memory efficient than list comprehensions because they don't need to generate all the values ​​at once. This is very useful when dealing with large-scale data.

3. Decorator 

Decorators are a very powerful tool that allow us to modify the behavior of a function or class without changing its source code. Here is a simple decorator example:

 1 def my_decorator(func):
 2     def wrapper():
 3         print("Something is happening before the function is called.")
 4         func()
 5         print("Something is happening after the function is called.")
 6     return wrapper
 7 
 8 @my_decorator
 9 def say_hello():
10     print("Hello!")
11 
12 say_hello()

The above code defines a decorator `my_decorator`, which will print a message before and after calling the `say_hello` function. `@my_decorator` is how the `say_hello` function is decorated with `my_decorator`. Decorators can be used to do many things, such as logging, performance testing, transaction handling, caching, and more. In many cases, using decorators can make our code cleaner, easier to manage and reuse.

One More Thing!!

While reading GitHub and various technical blogs, I discovered a very special but little known Python control flow trick - using `else` clauses in `for` and `while` loops.

Many of you may not know that `for` loops and `while` loops can have an optional `else` clause which is executed when the loop normally ends. If the loop is terminated by a `break` statement, the `else` clause will not be executed.

 1 for i in range(5):
 2     print(i)
 3 else:
 4     print("Loop finished!")
 5 
 6 count = 0
 7 while count < 5:
 8     print(count)
 9     count += 1
10 else:
11     print("Loop finished!")

This feature is very useful in many situations. For example, we search for an element in a loop. If we find an element, we terminate the loop through the `break` statement. If the loop ends normally and the element is not found, execute the code in the `else` clause.

Finally, I would like to thank everyone who has read my article carefully. Seeing the fans’ growth and attention all the way, there is always a need for reciprocity. Although it is not a very valuable thing, you can take it away if you need it:

​These materials should be the most comprehensive and complete preparation warehouse for [software testing] friends. This warehouse has also accompanied tens of thousands of test engineers through the most difficult journey. I hope it can help you too!

Software Testing Interview Questions

The software test question bank maxed out by millions of people! ! ! Who is who knows! ! ! The most comprehensive quiz mini program on the whole network, you can use your mobile phone to do the quizzes, on the subway or on the bus, roll it up!

The following interview question sections are covered:

1. Basic theory of software testing  , 2. web, app, interface function testing, 3. network, 4. database, 5. linux 6. web,
app, interface automation, 7. performance testing  , 8. programming basics, 9. hr Interview questions, 10, open test questions, 11, security test, 12, computer basics

This is in my QQ technology exchange group (technical exchange and resource sharing, do not disturb the advertisement)

You can join the group and take it away for free. There are also fellow masters to exchange technology together

method of obtaining:

Guess you like

Origin blog.csdn.net/qq_56271699/article/details/131231853