Python:模塊與包

一、模塊與包

python.org:模塊
python.org:包

python的概念層級:

  • 表達式,創建、處理對象。
  • 語句,包含表達式。
  • 邏輯單元,函數/類,由語句組成。
  • 模塊,.py文件。
  • 包,定義一組有關係的文件或模塊(包是文件夾,模塊是文件夾中的文件,且文件夾中包括一個__init__.py文件)。
  • 程序,若干個包和若干個文件組成。

二、模塊路徑問題

# 模塊路徑問題

# 1.查看現有包所在路徑,將自己創建的包存入該路徑
import pandas
print(pandas.__file__)

# 2.加載sys包,把新建的模塊文件所在路徑添加到該包中
import sys
sys.path.append('C:/Users/C1/Desktop/')

三、模塊調用

liaoxuefeng:使用模塊

調用整個模塊。

# 1.創建一個模塊,包含一個階乘函數f1(n)、一個列表刪值函數f2(lst,x),一個等差數列求和函數f3(a,d,n)

# 創建階乘函數f1(n)
def f1(n):
    y = 1
    for i in range(1,n+1):
        y = y * i
    return y

# 創建列表刪值函數f2(lst,x)
def f2(lst,x):
    while x in lst:
        lst.remove(x)
    return lst

# 創建等差數列求和函數f3(a,d,n)
# 創建模塊testmodel,包括三個函數
def f3(a,d,n):
    an = a
    s = 0
    for i in range(n-1):
        an = an + d
        s = s + an
    return s

# 2.調用模塊語句:import

import testmodel

print(testmodel.f1(5)) # 直接用import調用模塊,.f1()調用模塊函數(方法)
print(testmodel.f2([2,3,4,5,5,5,6,6,4,4,4,4],4))
print(testmodel.f3(10,2,10))


使用import調用模塊時,可以使用as簡化模塊名。

# 簡化模塊名:import...as...

import testmodel as tm
print(tm.f1(5))


調用模塊中部分功能。

# 調用部分模塊語句:From…import 語句

from testmodel import f2

print(f2([2,3,4,5,5,5,6,6,4,4,4,4],4))
#print(f3(10,2,10)) # 單獨導入模塊的部分功能,但無法使用其他未導入模塊功能

四、常用的兩個模塊:random,time

random

python.org:random

# python標準模塊 —— random隨機數

import random

x = random.random() # random.random()隨機生成一個[0:1)的隨機數
y = random.random()
print(x,y*10)

m = random.randint(0,10) # random.randint()隨機生成一個[0:10]的整數
print(m)

st1 = random.choice(list(range(10))) # random.choice()隨機獲取()中的一個元素,()內必須是一個有序類型
st2 = random.choice('abcdnehgjla')
print(st1,st2)

lst = list(range(20))
sli = random.sample(lst,5) # random.sample(a,b)隨機獲取a中指定b長度的片段,不改變原序列
print(sli)

lst = [1,3,5,7,9,11,13]
random.shuffle(lst) # random.shuffle(list)將一個列表內的元素打亂
print(lst)

time

python.org:time

# python標準模塊 —— time時間模塊

import time

for i in range(2):
    print('hello')
    time.sleep(1) # time.sleep()程序休息()秒
 
print(time.ctime()) # 將當前時間轉換爲一個字符串
print(type(time.ctime()))

# 將當前時間轉爲當前時區的struct_time
# wday,0-6表示週日到週六
# ydat,1-366 一年中的第幾天
# isdst,是否爲夏令時,默認爲-1
print(time.localtime())
print(type(time.localtime()))

# time.strftime(a,b)
# a爲格式化字符串格式
# b爲時間戳,一般用localtime()
print(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime()))

格式 說明
%y 兩位數的年份表示(00-99)
%Y 四位數的年份表示(000-9999)
%m 月份(01-12)
%d 月內中的一天(0-31)
%H 24小時制小時數(0-23)
%I 12小時制小時數(01-12)
%M 分鐘數(00=59)
%S 秒(00-59)
%a 本地簡化星期名稱
%A 本地完整星期名稱
%b 本地簡化的月份名稱
%B 本地完整的月份名稱
%c 本地相應的日期表示和時間表示
%j 年內的一天(001-366)
%p 本地A.M.或P.M.
%U 一年中的星期數(00-53)星期天爲星期的開始
%w 星期(0-6),星期天爲星期的開始
%W 一年中的星期數(00-53)星期一爲星期的開始
%x 本地相應的日期表示
%X 本地相應的時間表示
%Z 當前時區的名稱
%% %號本身

五、模塊的安裝

python.org:安裝python模塊
liaoxuefeng:安裝第三方模塊

# Windows
# 查詢pip命令參數
pip

# 安裝模塊
pip install <模塊名>

# 查詢已安裝的模塊
pip list

windows cmd運行python文件
python <python文件名.py>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章