out-of-the-box modules

Introduction: A module in python is actually a program file containing functions, classes, and variables, that is, a python program file with an extension of py, which can be referenced when needed to save time and effort.

Modules and Packages

1. Module import

Method: 1. import module name

2. import module name as module alias

3. From module name import function name/property/submodule name (with from you can not write the module name)

from module name import *: Import all of the modules.

Notice:

from math import pow

This method only imports the pow() method of the math module!

2. Module path

When installing a module or a third-party library that comes with python, the system will automatically record the storage path of the module in the sys. module.

How can I let the interpreter know the path? There are two methods:

1. Add a path to the list.

2. Modify the value of the system environment variable.

3. Namespace

A namespace represents the scope of visibility for an identifier. Identifiers are used to identify an object, including variable names, function names, module names, class names, etc.

If you use the 'from module name import function name/attribute/submodule name' method to import, you must pay attention not to have the same identifier in different modules.

4、name:

In python, in order to distinguish whether a code block is run alone or imported into another code as a module, it is identified by judging the ____name____ attribute value of the module.

If there are definitions of functions and classes, such interpretations are performed, and a judgment of "if____name____ == ' main ':" is added.

import math
def prime_judg(s):
    for i in range(2,int(math.sqrt(s)+1)): #判断是否是素数
        if s % i == 0:
            break
        else:
            return  True
if __name__ == '__main__': #判断是否有函数、类的定义
    print(prime_judg(13))

5. Package

The package is to classify the modules into different folders, and then create a ____init____.py file in the folder.

The init.py file is the flag of the package. Each package must contain one. This file can be empty or some initial code can be written.

When you import the module after you have the package, you need to add the name of the report, "signup.module name".

6. Standard library

1. Math module

There are a large number of commonly used mathematical calculation functions in this module, such as: trigonometric functions, inverse trigonometric functions, logarithmic functions, and mathematical constants pi, e, etc.

Use dir(math) to view the functions (methods) and constants (attributes) in the math module.

Two, random module

This module is mainly used to generate random numbers.

function usage
random() Used to generate random numbers random.random() between 0 and 1
randint(a,b) Used to generate an integer random.randint(a, b)
choice(seq) Used to randomly select an element from the sequence random.choice(seq)
Three, time module

The time module is a module related to time.

function usage
time() Timestamp function, used to obtain the total number of seconds from January 1, 1970, 0:00:00 to the present
localtime() for getting local time
ctime() Display the time as a string
strftime() Used to convert time to formatted time

The meanings of each time tuple:

index Attributes meaning
0 tm_year Year
1 tm_mon moon
2 tm_mday Day
3 tm_hour hour
4 tm_min point
5 tm_sec Second
6 tm_wday The day of the week, the value is [0, 6], 0 is Monday
7 tm_yday The day of the year, the value is [0,365], where 0 represents January 1st
8 tm_isdst Whether it is daylight saving time, if the daylight saving time is implemented, it is positive

Daylight Saving Time (Daylight Saving Time: DST), also known as Daylight Saving Time, also known as "Daylight Saving Time" and "Daylight Saving Time", is a system that artificially stipulates local time to save energy. The unified time adopted during this period is called "Daylight Saving Time". Generally, in the summer when the dawn is early, the time is artificially adjusted one hour earlier, which can make people get up early and go to bed early, reduce the amount of lighting, and make full use of lighting resources, thereby saving lighting electricity. The specific regulations of each country that adopts daylight saving time are different. Nearly 110 countries around the world implement daylight saving time every year.

import time
print(time.localtime()[0])
print(time.localtime()[1])
print(time.localtime().tm_hour)
print(time.localtime().tm_min)

The result of the operation is

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-VDBRPumF-1685766659786) (C:\Users\30967\AppData\Roaming\Typora\typora-user-images\ image-20230603120824816.png)]

Meaning of time formatting parameters (common list):

Format meaning
%a local simplified day of the week name
%A local full weekday name
%b local simplified month name
%B local full month name
%c local corresponding date and time representation
%d Day of the month (01-31)
%H Hour in 24-hour format (00-23)
%I Hours in 12-hour format (01-12)
Four, datetime module
function usage
datetime.date A class representing a date, commonly used attributes are year, month, day
datetime.time A class representing time, commonly used attributes are hour, minute, second, microsecond
datetime.datetime Classes representing dates and times
datetime.timedelta A class representing a time interval

(1) The current time now() function

datetime.datetime.now()

(2) Current time today() function

datetime.datetime.today()

(3) The current date date() function

datetime.datetime.now().date()

(4) Time tuple timetuple() function

datetime.datetime.now().timetuple()

(5) Time calculation timedelta() function

Use the datetime.timedelta() method to move time back and forth. The available parameters are: weeks, days, hours, minutes, seconds, microseconds.

(6) Format conversion surftime() function

The formatting parameters are the same as the surftime() function of the time module.

(7) Current time today() function - date submodule

datetime.date.today()
Five, urllib module

The urllib module is used to process URLs. This module is often used when crawling web pages.

import urllib.request#导入模块
baidu = urllib.request.urlopen('https://www.baidu.com')#打开网页
print(type(baidu))
html = baidu.read()#读取网页内容
print(type(html))
file = html.decode('utf-8')#进行解码
print(file)

Thank you for reading.
The next issue is some classic case questions of modules and packages.

Guess you like

Origin blog.csdn.net/m0_61901625/article/details/131019928