from os import getcwd #os模块以平台独立方式与底层操作系统交互
getcwd()#getcwd函数返回当前工作目录import sys #系统信息模块
sys.platform #查看系统内核print(sys.version)#查看python版本import datetime #日期时间模块
datetime.date.today()#今天的日期
datetime.date.today().day #日
datetime.date.today().month #月
datetime.date.today().year #年
datetime.date.isoformat(datetime.date.today())#格式化年月日'2022-04-07'import time #时间模块
time.strftime("%H:%M")#查看当前时间 '10:38'
time.strftime("%A %p")#查看星期几和上下午 'Thursday AM'import html
html.escape("<script>")#html符编码 '<script>'
html.unescape("<script>")#html符解码 '<script>'
odds =[1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45,47,49,51,53,55,57,59]#一个奇数列表
right_this_minute = datetime.today().minute #把函数的结果今天的分钟数赋值给变量if right_this_minute in odds:#检查一个变量是否(in)在一个列表中print("这是个奇数分钟数")else:#否则,elif=再如果print("这是个偶数分钟数")for i in[1,2,3]:#for循环print(i)for num inrange(5):#range函数循环5次,唯一默认值为stopprint('Hello!')list(range(5,10))#5-9 两个默认值为start,stoplist(range(10,5,-1))#10-6 三个值为 start,stop,step正数为正序,负数为倒序import time
time.sleep(5)#程序中断5秒import random
dir(random)#显示所有random可用属性help(random.randint)#查看randint方法帮助文档
random.randint(1,60)#在1~60中取一个随机数
2 列表
import random
wait_time =random.randint(1,60)
wait_time #如果wait_time第一次是19,那么永远都是19,不会再运行一次random.randint取值
car =['Toyota','RAV4',2.2,60870]#列表,有序可变#元祖,有序不可变#字典,无序的键/值对集合#集合,无序的唯一对象集合(不重复)len(car)#len函数查看一个对象的大小
car.append('gg')#list.append()方法为列表增加一个对象if"u"notin car:# not in 与in相对,查看对象是否不在
car.append('u')
word =input("输入一个字符串")#input()接收用户输入的函数
nums =[1,2,3,4]
nums.remove(3)#list.remove删除指定值的第一次出现(如果有相同的只删除第一个)
nums.pop()#如果未指定索引,则弹出最后一个
nums.extend([3,5,8])#把两个列表合并成一个
nums.insert(3,"333")#在列表索引3的位置插入任意一个对象
third = nums.copy()#赋值一个列表
third[5]#访问列表索引的值,支持负数索引
third[3:5:1]#批量访问列表元素[开始:结束:步长]str=['n','m','d']''.join(str[::3])#把列表中的字符串对象拼接成字符串
3 结构化数据
person ={'Name':'Dad','Gender':'Male'}#字典格式 无序
person['Name']#字典取值 速度快
person['Age']=55#字典新增键值对
person['Age']= person['Age']+1#根据字典键为字典值增值
person['Age']+=1#等同for i in person:print(person[i])#字典迭代for k,v in person.items():#items()方法拆分键值对print(k,v)#字典键值对迭代sorted('95687')#排序函数
person.setdefault('dage','大哥')#如果键dage不存在于字典中,将会添加键并将值设为默认值'大哥'
vowels ={'a','e','i','i','o','u','u'}#集合无序且自动去重
vowels2 =set('abcopq')#set快捷创建集合
u = vowels.union(vowels2)#union合并集合
d = vowels.difference(vowels2)#difference比较两个集合不重复的元素
i = vowels.intersection(vowels2)#intersection查找两个集合的共同元素
vowels3 =('a','e','i','o','u')#元组 不可变 必须含有一个对象以上type(vowels3)#查看对象类型
people ={'Aa':{'A':'a','B':'b'},'Bb':{'B':'b','A':'a'}}import pprint
pprint.pprint(people)#美观打印嵌套字典
people['Aa']['A']#访问嵌套两层的字典数据[][]
4 函数与模块
defsearch4vowels(word):
vowels =set('aeiou')
found = vowels.intersection(set(word))returnbool(found)#bool判定布尔值 return返回一个布尔值defsearch4vowels(word):
vowels =set('aeiou')
found = vowels.intersection(set(word))return found #返回一个集合对象list()#空列表dict()#空字典set()#空集合tuple()#空元组defsearch4letters(phrase,letters):#phrase接收一个短语,letters接收要查询的字符组returnset(letters).intersection(set(phrase))#set创建一个letters字符集合对象,intersection对比此集合对象是否在set(phrase)这个字符串集合对象中,return返回对比后的一个集合对象结果
search4letters('malone','abc')defsearch4letters(phrase,letters='aeiou'):#函数参数可指定默认值,如果没有参数就以默认值为参数returnset(letters).intersection(set(phrase))
search4letters('malone')
search4letters(letters='xyz',phrase='galaxy')#函数关键字赋值,不需要考虑顺序#解释器搜索模块顺序:1、当前工作目录 2、解释器的site-packages(第三方库和自写库)位置 3、标准库#打包模块:模块文件夹(模块文件.py setup.py README.TXT)#setup.pyfrom setuptools import setup
setup(
name='模块名',
version ='版本号',
description ='描述',
author ='作者',
author_email ='邮箱',
url ='主页',
py_modules =['模块包含的py文件列表'])#打包文件 in windows
c:\Users\Head Frist\mymodules> py -3 setup.py sdist
#打包文件 in UNIX
mymodules$ python3 setup.py sdist
#装入第三方库 源自dist文件夹 in windows
python3 -m pip install vsearch-1.0.zip#装入第三方库 源自dist文件夹 in UNIX
sudo python3 -m pip install vsearch-1.0.tar.gz
5 构建Web
6 文件读写
todos =open('todos.txt','a')#open打开文件,a追加写入,此文件流附给变量todosprint('abc',file=todos)#写入abc,file=todos文件流
todos.close()#close关闭文件
tasks =open('todos.txt')#默认打开为只读for chore in tasks:#默认迭代每一行数据print(chore,end='')#抑制print默认追加换行符open('todos.txt','r')#只读模式open('todos.txt','w')#重写模式open('todos.txt','a')#追加模式open('todos.txt','x')#类似w,可如果文件已存在则失败。#'wb'写入二进制文件,'xb'写入新的二进制文件……withopen('todos.txt')as tasks:#with会自动调用close关闭结束任务的文件 as赋值给新变量for chore in tasks:print(chore,end='')
contents = log.read()#read()一次性读取所有数据from flask import escape
escape('<html></html>')#escape转义html符号为字符串形式
Markup('<html></html>')
pythons ='|'.join(names)#拆解names列表为以|为分隔符的字符串
indivduals = pythons.splist('|')#以特定分隔符切分字符串组成列表
contents = log.readlines()#读取所有数据行
7 数据库
8 类
#创建一个类!classCountFromBy:#class定义类 + 类名def__init__(self,v:int,i:int):#初始化类属性,方法参数v数字,i数字 创建对象时候直接赋值v和i
self.val = v #val得到v的传参值
self.incr = i #incr得到i的传参值defincrease(self):#类的方法 self=js的this
self.val += self.incr #这个对象的val + incr 的和
h = CountFromBy(100,10)#通过CountFromBy类实例化一个h对象,v=100,i=10
h.val #初始化属性 val=v=100
h.incr #初始化属性 incr=i=10
h.increase()#调用类increase方法 val=val+incr#h.val=110 h.incr依然是10classCountFromBy:def__init__(self,v:int=0,i:int=1):#同函数相同,还可以为其指定默认值
self.val = v
self.incr = i
defincrease(self):
self.val += self.incr
def__repr__(self):returnstr(self.val)#repr把显示内存地址转为显示字符串
9 上下文管理协议 with
10 函数修饰符
#函数嵌套函数defapply(func:object,value:object):#func接受一个函数,value接受一个值return func(value)#运行函数func,value值作为参数传入funcapply(print,43)#函数apply运行函数print,43以参数传入print#嵌套函数中,函数运行顺序取决于内部调用的位置defouter():definner():print('内部函数')
inner()#先调用先输出print('外部函数')#后输出
outer()#内部函数#外部函数defmyfunc(*args):#*函数可接收任意个参数for a in args:print(a,end=' ')if args:print()
myfunc(10,50,80)#10 50 80
values =[1,2,3,4,5]
myfunc(values)#[1, 2, 3, 4, 5]
myfunc(*values)#解析列表参数#1 2 3 4 5 defmyfunc2(**kwargs):#接收任意键值对for k,v in kwargs.items():print(k,v,sep='->',end=' ')if kwargs:print()
myfunc2(a=10,b=20)defmyfunc3(*args,**kwargs):#接收混合类型参数if args:for a in args:print(a,end=' ')print()if kwargs:for k,v in kwargs.items():print(k,v,sep='->',end=' ')print()
myfunc3(1,2,3,a=100,b=200,c=300)#1 2 3 #a->100 b->200 c->300