I want to learn Python secretly, and then shock everyone (day 4)

Insert picture description here

The title is not intended to offend, but I think this ad is fun
. Take the above mind map if you like it. I can’t learn so much anyway.

Preface

Preliminary review: I want to learn Python secretly, and then stun everyone (the third day). The
above article wrote some basic knowledge of python, mainly Python's read and write operations on files, maybe because the number of words is relatively small, every time I felt a little embarrassed to open it myself.
But it is also because the file reading and writing is a bit more difficult than the previous two articles.

So today, let's take a look at the things that make Python a "magazine", modules! If you are not very proficient in the basics, you can solidify your foundations. After all, building on the ground is very dangerous.

本系列文默认各位有一定的C或C++基础,因为我是学了点C++的皮毛之后入手的Python,这里也要感谢齐锋学长送来的支持。
本系列文默认各位会百度,学习‘模块’这个模块的话,还是建议大家有自己的编辑器和编译器的,上一篇已经给大家做了推荐啦?

我要的不多,点个关注就好啦
然后呢,本系列的目录嘛,说实话我个人比较倾向于那两本 Primer Plus,所以就跟着它们的目录结构吧。

本系列也会着重培养各位的自主动手能力,毕竟我不可能把所有知识点都给你讲到,所以自己解决需求的能力就尤为重要,所以我在文中埋得坑请不要把它们看成坑,那是我留给你们的锻炼机会,请各显神通,自行解决。

Okay, let's move on to the topic.


What is a module?

If you have learned other high-level languages, you will know that at the beginning of a C/C++ source file, there will usually be a lot of'include'. This is a reference header file. There are some classes and functions in a header file. , Variables, etc., and you want to use these things, you have to make a statement in advance.

In this way, it is really out of space.
Insert picture description here

Suppose there is a QQ group with members, files, and chat records. If you want to obtain these things and use them, do you have to join the group?
This is the reason for discarding modules. There are classes, functions, and variables in a module. If you want to use these things, you have to import the module.

It's much smoother in this way.

emmm, I always feel that something is missing. Yes, let’s scan a module and just glance at it. I don’t want to understand. I probably know what’s inside.

The following is an interception in a random module:

from warnings import warn as _warn
from types import MethodType as _MethodType, BuiltinMethodType as _BuiltinMethodType
from math import log as _log, exp as _exp, pi as _pi, e as _e, ceil as _ceil
from math import sqrt as _sqrt, acos as _acos, cos as _cos, sin as _sin
from os import urandom as _urandom
from _collections_abc import Set as _Set, Sequence as _Sequence
from hashlib import sha512 as _sha512
import _random

__all__ = ["Random","seed","random","uniform","randint","choice","sample",
           "randrange","shuffle","normalvariate","lognormvariate",
           "expovariate","vonmisesvariate","gammavariate","triangular",
           "gauss","betavariate","paretovariate","weibullvariate",
           "getstate","setstate", "getrandbits",
           "SystemRandom"]

NV_MAGICCONST = 4 * _exp(-0.5)/_sqrt(2.0)
TWOPI = 2.0*_pi
LOG4 = _log(4.0)
SG_MAGICCONST = 1.0 + _log(4.5)
BPF = 53        # Number of bits in a float
RECIP_BPF = 2**-BPF

class Random(_random.Random):
    VERSION = 3     # used by getstate/setstate

    def __init__(self, x=None):
        self.seed(x)
        self.gauss_next = None

    def seed(self, a=None, version=2):
        if a is None:
            try:
                # Seed with enough bytes to span the 19937 bit
                # state space for the Mersenne Twister
                a = int.from_bytes(_urandom(2500), 'big')
            except NotImplementedError:
                import time
                a = int(time.time() * 256) # use fractional seconds

        if version == 2:
            if isinstance(a, (str, bytes, bytearray)):
                if isinstance(a, str):
                    a = a.encode()
                a += _sha512(a).digest()
                a = int.from_bytes(a, 'big')

        super().seed(a)
        self.gauss_next = None
……

As you can see, at the beginning, it adjusted a bunch of packages (import..., it doesn't matter if you don't understand it now), and then some variables, and then a class, which has functions.
Okay, maybe just a glance, let's continue


Assignment statements are needed to define variables, def statements are needed to encapsulate functions, class statements are needed to encapsulate classes, but no statements are needed to encapsulate modules.

The reason why no statement is used is because each individual Python code file (file with the extension .py) is a separate module.

This is not difficult to understand.

The purpose of encapsulating the module is also to store the program code and data for reuse. If it is encapsulated into classes and functions, it is mainly convenient to call by ourselves, but the module is encapsulated, not only can we use it ourselves, but the file format is also easy to share with others.


Join me to import your own modules

How should I put it, others have tens of millions of modules, but it is easier to use my own modules when I study, because I will also need to write modules myself in the future.

Step 1: Create a new module

Insert picture description here

Create a new module according to the sequence in the figure, and then write the code.

Step 2: Call the module

Insert picture description here

Well, this is a very simple little chestnut.

Call different methods of the module.

Just like in the previous article, there are two ways to open a file, one is to open it directly, and the other is to use an alias. There are also different ways to call the module.

The first type of direct import has already been seen, but I can say a little more here. If the module name is too long, you can use an alias.
For example import test, if you think test is a bit long, it is inconvenient to use later. You can do this: import test as t
but you can only use it later. t is used to refer to that module, but test can no longer be used, it has been top-packaged.

The second method, called from...import...
what is this method, or the example above, I now want to use the test3 class in the test, I don’t want the others, then why should I import everything else? Isn't that too big? At this time, you can use this method for precise positioning.

Look at the picture:
This is a typical wrong way of writing: Now that you have a precise positioning, don't get entangled with the big pool before
Insert picture description here

Here is a test if only a certain part is imported, and the remaining parts that have not been imported will be imported into the part of the application will not conflict:
Insert picture description here

This is the verification result:
Insert picture description here

This is the use of aliases, which can still be used:
Insert picture description here


One more point here, what if you want to import multiple modules? It is also possible. Use commas to separate the different modules. Please move up and try it yourself.


if __name__ == '__main__'

For Python and many other programming languages, a program must have an entry point.

In Python, when we are running a certain py file, we can start the program --- this py file is the entry point of the program.

However, when we have a lot of py files to form a program:
Insert picture description here

In order to [specify] a certain py file is the entry point of the program, we can write such code in the py file:

# 【文件:xx.py】

代码块 ①……

if __name__ == '__main__':
    代码块 ②……

The meaning of this sentence is this:
Insert picture description here

Here [if name ==' main '] is equivalent to the program entry of Python simulation. Python itself does not stipulate such writing, it is a coding habit that programmers reach a consensus.


csv module to manipulate Excel charts

First of all, we must clearly know that this is using someone else's module. Secondly, we only know that the function we want to achieve is simple operation of Excel tables.

So our order should be:
What module do I use?
What are the functions in this module?
How to use these specific functions?
Okay, I will use it.

What module do I need?

This is actually easy to handle, but also very difficult to handle.
If it's easy to handle, just ask Du Niang:
Insert picture description here
yes , you can find everything in one search.
It's not easy to say, you can't find a lot of previous experience, you have to ask.

For example, we use the csv module today because it is easy to use.

What is in this module?

Then this problem is easy to handle. If you think your English is okay, or if you want to practice your English, you can go to the official website because the official website is updated to the latest version.
The Chinese translation version, sometimes it is not very effective to find the latest version.

Hey, just kidding, the Chinese version also has the
Python manual (official Chinese version)

OK, we find the csv module (with a search box): CSV

If you are interested, you can read it with Chinese and English. If you are in a hurry, just look at its sample code.

Use csv module

First we build a table:
Insert picture description here

Then open this table, just like opening a file. If you are not familiar with file operations, you can return to this review:
I want to learn Python secretly (3)

read

import csv

with open('test.csv', newline = '', encoding = 'GBK')  as f:
    #参数encoding = 'utf-8'防止出现乱码
    reader = csv.reader(f)
    #使用csv的reader()方法,创建一个reader对象
    for row in reader:
        print(row)

Insert picture description here

write

First create an instance with a variable named writer (or other names). The creation method is writer = csv.writer(x), and then you can use writer.writerow (list) to write the contents of a line list to the csv file.
Insert picture description here

import csv

with open('test.csv','a', newline='',encoding='utf-8') as f:
    writer  = csv.writer(f)
    writer.writerow(['6', '小黑', '65', '82', '86'])
    writer.writerow(['7', '小红', '78', '64', '31'])

Insert picture description here
Insert picture description here

At this point, we have learned the most basic csv table reading and input methods.


Today’s task:
Let’s try to merge multiple csv files into one csv file. This is not difficult to say, and it is not so intuitive to say simple.

I will put my code in the next article.

Then, on average, I update a series of "Learn Python Secretly" three or four days on average, so don't worry, everything will come as planned.

The next article is a practical article. I will take you to review the learning content these days from the beginning. There will be more practice.


I drew a circle, welcome everyone to our small circle

I have built a Python Q&A group, friends who are interested can find out: What kind of group is this?

Portal through the group: Portal

Insert picture description here
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_43762191/article/details/109195441