Getting started with Python(18)

Getting started with Python (18/18)
**Section XVIII **Differences

Hello everyone! Coming here today, I want to congratulate you, because when you see today's course, it means that you have learned or even mastered most of the basic knowledge of Python technology.

The knowledge you have, if you happen to be able to practice diligently, then they not only exist in your mind, but also become skills in your hands, so that you truly have the technology of Python .

Before you are full of pride, ready to brave the world, and show off your skills, I still want to remind you: There is a sky outside the world, there are people outside the world, and there is a strong middle hand in the strong... Oh, this is a long way. I want to say that the basic knowledge you have learned is probably also learned by most people. So, the problem is that sometimes people can't help but want to show off, so how can they be different?

Yes, that's what it means,

Is it talking about your heart?

Haha! Don't be embarrassed,

in fact,

Everyone is thinking so...

OK, let's share something out of the ordinary today.

1、 Pass tuple

We have been using functions, and, most of the time, our functions return values. However, have you noticed that the return value we get is usually only one.

So the question is, what should I do if I want to return two or more values after the code block of the function is executed? What is the most efficient method?

The answer is: you just need to put them in a bunch of parentheses.

Goodness, it's that simple? Yes. Believe it or not, try writing and running the following code:

**Reminder: **Please note that a, b = The usage of interprets the result of the expression as a tuple with two values. This also means that the fastest way to swap two variables in Python is:

**Okay? It's really cool! **

2、 Magic method

We know that some sequence data types of Python, such as dictionaries, can be indexed by key. So, if we customize a certain class ourselves, we also hope that it can have the ability similar to the key index, can it? Yes!

**The following is a recommended magic method: ** If you want your custom class to also have the function of key indexing (such as x[key] used in lists and tuples), then you only need to include in your class Add the getitem() method. In fact, Python does this for the list class!

3、 Lambda expression

There are lambdas in many high-level programming languages, and lambdas are used to define an anonymous function.

Since it is an anonymous function definition, it would seem a bit superfluous if you insist on giving him a name. Therefore, we usually use lambda functions directly. As follows:

The above code creates an anonymous function by using lambda. This function has two variables x and y. The code block of the function is an equation: x+y. We use it as an object through "equation (assignment)" Symbol, assigned to add. At this time add actually becomes a function object. Therefore, as long as it is passed 2 actual parameters, the sum of them can be calculated.

Does this usage look cool? ! Don't feel it? I'm going... then look at the following example again.

PS: Usually in functional programming, we will use lambda expressions. Python provides many features of functional programming, such as map, reduce, filter, sorted and other functions that support functions as parameters.

4、 List comprehension

List comprehension is used to get a new list from an existing list.

Imagine that now you have a list of numbers and you want to get a corresponding list. The requirement is to multiply the numbers greater than 2 by 2 to get a new list. How?

code show as below:

how do you feel? Python, you are awesome!

Brother, be stunned, don't just smirk, just don't practice the fake style, I suggest you write this code ten times!

Write ten times!

Write ten times!

Write and write,

I was impressed,

I can't forget it.

5、 Pass a variable number of parameters in the function

Imagine if we have a function, it has multiple formal parameters, and its code block can achieve some functions we need. The problem is that when the number of parameters is uncertain, the result of the function code block operation may be different. In such a situation, do we need to write a similar function for every possibility?

Of course not, Python always has a way to get it.

It has a special method that uses * or ** parameter prefixes to achieve flexible parameter transmission. Let's look at the following example. When we pass 3 parameters and 2 parameters, the function can be executed, but the result is different.

Because we added a * prefix in front of the args variable, all other extra parameters of the function will be passed to args and stored as a tuple. If the ** prefix is used, the additional parameters will be treated as key-value pairs of the dictionary.

6、 assert statement

The assert statement is used to assert (Assert) that something is true. For example, if you are very sure that the list you are using contains at least one element, and want to confirm this, if the judgment is wrong, an error will be thrown. The assert statement is ideal in this case. When the statement assertion fails, an exception of the AssertionError class will be thrown (the exception will be introduced soon).

We should choose assert statements wisely. In most cases, it is better than catching the exception, or better than locating the problem or displaying an error message to the user and exiting.

7、 abnormal

Unlike program bugs, sometimes when we are writing code, we cannot predict whether there will be exceptions to the code processing here, and once an exception occurs, the program will terminate and report an error. This situation is called an Exception.

Python handles exceptions by using try...except.

The try statement works as follows:

(1) First, execute the try clause (the statement between the keyword try and the keyword except)

(2) If no exception occurs, ignore the except clause, and end after the try clause is executed.

(3) If an exception occurs during the execution of the try clause, the rest of the try clause will be ignored. If the type of the exception matches the name after except, the corresponding except clause will be executed.

(4) The code after the try statement is finally executed. If an exception does not match any except, then the exception will be passed to the upper try.

A try statement may contain multiple except clauses to handle different specific exceptions. More standard exception classes can be queried from official documents.

**Learning to handle exceptions is a sign that a programmer has become mature. **

8、 Standard library

Finally, let's introduce the standard library. The Python Standard Library (Python Standrad Library) contains a lot of useful modules, and it is also part of the Python installation package.

Familiar with the Python standard library is very important, it is definitely a treasure! Because the more you are familiar with it, the more you will find easy solutions to many problems. The common modules of some standard libraries are listed as follows:

**os: **operating system interface module

**sys: **System built-in function module

glob: provides a function to generate a file list module from a directory wildcard search

**re: **tool module that provides regular expressions for advanced string processing

**math: ** Mathematical operation module

**random: ** Provide a tool module for generating random numbers

**date: **Date and time module

**zlib, gzip, bz2, zipfile, and tarfile: ** modules that directly support common data packaging and compression formats

**What we need to emphasize is that, especially for a novice, when you are looking for a solution, you should not always try to solve the problem by writing code by yourself. Many times, the standard library of Python has already provided us. A perfect solution, at least a large part of the solution may be provided. Therefore, you have to get used to trying to learn more about the standard library of Python and know how many treasures it hides in it. When you need it, you only need to import the module to use it. This is also a highly efficient Python programming. important reason. **

Note: You can find all the details of all modules in the documentation attached to your Python installation package.

summary

We have introduced more features about Python in this chapter, but it is still far from covering all of Python. However, after the introductory stage of learning, we have covered most of the things you will encounter in practice, which is enough to enable you to start writing any program you expect.

At this point, our Python introductory course is all over. If you write any good code from this, remember to share it.

There are always people who are still unfinished, right?

Well, the classmates who haven't left yet, quietly tell: there are some easter eggs at the back of the course! Yes, as smart as you, continue to pay attention tomorrow.

Recommended Posts

Getting started with Python(18)
Getting started with Python(9)
Getting started with Python(8)
Getting started with Python(4)
Getting started with Python (2)
Getting started with python-1
Getting started with Python(14)
Getting started with Python(7)
Getting started with Python(17)
Getting started with Python(15)
Getting started with Python(10)
Getting started with Python(11)
Getting started with Python(6)
Getting started with Python(3)
Getting started with Python(12)
Getting started with Python(5)
Getting started with Python (18+)
Getting started with Python(13)
Getting started with Python(16)
Getting started with Numpy in Python
Getting started with Ubuntu
Getting Started with Python-4: Classes and Objects
Getting started with python-2: functions and dictionaries
04. Conditional Statements for Getting Started with Python
Getting started python learning steps
How to get started quickly with Python
python requests.get with header
Play WeChat with Python
Web Scraping with Python
Implementing student management system with python
Centos6.7 comes with python upgrade to
Played with stocks and learned Python
Gray-level co-occurrence matrix (with python code)
Speed up Python code with Cython
How to make a globe with Python
Automatically generate data analysis report with Python
Create dynamic color QR code with Python
Python | Quickly test your Python code with Hypothesis
How to process excel table with python