1 數學運算模塊 math
“math”模塊提供了許多常用的數學函數,例如三角函數、四舍五入、指數、對數、平方根、總和等
import math
1.1 常數
math.pi 返回圓周率的數學常數。 math.e 返回指數的數學常數 示例:
print(math.pi)
print(math.e)
1.2 fabs(x)
print(math.fabs(5))
print(math.fabs(-5))
1.3 ceil(x)、floor(x)、round(x)
print(math.ceil(3.1))
print(math.floor(3.1))
print(round(3.51))
print(round(3.49))
1.4 pow(x, y)、sqrt(x)
print(math.pow(2,3))
print(2**3)
print(math.sqrt(9))
1.5 factorial(x)
factorial(x):x的階乘,x只能為正整數
print(math.factorial(5))
2.6 gcd(a,b)、lcm(a,b)
print(math.gcd(12,8))
print(math.lcm(9,6))
2 隨機數模塊random
import random
2.1 random()方法
print(random.random())# 隨機數種子,使用種子生成隨機數
random.seed()
print(random.random())
print(random.random())
2.2 randint()方法
print(random.randint(8,9))
2.3 randrange()方法
返回指定范圍 [a,b) 內的隨機數 語法:random.randrange(start, stop, step) start – 可選, 一個整數,指定開始值,默認值為 0 stop – 必需, 一個整數,指定結束值 step – 可選, 一個整數,指定步長,默認值為 1 示例:
print(random.randrange(1,9,3))
3 日期和時間處理模塊datetime
date 類用于表示日期,包含年、月、日三個屬性 time 類用于表示時間,包含時、分、秒、微秒等屬性 datetime 類是 date 和 time 的結合體,可以同時表示日期和時間 timedelta 類用于表示時間差,可以用于日期和時間的加減操作
import datetime
3.1 datetime
print(datetime.datetime.now())
print(datetime.datetime.now().year)
now=datetime.datetime.now()
print(now.month)
print(now.day)
print(now.hour)
print(now.minute)
print(now.second)
print(datetime.datetime(2025,1,3,9,30,0))
格式化日期和時間 常用符號 Y m d H M S 年 四位 月 兩位:01~12 日 兩位:01~31 時 兩位:0~23 分 兩位:00~59 秒 兩位:00~59
now=datetime.datetime.now()
print(now.strftime("%Y-%m-%d %H:%M:%S"))
print(now.strftime("%Y年%m月%d日 %H:%M:%S"))
3.2 timedelta
now=datetime.datetime.now()
# 10天后
after_10_date=now+datetime.timedelta(days=10)
print(after_10_date)
# 10天前
before_10_date=now-datetime.timedelta(days=10)
print(before_10_date)
before_10_date=now+datetime.timedelta(days=-10)
print(before_10_date)# 1月前
before_1_month=now-datetime.timedelta(days=30)
print(before_1_month)# 1年前
before_1_year=now-datetime.timedelta(days=365)
print(before_1_year)
3.3 date
# print(datetime.date.today())
date=datetime.date.today()
path="D:/333/A/1.txt"
new_name=path.split('/')[-1].replace('.txt','_'+str(date)+'.txt')
print(new_name)
with open(path,'r',encoding='utf-8') as f1:text=f1.read()# print(text)with open('D:/333/B/'+new_name,'w',encoding='utf-8') as f2:f2.write(text)
4 系統相關模塊sys
提供了與python解釋器及其環境交互的功能 通過 sys 庫,可以訪問與 Python 解釋器相關的變量和函數,例如命令行參數、標準輸入輸出、程序退出等。
import sys
4.1 命令行參數
sys.argv 是一個包含命令行參數的列表。sys.argv[0] 是腳本的名稱,后續元素是傳遞給腳本的參數。
print(f'腳本名稱:{sys.argv[0]}')
print(f'腳本參數:{sys.argv[1]}')
4.2 sys.exit()
def A():print('-'*20,'函數A開始','-'*20)for i in range(10):print(i)if i==5:print('-'*20,'函數A結束','-'*20)# return結束當前函數return# exit退出當前程序# sys.exit()
def B():print('-'*20,'函數B開始','-'*20)A()# exit時不執行該語句print('-'*20,'函數B結束','-'*20)
B()
4.3 標準輸入輸出
sys.stdin、sys.stdout 和 sys.stderr 分別代表標準輸入、標準輸出和標準錯誤流。
# 標準輸出
with open('d:/333/2.txt','w',encoding='utf-8') as f:sys.stdout=fprint('標準輸出到文件')
# 標準輸入
print('輸入:')
list1=[]
for i in sys.stdin:if i.strip()=="":breaklist1.append(i.strip())
print('輸出:')
for i in list1:print(i)