<Python Panoramic Series-3>Python control process inventory and advanced usage, mysterious skills revealed!

Welcome to our blog series "Python Panorama Series"! In this series, we'll take you from the basics of Python to advanced topics, helping you master this powerful and flexible programming syntax. Whether you are new to programming or a developer with a certain foundation, this series will provide the knowledge and skills you need.

This is the third article in the series. 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. In particular, advanced usages such as list comprehension, generators, and decorators Catch them all. In addition, I will also 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:

 def my_decorator(func):
     def wrapper():
          print("Something is happening before the function is called.")
          func()
          print("Something is happening after the function is called.")
      return wrapper
  
  @my_decorator
  def say_hello():
     print("Hello!")
 
 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!!

Reading GitHub and various tech 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.

 for i in range(5):
     print(i)
 else:
     print("Loop finished!")
 
 count = 0
 while count < 5:
     print(count)
     count += 1
 else:
    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.

I hope that after reading this article, you can have a deeper understanding of Python's control flow. If you have any questions or better suggestions, please leave a message below, let's discuss and learn together.

[Get the update information of Python full perspective at the first time, please pay attention to my WeChat official account: Python full perspective ]

Guess you like

Origin blog.csdn.net/magicyangjay111/article/details/130723004