Those overlooked core features of Python...

The most practical, the simplest, and the most beautiful... In recent years, the enthusiasm for learning Python has never subsided; whether it is data analysis or scientific computing, Python is indispensable.

Python did not disappoint either. A program written in 100 lines of code in Java can be done in ten lines of Python!

When you want to say Hello World, C language, Java, and Python are like this:

picture

At a glance, Python is just one line!

While Python is remarkably easy to learn, many practitioners only scratch the surface, neglecting to delve into the more advanced and powerful aspects of the language that make it so unique and powerful. ——Excerpt from "Fluent Python"

(Photo: Stefan Steinbauer)

If your goal is to become an experienced Python programmer, you definitely want to know more. Therefore, let us understand the core functions of Python that you have never heard of, starting with the simplest permutations and combinations...

Function 1: Arrangement and combination

You can combine different for loops, output permutations, combinations and cartesian products etc.

1. Arrangement

For example: when you enter {[1,2,3], 2} in the permutation function, the following results will be output:

picture

2. Combination

When you enter ('ABC', 2) in the combine function, the output is arranged like this:

picture

3. Cartesian product

The Cartesian product is an operation in mathematics used to find all possible ordered pairs of two sets.

When we calculate Python with the Cartesian product, the result is this:

picture

Function 2: variable parameter default value

Now, start increasing the difficulty...

When you call the fib_memo function every time without assigning a value to the memo parameter, it will automatically use the original value when the function was defined. The formula and code are as follows:

picture

Since in Python, the default parameters are variable, you can also execute the function multiple times in a single script like in a "for loop", and each execution can automatically increase the Fibonacci number to be calculated without Will exceed the "maximum recursion depth" limit, because the memo can continue to expand.

*important hint:

Keep in mind that while mutable default arguments (as above) can reduce code, it can create bugs that are hard to fix. Some judged it a "gotcha" rather than a feature. Therefore, you still need to adhere to the Zen revealed in Python: explicit is better than implicit.

As pointed out in the Hacker news: if n not in memo is easier to read than if not n in memo, but the output is the same.

Function 3: Walrus operator

Next, let's talk about the more interesting "walrus operator"...

"Walrus operator" is an assignment expression operator introduced in Python 3.8, which is used to perform assignment operations in expressions, and its symbol is ":=". The symbol is a bit like the eyes and tusks of a walrus (hence the name "walrus operator").

It can be translated into English "whale calculus", which is a special operator based on the grammar rules of words, which is used to define the language modeling method of expressions and a series of operation steps.

picture

Obviously, in Python, assignment and checking whether the return value contains a truth value is much easier:

picture

Function 4: Single asterisk (*) and double asterisk (**)

Use (*) to decompress arguments or keyword arguments before passing them to the function, let's use it in code like this:

picture

When the sum_numbers function is called without unpacking my_numbers, a "TypeError" is raised because the function requires two separate arguments as input to output the result.

However, by using (*), we can unpack the values ​​in the my_numbers function and pass them as separate arguments, resulting in the correct output.

This unpacking technique works not only for tuples and lists, but also for dictionaries.

When keywords are used as parameters, we can use double asterisks (**), take the following code as an example:

picture

As well as unpacking a sequence to pass it as an argument to a function, you can use it to create a new sequence, for example:

picture

During this process, the original list of numbers is unaffected, and you will also have a new_list_numbers variable that contains a copy of the same list.

picture

Function five: any and any

Any and all are built-in functions in python. They operate on iterable objects (such as lists, tuples, or collections) and return them in the form of Boolean operations based on the elements in the iterable objects. The statements are as follows:

picture

You can use the any and all functions with list comprehensions, which return an iterable object and pass it as an argument to the all function:

picture

or any function:

picture

The following table lists the difference in the output of any and all function assignments in iterable objects:

picture

Function 6: Exchange variables

In Python, you can combine parameter packing (to the right of the (=) sign) and unpacking (to the left of the (=) sign), and use this feature to swap variables:

picture

Function 7: str vs repr

There is a difference between str() and repr() in Python when it comes to string handling. str() converts the value into front-end style text, and repr() is the underlying code of the back-end.

  • str() function: convert the value into a form suitable for human reading, facing the user, and the return value is readable and understandable.
  • repr() function: Convert the object into a form that can be read by the interpreter, for developers, and the return value represents the meaning inside the python interpreter.

The image below is a good example:

picture

As you can see, repr() simply arranges the time as a string and outputs it; if you want to determine whether the current variable contains a string or a time object, there is no way to identify it.

str() provides information about the actual object held by the variable, which can be very valuable during debugging.

Function 8: Extended iterative unpacking

Iterative unpacking can be applied to any iterable object, the only rigid requirement is: the number of elements in the iterated object must be consistent with the number of tuple spaces that accept these elements, and an asterisk * can also be used to indicate that redundant elements are ignored .

The advantage of this method is: better assignment and better acquisition of a value in the iterable object (general iterable objects are divided into: tuples, lists, dictionaries, strings, etc.).

If you want to get the first and last value of the sequence, you need to enter the following code:

picture

The same works after replacing the input and output statements...

picture

Other combinations work just as well...

Function Nine: Multiple Context Managers

Usually, we are used to using a context manager at one time. For example, when you open a program file, you need to enter the following code:

picture

However, in Python, multiple files can be opened with a single statement. If you want to write lines to other files, it's easy to do it with Python statements, for example:

picture

Function ten: debug program

For debugging purposes, we can output a large number of variables in the file or simply use the Python debugger (pdb), which can help us set breakpoints:

picture

The program will stop at the breakpoint where you can get any variable to check its value or if that particular breakpoint exists. When the program encounters a breakpoint, the following commands can be used:

  • n or next: Execute the next line.
  • s or step: Step into a function call.
  • c or continue: Continue execution until the next breakpoint.
  • l or list: Display the context of the current code.
  • p <expression> or pp <expression>: Print the value of the expression.
  • b <line> or break <line>: Set a new breakpoint on the specified line.
  • h or help: Provide help when using pdb.
  • q or quit: Quit the debugger and terminate the program.

Function 11: Counter in the collections module

The Counter class in the collections module provides a convenience method to count the elements in an iterable:

picture

Function twelve: two cases of using underscore

Underscores are used in two ways in Python: to separate multiple digits or to exclude unwanted values.

1. Exclude unwanted values

The underscore _ can be used to exclude unwanted values:

picture

2. Multi-digit separator

When dealing with multiple digits, an underscore (_) can be used as a visual separator to enhance readability. This feature was introduced in Python 3.6.

picture

User: simple, practical but limited in scope

picture

On reddit, we found 181 comments from users on this article:

picture

As stated at the beginning of the article, they believe: "The program debugged with Python is really simple and practical."

Having said that, some users also raised doubts: "Pythonic filters and maps are more readable, but limited in scope."

But this does not affect users' love for Python at all!

If you need to develop software, you can take a look at it

The JNPF rapid development platform is a low-code application construction platform developed by Yinmai Information. Through the visual drag and drop method, it takes only 2 hours to complete the development of an application in the traditional mode in 2 weeks with JNPF. To build applications with JNPF, you only need to focus on the business itself. Data storage, operating environment, server, network security, etc., the platform handles everything for you.

Supports connecting to multiple data sources, SQL Server, MySQL, Oracle, PostgreSQL, and is compatible with domestic databases Dameng, Renda Jincang, etc. Application Experience Center: https://www.jnpfsoft.com/?csdn

Written at the end: Python is an essential weapon for you to become a full-stack engineer

Front-end development, back-end development, project testing... If you want to become a qualified full-stack engineer, Python is your indispensable "weapon".

picture

With such an introvert in the development field, to complete a modernization project, one person needs to be in charge of the overall situation. He does not need to be a senior expert in various technologies, but he needs to be familiar with various technologies. For a team, especially an Internet company, people with global thinking are really rare.

Guess you like

Origin blog.csdn.net/wangonik_l/article/details/132145620