字符串
'''字符串的驻留机制
字符串长度为0或1时
符合标识符的字符串
字符串只在编译时进行驻留,而非运行时
[-5,256]之间的整数数字
强制驻留 import syc
'''
a= 'python'
b= 'python'
print ( a== b, a is b)
a, b= '' , ''
print ( a== b, a is b)
a, b= 's' , 's'
a, b= 'abc%' , 'abc%'
print ( a== b, a is b)
a= 'abc'
b= 'a' + 'bc'
c= '' . join( [ 'ab' , 'c' ] )
print ( a== b, a is b, a== c, a is c)
a, b, c, d= - 5 , - 5 , - 6 , - 6
print ( a== b, a is b, c== d, c is d)
'''
字符串的查询操作:
s.index(substr): 查询substr第一次出现的位置,若不存在,ValueError
s.rindex(substr): 查询substr最后一次出现的位置,若不存在,ValueError
s.find(substr): 查询substr第一次出现的位置,若不存在,返回-1
s.rfind(substr): 查询substr最后一次出现的位置,若不存在,返回-1
'''
s= '且将新火试新茶,诗酒趁年华'
print ( s. index( '新' ) , s. rindex( '新' ) )
print ( s. find( '新' ) , s. rfind( '新' ) )
print ( s. find( '苏轼' ) )
len ( string)
'''
字符串中的大小写转换方法:
s.upper() 大写
s.lower() 小写
s.swapcase() 大小写互换
s.capitalize() 首字母大写
s.title() 单词首字母大写
'''
s= 'hello,world'
s= s. upper( )
print ( s)
s= s. lower( )
print ( s)
s= s. capitalize( )
print ( s)
s= s. title( )
print ( s)
s= s. swapcase( )
print ( s)
'''
字符串的对齐操作:
s.center(__width,__fillchar) 宽度小于字符串本身则返回原字符串
s.ljust(__width,__fillchar=' ')
s.rjust(__width,__fillchar)
s.zfill(__width) 填充符为0
'''
s= 'hello,python'
print ( s. center( 40 , '-' ) )
print ( s. center( 40 ) )
print ( s. ljust( 40 , '-' ) )
print ( s. ljust( 40 ) )
print ( s. rjust( 40 , '-' ) )
print ( s. rjust( 40 ) )
print ( s. zfill( 40 ) )
print ( '-666' . zfill( 40 ) )
'''
字符串的劈分操作:
s.split(sep=' ',maxsplit) 劈分后返回列表
s.rsplit() 从右侧开始劈分
'''
s= 'hello world python'
print ( s. split( ) )
s= 'hello|world|python'
print ( s. split( ) )
print ( s. split( '|' ) )
print ( s. split( '|' , 1 ) )
print ( s. rsplit( "|" , 1 ) )
'''
字符串的判断操作:
s.isidentifier() 判断字符串是不是合法的标识符
s.isspace() 判断字符串是不是由空白字符(\t\r\n)组成
s.isalpha() 判断字符串是不是由字母组成
s.isdecimal() 判断字符串是否由十进制数字组成
s.isnumeric() 判断字符串是否由数字组成
s.isalnum() 判断字符串是否由数字和字母组成
s.isdigit() 判断字符串是否由数字组成
'''
print ( '且将新火试新茶' . isidentifier( ) )
print ( '且将新火试新茶' . isalpha( ) )
print ( '\t\n\r' . isspace( ) )
print ( '123' . isdecimal( ) )
print ( '一二三' . isdecimal( ) )
print ( 'ⅠⅡⅢⅣ' . isdecimal( ) )
print ( '123' . isnumeric( ) )
print ( '一二三' . isnumeric( ) )
print ( 'ⅠⅡⅢⅣ' . isnumeric( ) )
print ( 'windows98' . isalnum( ) )
'''
字符串的替换与合并:
s.replace(__old,__new,__count)
s.join() 将列表或元组中的字符串合并成一个字符串
'''
s= 'Jack is strong and Jack is tall.'
print ( s)
s= s. replace( 'Jack' , 'Tony' )
print ( s)
s= s. replace( 'Tony' , 'Jack' , 1 )
print ( s)
l= [ 'hello' , 'world' , 'python' ]
print ( '____' . join( l) )
t= tuple ( l)
print ( '' . join( t) )
print ( '_' . join( '且将新火试新茶' ) )
'''
字符串的比较操作:
ord():获取字符的ASCII码
chr():获取ACSCII对应的字符
> < >= <= == != 类似于C语言中字符串的比较
==比较的是值 is比较的是id地址
'''
print ( ord ( 'a' ) , ord ( '秋' ) )
print ( chr ( 97 ) , chr ( 31179 ) )
'''
字符串的切片:
类似于列表的切片,但是切片操作只能产生新的字符串对象,而不能对原字符串进行修改
字符串的索引也类似与列表,从前往后起始为0,从后往前起始为-1
'''
s= 'hello,python'
print ( s[ : 5 ] + ' world ' + s[ - 6 : ] )
'''格式化字符串,类似于C语言'''
name= '张三'
age= 20
print ( '我叫%s,今年%d岁' % ( name, age) )
print ( '我叫%s,今年%d岁' % ( name, age) )
print ( '我叫{0},今年{1}岁,{0}是我父母给我取的' . format ( name, age) )
print ( f'我叫 { name} ,今年 { age} 岁' )
print ( '%10d' % 666 )
print ( '%.1f' % 3.1415926 )
print ( "%15.2f" % 3.1415926 )
print ( '%-10.1f' % 3.1415926 , 0 )
print ( '{0:.3}' . format ( 3.1415926 ) )
print ( '{0:.3f}' . format ( 3.1415926 ) )
print ( '{0:20.3f}' . format ( 3.1415926 ) )
'''字符串的编码与解码'''
s= '诗酒趁年华'
print ( s. encode( encoding= 'GBK' ) )
print ( s. encode( encoding= 'UTF-8' ) )
byte1= s. encode( encoding= 'GBK' )
byte2= s. encode( encoding= 'UTF-8' )
print ( byte1. decode( encoding= "GBK" ) )
print ( byte2. decode( encoding= 'UTF-8' ) )
os.path模块
import os. path
print ( os. path. abspath( '包.py' ) )
print ( os. path. exists( '列表.py' ) , os. path. exists( '你大爷.py' ) )
print ( os. path. join( '..\\' , '列表.py' ) )
print ( os. path. split( 'C:\\Users\\霜秋-晓醉\\Documents\\python项目文件\\vippython\\杨淑娟\\text1.txt' ) )
print ( os. path. splitext( 'text1.txt' ) )
print ( os. path. basename( 'C:\\Users\\霜秋-晓醉\\Documents\\python项目文件\\vippython\\杨淑娟\\text1.txt' ) )
print ( os. path. dirname( 'C:\\Users\\霜秋-晓醉\\Documents\\python项目文件\\vippython\\杨淑娟\\text1.txt' ) )
print ( os. path. isdir( 'C:\\Users\\霜秋-晓醉\\Documents\\python项目文件\\vippython\\杨淑娟\\text1.txt' ) )
os模块
import os
'''
os.system('notepad.exe') #command命令
os.system('calc.exe') #win+r clac
'''
'''
os模块的相关操作:
getcwd():返回当前的工作目录
listdir(path):返回指定路径下的文件和目录信息
mkdir(path,[mode]):创建目录
makedirs(path1/path2...,[mode]):创建多级目录
rmdir(path):删除目录
removedirs(path1,path2...):删除多级目录
chdir(path):将path设置为当前工作目录
os.remove(filename):删除文件
'''
print ( os. getcwd( ) )
print ( '返回当前目录下的文件' . center( 40 , '-' ) )
print ( os. listdir( ) )
print ( os. listdir( '.\\' ) )
print ( os. listdir( './' ) )
print ( '返回上一级目录的文件' . center( 40 , '-' ) )
print ( os. listdir( '..\\' ) )
print ( os. listdir( '../' ) )
print ( '返回上上一级目录的文件' . center( 40 , '-' ) )
print ( os. listdir( '..\\..\\' ) )
print ( os. listdir( '../../' ) )
print ( '返回Folder中的文件' . center( 40 , '-' ) )
print ( os. listdir( 'Folder' ) )
print ( os. listdir( '.\\Folder' ) )
print ( os. listdir( './Folder' ) )
print ( os. listdir( '..\\..\\vippython\\杨淑娟\\Folder' ) )
print ( os. listdir( '../../vippython/杨淑娟/Folder' ) )
print ( os. getcwd( ) )
print ( '获取指定目录下所有的python文件' . center( 40 , '-' ) )
for file_name in os. listdir( ) :
if file_name. endswith( '.py' ) :
print ( file_name)
print ( '获取指定目录下的所有文件及其子文件' . center( 40 , '-' ) )
path= 'C:\\Users\\霜秋-晓醉\\Documents\\python项目文件\\vippython'
lst_files= os. walk( path)
print ( lst_files, type ( lst_files) )
for i in lst_files:
print ( i)
print ( type ( i) )
print ( '' . center( 40 , '-' ) )
print ( '\n\n\n\n' )
lst_files= os. walk( path)
for dirpath, dirname, file_name in lst_files:
print ( '' . center( 40 , '-' ) )
for dir in dirname:
print ( os. path. join( dirpath, dir ) )
for file in file_name:
print ( os. path. join( dirpath, file ) )
os. path. exists( 'xxx/xxx/filename' )
os. remove( filename)
print ( os. path. exists( 'a/b/快代理.txt' ) )
if os. path. exists( 'a/b/快代理.txt' ) :
os. remove( 'a/b/快代理.txt' )
文件的读写操作
'''
file=open(filename,[mode,encoding]) []代表可省略的参数
'''
def f1 ( ) :
file = open ( 'text1.txt' , 'r' )
print ( file . readlines( ) )
file . close( )
'''
常用的文件打开格式:
r:只读
w:只写
a:附加
b:以二进制打开,需与其他模式一同使用,如:rb,wb,通过二进制可以打开一些记事本打开不了的内容,如mp3,mp4,jpg,png等
+:以读写方式打开,需与其他模式一起用,如:a+
'''
def f2 ( ) :
file = open ( 'text1.txt' , 'a' )
file . write( '我与春风皆过客,你携秋水揽星河\n' )
print ( '星河灿烂,你是人间理想' , file = file )
file . close( )
def f3 ( n) :
current_file= open ( '金克斯.jpg' , 'rb' )
target_file= open ( f'金克斯( { n} ).jpg' , 'wb' )
target_file. write( current_file. read( ) )
target_file. close( )
current_file. close( )
'''
文件对象的常用方法: []表示可省略
file.read([size]) 读取size个字符,若size不指定,则默认全部读取
file.readline() 读取一行内容
file.readlines() 将每一行的内容作为字符串存入列表返回
file.write(str) 写入字符串
file.writelines(s_list) 将字符串列表写入文件
file.seek(offset,[whence]) 把文件指针移动到新的位置上,offset表示相对于whence的位置,为正向后,为负向前,whence——0开始-1当前-2末尾
file.tell() #告诉当前指针的位置
file.flush() 把缓冲区的内容写入文件,但不关闭文件
file.close() 吧缓冲区的内容写入文件同时关闭文件,释放相关资源
'''
def f4 ( ) :
file = open ( 'text1.txt' , 'r' )
file . close( )
def f5 ( ) :
file = open ( 'text2.txt' , 'w' , encoding= 'gbk' )
file . write( '此情应是长相守,你若无心我便休\n' )
file . writelines( [ '半生风雨半生伤,半句别恨半心凉\n' , '一别两宽,各生欢喜\n' , '我愿提笔画天下,许你一世繁华\n' ] )
file . close( )
def f6 ( ) :
file = open ( 'text1.txt' , 'r' )
file . seek( 2 )
print ( file . tell( ) )
print ( file . read( ) )
print ( file . tell( ) )
file . close( )
def f7 ( ) :
file = open ( 'text2.txt' , 'a' , encoding= 'utf-8' )
file . write( '且将新火试新茶,诗酒趁年华\n' )
file . flush( )
file . write( '大江东去,浪淘尽,千古风流人物' )
file . close( )
'''
with as语句可以保证在任何时候都能够正确的关闭文件,称上下文管理器
实现了__enter__方法和__exit__方法,遵守了上下文管理协议'''
def f8 ( ) :
print ( type ( open ( 'text1.txt' , 'r' ) ) )
with open ( 'text1.txt' , 'r' ) as file :
print ( file . read( ) )
def f9 ( ) :
class MyContentMgr ( object ) :
def __enter__ ( self) :
print ( '__enter__被调用执行了' )
return self
def __exit__ ( self, exc_type, exc_val, exc_tb) :
print ( '__exit__被调用执行了' )
def show ( self) :
print ( 'show方法被调用执行了' )
with MyContentMgr( ) as file :
file . show( )
def f10 ( n) :
while True :
i= input ( '请选择您的文件类型:1.txt 2.jpg 3.png 4.jpeg 5.mp3 6.mp4 7.docx:' )
if i== '1' :
type = '.txt'
elif i== '2' :
type = '.jpg'
elif i== '3' :
type = '.png'
elif i== '4' :
type = '.jpeg'
elif i== '5' :
type = '.mp3'
elif i== '6' :
type = '.mp4'
elif i== '7' :
type = '.docx'
else :
print ( '不支持的文件类型' )
continue
filename= input ( '请输入您的文件名:' )
try :
with open ( filename+ type , 'rb' ) as file :
with open ( filename+ f'( { n} )' + type , 'wb' ) as target:
target. write( file . read( ) )
except :
print ( '未找到相应文件' )
flag= input ( '按q退出或按任意键继续:' )
if flag== 'q' :
break
if __name__ == '__main__' :
n= 1
while 1 :
ans= input ( '请选择要执行的函数:1,2,3,10\n' )
if ans== '1' :
f1( )
elif ans== '2' :
f2( )
elif ans== '3' :
f3( n)
n+= 1
elif ans== '10' :
f10( n)
n+= 1
else :
print ( '不是有效字符' )
res= input ( '按q退出或按其他任意键继续' )
print ( '' . center( 40 , '=' ) )
if res== 'q' :
break
列表
'''列表的创建'''
list1= [ 'hello' , 'windows' , 98 , True ]
list2= list ( [ 'hello' , 'windows' , 98 , True ] )
print ( list1, id ( list1) , type ( list1) )
print ( list2, id ( list2) , type ( list2) )
'''获取元素的索引'''
list3= [ 'hello' , 'world' , 98 , 'hello' ]
'''
index()
若列表中存在N个相同元素,则指返回所查第一个元素的索引
若所查元素不存在列表中,则出现ValueError
还可以在指定start和stop中进行查找
'''
print ( list3. index( 'hello' ) )
try :
print ( list3. index( 77 ) )
except ValueError:
print ( '所查元素在该列表中不存在' )
print ( list3. index( 'world' , 1 , 4 ) )
'''获取列表中的单个元素'''
print ( list3)
print ( list3[ 1 ] )
print ( list3[ - 3 ] )
'''
列表的切片
语法格式:list[start:stop:step]
切片的结果:原列表的片段的拷贝
step默认为1:[start:stop]
建立原列表的副本:[:]
step为正数:
[:stop:step] [:stop]
[start::step] [start:]
step为负数:(切片时往前数)
[:stop:step]
[start::step]
'''
list1= [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ]
list2= list1[ : ]
list3= list1[ 2 : 5 ]
list4= list1[ - 4 : - 7 : - 1 ]
list5= list1[ - 4 : - 7 ]
list6= list1[ - 4 : ]
list7= list1[ : - 4 ]
list8= list1[ : : - 1 ]
print ( list1, id ( list1) )
print ( list2, id ( list2) )
print ( list3, id ( list3) )
print ( list4, id ( list4) )
print ( list5, id ( list5) )
print ( list6, id ( list6) )
print ( list7, id ( list7) )
print ( list8, id ( list8) )
'''判断对象在列表中是否存在——in not in'''
list1= [ 'hello' , 'world' , 98 , 'hello' ]
print ( 'hello' in list1)
print ( 98 not in list1)
'''使用for_in遍历列表中的元素'''
for item in list1[ : : - 1 ] :
print ( item)
'''
列表元素的增加操作:
append()
extend()
insert()
切片
'''
list1= [ 'hello' , 'world' , 98 , 'hello' ]
print ( '添加之前:' , list1, id ( list1) )
list1. append( 'Autumn' )
print ( '添加之后:' , list1, id ( list1) )
list2= [ 10 , 20 , 30 ]
list1. append( list2)
print ( list1, '\n' , list1[ - 1 ] )
list1. extend( list2)
print ( list1)
list1. insert( 2 , 'Jack' )
print ( list1)
list1[ 1 : ] = [ 1 , 2 , 3 , 4 , 5 ]
print ( list1)
list1[ 1 : 1 ] = [ 10 , 20 , 30 ]
print ( list1)
'''
列表的删除操作:
remove() list.remove(elemenet)
pop() list.pop(index) list.pop()
切片 [start:stop]=[]
clear() list.clear()
del del list
'''
list1= [ 1 , 2 , 2 , 3 , 4 , 4 , 4 , 4 , 4 , 5 , 6 , 7 , 8 ]
print ( list1)
list1. remove( 2 )
print ( list1)
while 4 in list1:
list1. remove( 4 )
print ( list1)
list1. extend( [ 9 , 10 ] )
list1[ 3 : 3 ] = [ 4 ]
print ( list1)
a1= list1. pop( )
print ( list1, a1)
list1. pop( 3 )
print ( list1)
list1[ 3 : 7 ] = [ ]
print ( list1)
list1. clear( )
print ( list1)
del list1
'''列表元素的修改:使用索引或者切片'''
list1= [ 10 , 20 , 30 , 40 , 50 , 60 ]
print ( list1)
list1[ 3 ] = 400
print ( list1)
list1[ : 3 ] = [ 'a' , 'b' , 'c' , 'd' ]
print ( list1)
'''
列表元素的排序:
list.sort() list.sort(reverse=False) 升序排序
list.sort(reverse=True) 降序排序
sorted(list) 升序排序,返回一个列表
sorted(list,reverse=True) 降序排序
'''
list1= [ 5 , 6 , 4 , 3 , 7 , 8 , 9 , 1 , 2 ]
print ( '排序前:' , list1, id ( list1) )
list1. sort( )
print ( '升序后:' , list1, id ( list1) )
list1. sort( reverse= True )
print ( '降序后:' , list1)
list2= sorted ( list1)
print ( list1, id ( list1) )
print ( list2, id ( list2) )
list3= sorted ( list1, reverse= True )
print ( list3, id ( list3) )
'''列表生成式'''
list1= [ i for i in range ( 10 ) ]
list2= [ i* i for i in range ( 10 ) ]
print ( list1, '\n' , list2)
变量的作用域
def fun ( a, b) :
c = a + b
return c
poem = '世事一场大梦,人生几度秋凉'
def fun1 ( ) :
print ( poem)
fun1( )
def fun2 ( ) :
global poem2
poem2= '人生如逆旅,我亦是行人'
print ( '' . center( 40 , '=' ) )
fun2( )
print ( poem2)
异常处理机制
'''
多个except结构:
try:
pass
except Exception1:
pass
except Exception2:
pass
except BaseException:
pass
'''
def f1 ( ) :
try :
n1= int ( input ( "请输入以一个整数:" ) )
n2= int ( input ( '请输入另一个整数' ) )
result= n1/ n2
print ( result)
except ZeroDivisionError:
print ( '除数不能为0' )
except ValueError:
print ( '不能将非数字串转换为数字' )
except BaseException as e:
print ( e)
'''try-except-else结构'''
def f2 ( ) :
try :
print ( '' . ljust( 40 , '=' ) )
n1= int ( input ( "请输入以一个整数:" ) )
n2= int ( input ( '请输入另一个整数' ) )
result= n1/ n2
except BaseException as e:
print ( '出错了' , e)
else :
print ( result)
'''try-except-else-finally结构'''
def f3 ( ) :
try :
n1= int ( input ( "请输入以一个整数:" ) )
n2= int ( input ( '请输入另一个整数' ) )
result= n1/ n2
except BaseException as e:
print ( '出错了' , e)
else :
print ( result)
finally :
print ( '程序结束,不管出没出错都会执行' )
'''traceback——捕获异常信息'''
import traceback
def f4 ( ) :
try :
print ( 1 / 0 )
except :
traceback. print_exc( )
time= 0
while True :
try :
ans= int ( input ( '请选择您要执行的函数:1 2 3 4' ) )
except :
print ( '非合法字符' )
else :
if ans== 1 :
f1( )
elif ans== 2 :
f2( )
elif ans== 3 :
f3( )
elif ans== 4 :
f4( )
else :
print ( '所选内容不在可执行的序列内' )
flag= input ( '按q退出或按其他任意键继续:' )
time+= 1
print ( f'循环执行次数 { time} ' . center( 40 , '=' ) )
if flag== 'q' :
break
带附件的发送
import smtplib
from email. mime. text import MIMEText
from email. mime. image import MIMEImage
from email. mime. multipart import MIMEMultipart
from email. mime. application import MIMEApplication
if __name__ == '__main__' :
fromaddr = '137xxxx@163.com'
password = 'password'
toaddrs = [ '137xxxx@163.com' , '137xxxx@qq.com' ]
content = 'hello, this is email content.'
textApart = MIMEText( content)
imageFile = '1.png'
imageApart = MIMEImage( open ( imageFile, 'rb' ) . read( ) , imageFile. split( '.' ) [ - 1 ] )
imageApart. add_header( 'Content-Disposition' , 'attachment' , filename= imageFile)
pdfFile = '算法设计与分析基础第3版PDF.pdf'
pdfApart = MIMEApplication( open ( pdfFile, 'rb' ) . read( ) )
pdfApart. add_header( 'Content-Disposition' , 'attachment' , filename= pdfFile)
zipFile = '算法设计与分析基础第3版PDF.zip'
zipApart = MIMEApplication( open ( zipFile, 'rb' ) . read( ) )
zipApart. add_header( 'Content-Disposition' , 'attachment' , filename= zipFile)
m = MIMEMultipart( )
m. attach( textApart)
m. attach( imageApart)
m. attach( pdfApart)
m. attach( zipApart)
m[ 'Subject' ] = 'title'
try :
server = smtplib. SMTP( 'smtp.163.com' )
server. login( fromaddr, password)
server. sendmail( fromaddr, toaddrs, m. as_string( ) )
print ( 'success' )
server. quit( )
except smtplib. SMTPException as e:
print ( 'error:' , e)
随机数
import random
print ( random. randint( 1 , 10 ) )
print ( random. random( ) )
print ( random. uniform( 1.1 , 5.4 ) )
print ( random. choice( [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 0 ] ) )
print ( random. randrange( 1 , 100 , 2 ) )
a= [ 1 , 3 , 5 , 6 , 7 ]
random. shuffle( [ 1 , 3 , 5 , 6 , 7 ] )
print ( a)
import numpy as np
print ( np. random. rand( 5 , 5 , 5 ) )
print ( np. random. randn( 5 , 5 , 5 ) )
print ( np. random. randint( 1 , 50 , 5 ) )
print ( np. random. random( 10 ) )
print ( np. random. choice( [ 2 , 5 , 7 , 8 , 9 , 11 , 3 ] ) )
item = [ 2 , 5 , 7 , 8 , 9 , 11 , 3 ]
np. random. shuffle( item)
print ( item)
import random
price= random. randint( 1 , 10 )
guess= int ( input ( '请输入竞猜的数字' ) )
if guess> price:
print ( '大了' )
elif guess< price:
print ( '小了' )
else :
print ( '你猜对了' )
print ( price)
continue与break
print ( '使用continue:' )
for item in range ( 1 , 51 ) :
if item% 5 != 0 :
continue
print ( item)
for _ in range ( 3 ) :
key= int ( input ( '请输入您的账户密码:' ) )
if key== 6666 :
print ( '密码正确' )
break
else :
print ( '密码错误,请重新输入' )
else :
print ( '三次密码均输入错误,账户已被冻结' )
颜色控制
'''
语法:
\033[显示方式; 前景色; 背景色m******\033[0m
'''
print ( '修改颜色' . center( 40 , '=' ) )
print ( "\033[31m这是红色字体\033[0m" )
print ( "\033[32m这是绿色字体\033[m" )
print ( "\033[33m这是黄色字体\033[" )
print ( "\033[34m这是蓝色字体\033" )
print ( "\033[38m这是默认字体\033" )
print ( '单句进行前景色背景色填充' . center( 40 , '=' ) )
print ( "\033[0;31;42m这是默认红色字体背景绿色\033[0m" )
print ( "\033[1;32;43m这是高亮绿色字体背景黄色\033[0m" )
print ( "\033[4;33;45m这是下划线黄色字体背景紫红色\033[0m" )
print ( "\033[5;34;46m这是闪烁蓝色字体背景青蓝色\033[0m" )
print ( '多行操作' . center( 40 , '=' ) )
print ( "\033[4;35;43m平生不会相思," )
print ( "才会相思,便害相思。" )
print ( "身似浮云,心如飞絮," )
print ( "气若游丝。" )
print ( "空一缕馀香在此," )
print ( "盼千金游子何之。" )
print ( "证候来时,正是何时?" )
print ( "灯半昏时,月半明时。\033[0m" )
异常处理机制
'''
多个except结构:
try:
pass
except Exception1:
pass
except Exception2:
pass
except BaseException:
pass
'''
def f1 ( ) :
try :
n1= int ( input ( "请输入以一个整数:" ) )
n2= int ( input ( '请输入另一个整数' ) )
result= n1/ n2
print ( result)
except ZeroDivisionError:
print ( '除数不能为0' )
except ValueError:
print ( '不能将非数字串转换为数字' )
except BaseException as e:
print ( e)
'''try-except-else结构'''
def f2 ( ) :
try :
print ( '' . ljust( 40 , '=' ) )
n1= int ( input ( "请输入以一个整数:" ) )
n2= int ( input ( '请输入另一个整数' ) )
result= n1/ n2
except BaseException as e:
print ( '出错了' , e)
else :
print ( result)
'''try-except-else-finally结构'''
def f3 ( ) :
try :
n1= int ( input ( "请输入以一个整数:" ) )
n2= int ( input ( '请输入另一个整数' ) )
result= n1/ n2
except BaseException as e:
print ( '出错了' , e)
else :
print ( result)
finally :
print ( '程序结束,不管出没出错都会执行' )
'''traceback——捕获异常信息'''
import traceback
def f4 ( ) :
try :
print ( 1 / 0 )
except :
traceback. print_exc( )
time= 0
while True :
try :
ans= int ( input ( '请选择您要执行的函数:1 2 3 4' ) )
except :
print ( '非合法字符' )
else :
if ans== 1 :
f1( )
elif ans== 2 :
f2( )
elif ans== 3 :
f3( )
elif ans== 4 :
f4( )
else :
print ( '所选内容不在可执行的序列内' )
flag= input ( '按q退出或按其他任意键继续:' )
time+= 1
print ( f'循环执行次数 { time} ' . center( 40 , '=' ) )
if flag== 'q' :
break
元组
'''元组和字符串一样,是不可变序列,没有增删改操作'''
'''元组的创建'''
t1= ( 'python' , 'world' , 98 , True )
print ( t1, type ( t1) , id ( t1) )
t1= tuple ( ( 'hello' , 'world' , 98 , False ) )
print ( t1, type ( t1) , id ( t1) )
t2= 'hello' , 'world' , 98 , False
print ( t1, type ( t1) , id ( t1) )
t3= 99 , 89 , 76 , 55
print ( t3, type ( t3) )
t4= ( 89 )
print ( t4, type ( t4) )
t4= ( 'python' , )
print ( t4, type ( t4) )
l1= [ ]
l2= list ( )
d1= { }
d2= dict ( )
t1= ( )
t2= tuple ( )
print ( l1, l2, d1, d2, t1, t2)
'''元组中存储的数据类型,以及用索引去访问元素'''
t= ( 10 , [ 20 , 30 ] , 40 )
print ( t, type ( t) , id ( t) )
print ( t[ 0 ] , type ( t[ 0 ] ) , id ( t[ 0 ] ) )
print ( t[ 1 ] , type ( t[ 1 ] ) , id ( t[ 1 ] ) )
print ( t[ 2 ] , type ( t[ 2 ] ) , id ( t[ 2 ] ) )
t[ 1 ] . append( 100 )
print ( t, type ( t) , id ( t) )
print ( t[ 1 ] , type ( t[ 1 ] ) , id ( t[ 1 ] ) )
t[ 1 ] [ : ] = [ 666 , 777 , 888 ]
print ( t, type ( t) , id ( t) )
print ( t[ 1 ] , type ( t[ 1 ] ) , id ( t[ 1 ] ) )
'''元组的遍历'''
t= ( '且将新火试新茶' , '诗酒趁年华' , [ 20 , 30 ] , 40 )
for item in t:
print ( item)
运算符
print ( '1+2=' , 1 + 2 )
print ( '2-0.7=' , 2 - 0.7 )
print ( '3*9=' , 3 * 9 )
print ( '9/4=' , 9 / 4 )
print ( '9//4=' , 9 // 4 )
print ( '9%4=' , 9 % 4 )
print ( '2**3=' , 2 ** 3 )
print ( '9//4=' , 9 // 4 )
print ( '-9//4=' , - 9 // 4 )
print ( '9//-4=' , 9 // - 4 )
print ( '9%4=' , 9 % 4 )
print ( '9%-4=' , 9 % - 4 )
print ( '-9%4=' , - 9 % 4 )
i= 3 + 4
print ( i)
a= b= c= 666
print ( a, id ( a) )
print ( b, id ( b) )
print ( c, id ( c) )
a= 10
print ( a, type ( a) )
a+= 10
print ( a, type ( a) )
a*= 10
print ( a, type ( a) )
a/= 3
print ( a, type ( a) )
a//= 5
print ( a, type ( a) )
a%= 10
print ( a, type ( a) )
a, b, c, d, e, f= 10 , 20 , 30 , 'hello' , True , 66.66
print ( a, b, c, d, e, f)
print ( '交换之前:a,b,c,d,e,f:' , a, b, c, d, e, f)
a, b, c, d, e, f= f, e, d, c, b, a
print ( '交换之后:a,b,c,d,e,f:' , a, b, c, d, e, f)
a, b= 10 , 20
print ( 'a>b' , a> b)
print ( 'a<b' , a< b)
print ( 'a>=b' , a>= b)
print ( 'a<=b' , a<= b)
print ( 'a==b' , a== b)
print ( 'a!b' , a!= b)
a= 10
b= 10
print ( 'a==b' , a== b)
print ( 'a is b' , a is b)
list1= [ 10 , 20 , 30 , 40 ]
list2= [ 10 , 20 , 30 , 40 ]
print ( list1, id ( list1) )
print ( list2, id ( list2) )
print ( 'list1==list2' , list1== list2)
print ( 'list1 is list2' , list1 is list2)
print ( 'list1 is not list2' , list1 is not list2)
a= True
b= False
print ( 'a and b' , a and b)
print ( 'a or b' , a or b)
print ( 'not a' , not a)
str1= 'hello world'
print ( 'wor in str1' , 'wor' in str1)
print ( 'o not in str1' , '0' not in str1)
print ( '4&8' , 4 & 8 )
print ( '4|8' , 4 | 8 )
print ( 4 & 8 )
print ( 4 | 8 )
print ( '4<<1' , 4 << 1 )
print ( '4<<2' , 4 << 2 )
print ( '4>>1' , 4 >> 1 )
print ( '4>>2' , 4 >> 2 )
转义字符
'''
反斜杠: \\
单引号: \'
双引号: \"
回车: \r
换行: \n
水平制表符: \t
退格: \b
'''
print ( 'hello\nworld' )
print ( 'hello\tworld' )
print ( 'helllooo\tworld' )
print ( 'hello\bworld' )
print ( 'hello\rworld' )
print ( 'http//:www.bilibili.com' )
print ( 'C:\\Users\\霜秋-晓醉\\AppData' )
print ( '\'且将新火试新茶,诗酒趁年华\'' , '\n' , "'且将新火试新茶,诗酒趁年华'" )
print ( r"hello\nworld" )
print ( r'hello\\' )
字典
'''字典中的key是不可变序列,字符串是不可变序列'''
'''
字典的创建:
使用{}
使用内置函数dict()
'''
scores= { 'Jack' : 100 , 'Bill' : 88 , 'Anni' : 78 , 'Steve' : 90 }
print ( scores)
student1= dict ( name= 'Jack' , age= 22 )
print ( student1)
dict1= { }
print ( dict1)
'''字典元素的访问'''
print ( scores[ 'Jack' ] )
print ( scores. get( 'Bill' ) )
print ( scores. get( 'John' ) )
print ( scores. get( 'John' , 99 ) )
print ( scores. get( 'Bill' , 55 ) )
'''字典元素的判断,删除,清空,新增,修改'''
scores= { 'Jack' : 100 , 'Bill' : 88 , 'Anni' : 78 , 'Steve' : 90 }
print ( 'Jack' in scores)
print ( 'Jack' not in scores)
print ( scores)
del scores[ 'Anni' ]
print ( scores)
scores[ 'Tony' ] = 71
print ( scores)
scores[ 'Tony' ] = 100
print ( scores)
scores. clear( )
print ( scores)
del scores
'''
获取字典中的元素:
dict.keys()
dict.values()
dict.items()
'''
scores= { 'Jack' : 100 , 'Bill' : 88 , 'Anni' : 78 , 'Steve' : 90 }
keys= scores. keys( )
values= scores. values( )
items= scores. items( )
print ( keys, type ( keys) )
print ( values, type ( values) )
print ( items, type ( items) )
print ( list ( keys) )
print ( list ( values) )
print ( list ( items) )
'''字典元素的遍历'''
for i in scores:
print ( i, scores[ i] , scores. get( i) )
for i in scores. keys( ) :
print ( i)
for i in scores. values( ) :
print ( i)
for i in scores. items( ) :
print ( i)
'''字典中的键不允许重复,一旦重复,会出现值覆盖的情况'''
scores= { 'Jack' : 100 , 'Jack' : 88 , 'Anni' : 100 , 'Steve' : 100 }
print ( scores)
'''字典生成式:{key:value for key,value in zip(list1,list2)}'''
names= [ 'Jack' , 'Bill' , 'Anni' , 'John' ]
scores= [ 99 , 88 , 77 , 66 ]
dict1= { name: score for name, score in zip ( names, scores) }
print ( dict1)
weights= [ 120 , 110 , 100 , 90 , 80 , 70 ]
dict2= { i: j for i, j in zip ( names, weights) }
print ( dict2)
input函数
a= input ( '请输入一个加数:' )
b= input ( '请输入另一个加数:' )
print ( a+ b)
print ( type ( a) , type ( b) )
a= float ( input ( '请输入一个加数:' ) )
b= float ( input ( '请输入另一个加数:' ) )
print ( a+ b)
print ( type ( a) , type ( b) )
os模块
import os
'''
os.system('notepad.exe') #command命令
os.system('calc.exe') #win+r clac
'''
'''
os模块的相关操作:
getcwd():返回当前的工作目录
listdir(path):返回指定路径下的文件和目录信息
mkdir(path,[mode]):创建目录
makedirs(path1/path2...,[mode]):创建多级目录
rmdir(path):删除目录
removedirs(path1,path2...):删除多级目录
chdir(path):将path设置为当前工作目录
'''
print ( os. getcwd( ) )
print ( '返回当前目录下的文件' . center( 40 , '-' ) )
print ( os. listdir( ) )
print ( os. listdir( '.\\' ) )
print ( os. listdir( './' ) )
print ( '返回上一级目录的文件' . center( 40 , '-' ) )
print ( os. listdir( '..\\' ) )
print ( os. listdir( '../' ) )
print ( '返回上上一级目录的文件' . center( 40 , '-' ) )
print ( os. listdir( '..\\..\\' ) )
print ( os. listdir( '../../' ) )
print ( '返回Folder中的文件' . center( 40 , '-' ) )
print ( os. listdir( 'Folder' ) )
print ( os. listdir( '.\\Folder' ) )
print ( os. listdir( './Folder' ) )
print ( os. listdir( '..\\..\\vippython\\杨淑娟\\Folder' ) )
print ( os. listdir( '../../vippython/杨淑娟/Folder' ) )
print ( os. getcwd( ) )
print ( '获取指定目录下所有的python文件' . center( 40 , '-' ) )
for file_name in os. listdir( ) :
if file_name. endswith( '.py' ) :
print ( file_name)
print ( '获取指定目录下的所有文件及其子文件' . center( 40 , '-' ) )
path= 'C:\\Users\\霜秋-晓醉\\Documents\\python项目文件\\vippython'
lst_files= os. walk( path)
print ( lst_files, type ( lst_files) )
for i in lst_files:
print ( i)
print ( type ( i) )
print ( '' . center( 40 , '-' ) )
print ( '\n\n\n\n' )
lst_files= os. walk( path)
for dirpath, dirname, file_name in lst_files:
print ( '' . center( 40 , '-' ) )
for dir in dirname:
print ( os. path. join( dirpath, dir ) )
for file in file_name:
print ( os. path. join( dirpath, file ) )
python中常用的内容模块
import sys
print ( sys. getsizeof( 55 ) )
print ( sys. getsizeof( 77 ) )
print ( sys. getsizeof( True ) )
print ( sys. getsizeof( False ) )
import time
print ( time. time( ) )
print ( time. localtime( time. time( ) ) )
import urllib
import urllib. request
ans= input ( '是否要读取网站上的数据?y/n:' )
if ans== 'y' :
print ( urllib. request. urlopen( 'http://eol.yzu.edu.cn/meol/index.do' ) . read( ) )
import math
print ( math. pi)
python中的标识符
import keyword
print ( keyword. kwlist)
range函数
r1= range ( 10 )
print ( r1)
print ( list ( r1) )
print ( range ( 1 , 10 ) )
print ( list ( range ( 1 , 10 ) ) )
print ( range ( 1 , 2 , 20 ) )
print ( list ( range ( 1 , 20 , 2 ) ) )
print ( 10 in range ( 10 ) )
print ( 10 not in range ( 10 ) )
包
import 模块
'''
包和文件的不同在于包内含有一个__init__.py的文件
一般把多个类似的模块放在同一个包内
'''
import Package1. pi
print ( Package1. pi. pi)
import Package1. add as fun
print ( fun. add( 10 , 20 ) )
'''
使用import只能导入包名或模块名
import package
import module
使用from import可以导入包名,模块名,函数名,变量名,类名
from package1 import package2
from package import module
from module import a,b,c
'''
变量的定义与使用
name= 'Autumn'
print ( '标识:' , id ( name) )
print ( '类型:' , type ( name) )
print ( '值:' , name)
name= 'Jack'
print ( '标识:' , id ( name) )
print ( '类型:' , type ( name) )
print ( '值:' , name)
递归函数
def fac ( n) :
if n== 1 :
return 1
else :
res= n* fac( n- 1 )
return res
def print_fac ( n) :
print ( f' { n} 的阶乘为: { fac( n) } ' )
for i in range ( 1 , n) :
print ( str ( i) + '*' , end= '' )
print ( str ( n) + '=' + str ( fac( n) ) )
print ( '' . center( 40 , '=' ) , '\n\n' )
for i in range ( 1 , 10 ) :
print_fac( i)
def fib ( n) :
if n== 1 or n== 2 :
return 1
else :
res= fib( n- 1 ) + fib( n- 2 )
return res
print ( '斐波那契数列' . center( 40 , '-' ) )
l= [ ]
for i in range ( 1 , 10 ) :
print ( fib( i) , end= ',' )
l. append( fib( i) )
print ( '\n' , l)
第三方模块的安装与使用
'''
第三方模块的安装:
在cmd模式下使用pip安装:
pip install pygame
pip install schedule
镜像安装?我也不太懂,后期可以在网络上学习一下
使用pycharm在解释器中点击左下角+号安装
在python官网安装
'''
import schedule
import time
def job ( ) :
print ( '我与春风皆过客,你携秋水揽星河' )
schedule. every( 1 ) . seconds. do( job)
while 1 :
schedule. run_pending( )
time. sleep( 1 )
对象的布尔值
print ( '以下对象布尔值为False:' )
print ( bool ( False ) )
print ( bool ( 0 ) )
print ( bool ( 0.0 ) )
print ( bool ( '' ) )
print ( bool ( "" ) )
print ( bool ( [ ] ) )
print ( bool ( list ( ) ) )
print ( bool ( ( tuple ( ) ) ) )
print ( bool ( { } ) )
print ( bool ( dict ( ) ) )
print ( bool ( set ( ) ) )
print ( '其他对象的布尔值都为True' )
print ( bool ( 'hello world' ) )
函数
'''
在函数调用过程中,进行参数的传递
如果是可变对象实参,则函数会影响到实参的值
如果是不可变实参,则函数不会影响到实参的值
'''
def fun1 ( a, b) :
a= a** 2
b. append( 'autumn' )
print ( 'n' , a)
print ( 'l' , b)
n, l= 9 , [ 'hello' , 98 ]
print ( 'n' , n)
print ( 'l' , l)
fun1( n, l)
print ( 'n' , n)
print ( 'l' , l)
'''
函数的返回值:
可以没有返回值
返回值为一个时返回原类型
返回值为多个时返回元组
'''
def fun2 ( list ) :
odd, even= [ ] , [ ]
for num in list :
if num% 2 :
odd. append( num)
else :
even. append( num)
return odd, even
list1= [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 11 , 22 , 33 , 44 , 55 , 66 , 77 , 88 , 99 ]
print ( fun2( list1) )
print ( type ( fun2( list1) ) )
'''函数的默认值参数'''
def fun3 ( a, b= 'hello' ) :
print ( a, b)
fun3( 10 )
fun3( 10 , 888 )
print ( '指定默认值参数实现不换行输出' , end= '\t' )
print ( '' . center( 40 , '-' ) )
'''
个数可变的位置参数: * 传到形参的结果为一个元组
个数可变的关键字形参: ** 传到形参的结果为一个字典
'''
def fun4 ( * args) :
print ( args)
print ( type ( args) )
print ( '' . center( 40 , '-' ) )
def fun5 ( ** args) :
print ( args)
print ( type ( args) )
print ( '' . center( 40 , '-' ) )
fun4( 1 )
fun4( 'hello' , 'world' , 'python' , 98 )
l= [ '且将新火试新茶' , 'hello' , 'world' , 'python' ]
fun4( l)
fun4( * l)
fun5( Jack= 44 , Tony= 'tall' )
d= { '苏轼' : '江城子-密州出猎' , '辛弃疾' : '青玉案' , '李清照' : '声声慢' , '柳永' : '雨霖铃' }
fun5( ** d)
'''
个数可变的位置形参最多定义一个
个数可变的关键字形参最多定义一个
若两者同时存在,再个数可变的位置形参要定义在个数可变的关键字形参前面
'''
def fun6 ( * args1, ** args2) :
pass
def fun7 ( a, b, * , c, d) :
print ( 'a=' , a, ' b=' , b, ' c=' , c, ' d=' , d)
print ( '' . center( 40 , '=' ) )
fun7( '苏轼' , '辛弃疾' , c= '李清照' , d= '柳永' )
'''函数定义时的形参顺序问题'''
def fun8 ( a, b, * , c, d) :
pass
def fun9 ( * a, ** b) :
pass
def fun10 ( a, b= 666 , * c, ** d) :
pass
集合
'''集合是只有键的字典'''
'''集合的创建'''
s= { 1 , 2 , 2 , 3 , 4 , 4 , 4 , 'hello' , True , }
print ( s)
s1= set ( range ( 10 ) )
print ( s1, type ( s1) )
s2= set ( [ 1 , 2 , 3 , 4 , 5 , 890 ] )
print ( s2, type ( s2) )
s3= set ( ( 1 , 2 , 4 , 5 , 6 , 345 , 888 , 65 ) )
print ( s3, type ( s3) )
s4= set ( 'python' )
print ( s4, type ( s4) )
s5= set ( { 1 , 3 , 4 , 2 , 6 } )
print ( s5, type ( s5) )
s= set ( )
print ( s, type ( s) )
'''
集合的相关操作:
判断 in not in
增加 set.add() set.update()
删除 set.remove() set.discard()
修改
'''
s= { 10 , 20 , 30 , 40 }
print ( 10 in s, 10 not in s)
s. add( 50 )
print ( s)
s. update( { 60 , 70 , 80 } )
s. update( [ 'hello' , 'world' ] )
s. update( ( 78 , True ) )
print ( s)
s. remove( 'hello' )
print ( s)
s. discard( 70 )
s. discard( '且将新火试新茶' )
print ( s)
s. pop( )
print ( s)
s. clear( )
print ( s)
'''集合之间的关系:
等于:== 不等于:!=
子集:s1.issubset(s2)
超集:s1.issuperset(s2)
交集:s1.isdisjoint(s2)
'''
s1= { 1 , 2 , 3 , 4 , 5 }
s2= { 2 , 3 , 1 , 5 , 4 }
s3= { 1 , 2 , 3 }
s4= { 9 , 2 }
s5= { 100 , 200 , 300 }
print ( s1== s2, s1!= s2)
print ( s3. issubset( s1) , s4. issubset( s2) )
print ( s1. issuperset( s3) , s1. issuperset( ( s4) ) )
print ( s1. isdisjoint( s4) , s1. isdisjoint( ( s5) ) )
'''集合的数学操作:
取交集:s1.intersection(s2) s1 & s2
取并集:s1.union(s2) s1 | s2
取差集:s1.difference(s2) s1-s2
取对称差集:s1.symmetric_difference(s2) s1 ^ s2
'''
s1= { 1 , 2 , 3 , 4 , 5 , 6 , 7 }
s2= { 9 , 8 , 7 , 6 , 5 , 4 , 3 }
print ( s1. intersection( s2) )
print ( s1 & s2)
print ( s1. union( s2) )
print ( s1 | s2)
print ( s1. difference( s2) )
print ( s1- s2)
print ( s1. symmetric_difference( s2) )
print ( s1 ^ s2)
'''集合生成式'''
l= [ i** 3 for i in range ( 10 ) ]
s= { i** 3 for i in range ( 10 ) }
print ( l, type ( l) )
print ( s, type ( s) )
进制转换
n= eval ( input ( '请输入一个数字:' ) )
print ( type ( n) )
print ( bin ( n) , type ( ( bin ( n) ) ) )
print ( oct ( n) , type ( oct ( n) ) )
print ( hex ( n) , type ( hex ( n) ) )
类
'''
class Student: #创建类对象
def __init__(self,arg1,arg2):
self.arg1=arg1
def fun(self):
stu1=Student(arg1,arg2) #根据类对象创建实例对象
stu1.fun() #实例名.方法名
Student.fun(stu1) #类名.方法名(实例名)
print(Student,type(Student),id(Student))'''
'''
类里面定义的函数称为方法:
初始化方法:
def __init__(self,arg1,arg2):
self.arg1=arg1 self.arg1称为属性,将实参arg1赋值给属性self.arg1
self.arg2=arg2
实例方法:
def fun(self):
静态方法:(使用@staticmethod进行修饰) 使用类名直接访问
@staticmethod
def fun():
类方法:(使用@classmethod进行修饰)使用类名直接访问
@classmethod
def fun(cls):
'''
'''可以在类之外单独的给实例对象动态地绑定属性和方法'''
'''
stu1.score=100 #单独的给stu1绑定属性score
def fun3():
pass
stu1.fun3() #单独的给实例stu1绑定方法fun3
动态绑定的属性和方法只针对绑定的实例有用
'''
'''
不希望属性再类的外部被使用,可以在属性前加__
class Student:
def __init__(self,name,age):
self.__name=name
self.__age=age
stu1=Student('张三',20)
#print(stu1.__name) 外部无法访问
print(dir(stu1)) #查看对象中的属性和方法
print(stu1._Student__age) #在类的外部可使用_Student__age访问
'''
'''类的继承'''
class Person ( object ) :
def __init__ ( self, name, age) :
self. name= name
self. age= age
def info ( self) :
print ( self. name, self. age)
class Student ( Person) :
def __init__ ( self, name, age, stu_num) :
super ( ) . __init__( name, age)
self. stu_num= stu_num
def info ( self) :
super ( ) . info( )
print ( self. stu_num)
class Teacher ( Person) :
def __init__ ( self, name, age, teachofyear) :
super ( ) . __init__( name, age)
self. teachofyear= teachofyear
class Third_Person ( Teacher, Student) :
pass
stu1= Student( '张三' , 20 , 201803314 )
teacher1= Teacher( '李四' , 40 , 10 )
stu1. info( )
teacher1. info( )
'''在不指定父类的情况下,所有类默认继承object类'''
class Box ( ) :
def __init__ ( self, material) :
self. material= material
def __str__ ( self) :
return f'这是一个 { self. material} 的箱子'
class Water :
pass
print ( dir ( Box) )
fenda= Water( )
print ( dir ( fenda) )
box1= Box( '木头' )
print ( box1)
'''特殊的属性和方法'''
print ( dir ( object ) )
class A :
pass
class B :
pass
class C ( A, B) :
def __init__ ( self, name, age) :
self. name= name
self. age= age
class D ( A) :
pass
x= C( 'Jack' , 20 )
print ( x. __dict__)
print ( C. __dict__)
print ( x. __class__)
print ( C. __bases__)
print ( C. __base__)
print ( C. __mro__)
print ( A. __subclasses__( ) )
a= 10
b= 20
print ( a+ b, a. __add__( b) , dir ( a) )
class AA :
def __init__ ( self, name) :
self. name= name
def __add__ ( self, other) :
return self. name+ other. name
def __len__ ( self) :
return len ( self. name)
aa1, aa2= AA( '张三' ) , AA( '李四' )
print ( aa1+ aa2, aa1. __add__( aa2) )
l= [ 1 , 2 , 3 , 4 , 5 , 6 , 7 ]
print ( dir ( l) , l. __len__( ) , len ( l) )
类2
class Person ( object ) :
def __new__ ( cls, * args, ** kwargs) :
print ( '__new__被调用执行了,cls的id值为{0}' . format ( id ( cls) ) )
obj= super ( ) . __new__( cls)
print ( '创建的对象的id为:{0}' . format ( id ( obj) ) )
return obj
def __init__ ( self, name, age) :
print ( '__init__被调用了,self的id值为:{0}' . format ( id ( self) ) )
self. name= name
self. age= age
print ( 'object这个类对象的id为:{0}' . format ( id ( object ) ) )
print ( 'Person这个类对象的id为:{0}' . format ( id ( Person) ) )
p1= Person( '张三' , 20 )
print ( 'p1这个Person类的实例对象的id为:{0}' . format ( id ( p1) ) )
类的赋值与浅拷贝
class CPU :
pass
class Disk :
pass
class Computer :
def __init__ ( self, cpu, disk) :
self. cpu= cpu
self. disk= disk
cpu1= CPU( )
cpu2= cpu1
print ( id ( cpu1) , id ( cpu2) )
print ( '' . ljust( 40 , '-' ) )
disk1= Disk( )
computer1= Computer( cpu1, disk1)
import copy
computer2= copy. copy( computer1)
computer3= copy. deepcopy( computer1)
print ( computer1, computer1. cpu, computer1. disk)
print ( '' . ljust( 40 , '-' ) )
print ( computer2, computer2. cpu, computer2. disk)
print ( '' . ljust( 40 , '-' ) )
print ( computer3, computer3. cpu, computer3. disk)
模块
import math
print ( id ( math) )
print ( type ( math) )
print ( math)
print ( math. pi)
print ( 'math中包含的内容' . center( 40 , '=' ) )
print ( dir ( math) )
print ( math. ceil( 3.1 ) )
print ( math. floor( 9.7 ) )
'''
import 模块名称 使用句点访问模块内的变量,函数,类
import 模块名称 as 别名
from module_name import a,b,c 直接访问模块内的变量,函数,类
from module_name import * 导入模块所有的类
'''
if __name__ == '__main__' :
print ( '你猜导入我所在的模块的时候你看的到我不' )
嵌套if
def pay_money ( answer, money) :
if answer == 'y' :
if money >= 200 :
print ( '打八折,您需要付款的金额为:' , int ( money * 0.8 ) )
elif 100 <= money < 200 :
print ( '打九折,您需要付款的金额为:' , int ( money * 0.9 ) )
else :
print ( '打九五折,您需要付款的金额为:' , int ( money * 0.95 ) )
elif answer == 'n' :
print ( '不打折,您需要付全款:' , money)
while True :
while True :
answer= input ( '您是会员吗?y/n:' )
if answer== 'y' or answer== 'n' :
break
else :
print ( '非有效选项,请重新进行输入' )
while True :
try :
money = int ( input ( '请输入您的购物金额:' ) )
except ValueError:
print ( '请输入数字!' )
continue
if 0 < money:
break
else :
print ( '您输入的金额有误,请重新进行输入' )
pay_money( answer, money)
print ( )
flag= input ( '请选择接下来的操作:\nq——退出\n按任意键继续\n' )
print ( '--------------------------------' )
if flag== 'q' :
break
嵌套循环
'''绘制矩形'''
for i in range ( 4 ) :
for j in range ( 6 ) :
print ( '*' , end= '\t' )
print ( )
'''绘制下三角'''
for i in range ( 10 ) :
for j in range ( 10 ) :
if i>= j:
print ( '*' , end= '\t' )
print ( )
for i in range ( 10 ) :
for j in range ( i+ 1 ) :
print ( '囧' , end= '\t' )
print ( )
'''绘制乘法表'''
for i in range ( 1 , 10 ) :
for j in range ( 1 , 10 ) :
if i>= j:
print ( str ( j) + '*' + str ( i) + '=' + str ( i* j) , end= '\t' )
print ( )
上下文管理器
class MyContentMgr ( object ) :
def __enter__ ( self) :
print ( '__enter__被调用执行了' )
return self
def __exit__ ( self, exc_type, exc_val, exc_tb) :
print ( '__exit__被调用执行了' )
def show ( self) :
print ( 'show方法被调用执行了' )
with MyContentMgr( ) as file :
file . show( )
输出函数print
print ( 100 )
print ( 100 + 100 )
fy= open ( 'text1.txt' , 'a+' )
print ( '且将新火试新茶\n诗酒趁年华' , file = fy)
fy. close( )
print ( '且将新火试新茶' , '诗酒趁年华' )
数据类型
'''
整数类型:int——98 1000
布尔类型:bool——True False
浮点类型:float——3.1415926
字符串类型:str——'hello' "world"
'''
print ( 100 , type ( 100 ) )
print ( - 98 , type ( - 98 ) )
print ( 0 , type ( 0 ) )
print ( '十进制:' , 666 )
print ( '八进制:' , 0o1234567 )
print ( '十六进制:' , 0x123456789abcdef )
print ( '二进制:' , 0b10110011 )
print ( 1.1 + 2.1 )
print ( 1.1 + 2.2 , '\n' , type ( 1.1 + 2.2 ) )
from decimal import Decimal
print ( Decimal( '1.1' ) + Decimal( '2.2' ) )
b1= True
b2= False
print ( b1, type ( b1) )
print ( b2, type ( b2) )
print ( b1+ 1 )
print ( b2- 2 )
str1= '且将新火试新茶,诗酒趁年华'
str2= "且将新火试新茶,诗酒趁年华"
str3= '''且将新火试新茶,
诗酒趁年华'''
str4= """且将新火试新茶,
诗酒趁年华"""
print ( str1, type ( str1) )
print ( str2, type ( str2) )
print ( str3, type ( str3) )
print ( str4, type ( str4) )
数据类型转换
'''
str()——将其他类型转换为字符串,也可使用引号转换
int()——将其他类型转换成整数,文字和小数类字符串无法转换,浮点数抹零取整
float()——将其他类型转换成浮点数,文字类无法转换,整数后面加.0
'''
a= 10
b= 6.6
c= False
print ( a, type ( a) , b, type ( b) , c, type ( c) )
print ( str ( a) , str ( b) , str ( c) , type ( str ( a) ) , type ( str ( b) ) , type ( str ( c) ) )
s1= '128'
f1= 98.7
s2= '76.77'
b2= True
s3= 'hello'
print ( type ( s1) , type ( f1) , type ( s2) , type ( b2) , type ( s3) )
print ( int ( s1) , type ( int ( s1) ) )
print ( int ( f1) , type ( int ( f1) ) )
print ( int ( b2) , type ( int ( b2) ) )
s1= '128'
n1= 666
s2= '76.77'
b2= True
s3= 'hello'
print ( float ( s1) , type ( float ( s1) ) )
print ( float ( n1) , type ( float ( n1) ) )
print ( float ( s2) , type ( float ( s2) ) )
print ( float ( b2) , type ( float ( b2) ) )
随机数
import random
price= random. randint( 1 , 10 )
guess= int ( input ( '请输入竞猜的数字' ) )
if guess> price:
print ( '大了' )
elif guess< price:
print ( '小了' )
else :
print ( '你猜对了' )
print ( price)
条件表达式和pass语句
'''语句1 if 条件判断 else 语句2'''
num1 = int ( input ( 'num1:' ) )
num2 = int ( input ( 'num2:' ) )
print ( '使用条件表达式进行判断输出' )
print ( str ( num1) + '>=' + str ( num2) if num1 >= num2 else str ( num1) + '<' + str ( num2) )
print ( str ( num1) + '>=' + str ( num2) ) if num1 >= num2 else print ( str ( num1) + '<' + str ( num2) )
if True :
pass
条件语句
def grades1 ( score) :
if score >= 90 and score <= 100 :
print ( 'A' )
elif score >= 80 and score < 90 :
print ( 'B' )
elif score >= 70 and score < 80 :
print ( 'C' )
elif score >= 60 and score < 70 :
print ( 'D' )
elif score >= 0 and score < 60 :
print ( 'E' )
else :
print ( 'error score' )
def grades2 ( score) :
if 90 <= score<= 100 :
print ( '优' )
elif 80 <= score< 90 :
print ( '良' )
elif 70 <= score< 80 :
print ( '中' )
elif 60 <= score< 70 :
print ( '差' )
elif 0 <= score< 60 :
print ( '不及格' )
else :
print ( '输入成绩错误' )
def score_print ( n) :
score = int ( input ( '请输入你的成绩:' ) )
if n== 1 :
grades1( score)
elif n== 2 :
grades2( score)
else :
print ( '所选成绩分类函数不存在' )
print ( )
while True :
flag1= int ( input ( '请选择您的成绩分类系统——1/2:' ) )
while True :
score_print( flag1)
flag2= input ( '请选择接下来操作:\n1——重新选择成绩分类系统\n2——退出\n或按其他任意键继续' )
print ( )
if flag2== '1' or flag2== '2' :
break
if flag2== '2' :
break
elif flag2== '1' :
continue
文件的读写操作
'''
file=open(filename,[mode,encoding]) []代表可省略的参数
'''
def f1 ( ) :
file = open ( 'text1.txt' , 'r' )
print ( file . readlines( ) )
file . close( )
'''
常用的文件打开格式:
r:只读
w:只写
a:附加
b:以二进制打开,需与其他模式一同使用,如:rb,wb,通过二进制可以打开一些记事本打开不了的内容,如mp3,mp4,jpg,png等
+:以读写方式打开,需与其他模式一起用,如:a+
'''
def f2 ( ) :
file = open ( 'text1.txt' , 'a' )
file . write( '我与春风皆过客,你携秋水揽星河\n' )
print ( '星河灿烂,你是人间理想' , file = file )
file . close( )
def f3 ( n) :
current_file= open ( '金克斯.jpg' , 'rb' )
target_file= open ( f'金克斯( { n} ).jpg' , 'wb' )
target_file. write( current_file. read( ) )
target_file. close( )
current_file. close( )
'''
文件对象的常用方法: []表示可省略
file.read([size]) 读取size个字符,若size不指定,则默认全部读取
file.readline() 读取一行内容
file.readlines() 将每一行的内容作为字符串存入列表返回
file.write(str) 写入字符串
file.writelines(s_list) 将字符串列表写入文件
file.seek(offset,[whence]) 把文件指针移动到新的位置上,offset表示相对于whence的位置,为正向后,为负向前,whence——0开始-1当前-2末尾
file.tell() #告诉当前指针的位置
file.flush() 把缓冲区的内容写入文件,但不关闭文件
file.close() 吧缓冲区的内容写入文件同时关闭文件,释放相关资源
'''
def f4 ( ) :
file = open ( 'text1.txt' , 'r' )
file . close( )
def f5 ( ) :
file = open ( 'text2.txt' , 'w' , encoding= 'gbk' )
file . write( '此情应是长相守,你若无心我便休\n' )
file . writelines( [ '半生风雨半生伤,半句别恨半心凉\n' , '一别两宽,各生欢喜\n' , '我愿提笔画天下,许你一世繁华\n' ] )
file . close( )
def f6 ( ) :
file = open ( 'text1.txt' , 'r' )
file . seek( 2 )
print ( file . tell( ) )
print ( file . read( ) )
print ( file . tell( ) )
file . close( )
def f7 ( ) :
file = open ( 'text2.txt' , 'a' , encoding= 'utf-8' )
file . write( '且将新火试新茶,诗酒趁年华\n' )
file . flush( )
file . write( '大江东去,浪淘尽,千古风流人物' )
file . close( )
'''
with as语句可以保证在任何时候都能够正确的关闭文件,称上下文管理器
实现了__enter__方法和__exit__方法,遵守了上下文管理协议'''
def f8 ( ) :
print ( type ( open ( 'text1.txt' , 'r' ) ) )
with open ( 'text1.txt' , 'r' ) as file :
print ( file . read( ) )
def f9 ( ) :
class MyContentMgr ( object ) :
def __enter__ ( self) :
print ( '__enter__被调用执行了' )
return self
def __exit__ ( self, exc_type, exc_val, exc_tb) :
print ( '__exit__被调用执行了' )
def show ( self) :
print ( 'show方法被调用执行了' )
with MyContentMgr( ) as file :
file . show( )
def f10 ( n) :
while True :
i= input ( '请选择您的文件类型:1.txt 2.jpg 3.png 4.jpeg 5.mp3 6.mp4 7.docx:' )
if i== '1' :
type = '.txt'
elif i== '2' :
type = '.jpg'
elif i== '3' :
type = '.png'
elif i== '4' :
type = '.jpeg'
elif i== '5' :
type = '.mp3'
elif i== '6' :
type = '.mp4'
elif i== '7' :
type = '.docx'
else :
print ( '不支持的文件类型' )
continue
filename= input ( '请输入您的文件名:' )
try :
with open ( filename+ type , 'rb' ) as file :
with open ( filename+ f'( { n} )' + type , 'wb' ) as target:
target. write( file . read( ) )
except :
print ( '未找到相应文件' )
flag= input ( '按q退出或按任意键继续:' )
if flag== 'q' :
break
if __name__ == '__main__' :
n= 1
while 1 :
ans= input ( '请选择要执行的函数:1,2,3,10\n' )
if ans== '1' :
f1( )
elif ans== '2' :
f2( )
elif ans== '3' :
f3( n)
n+= 1
elif ans== '10' :
f10( n)
n+= 1
else :
print ( '不是有效字符' )
res= input ( '按q退出或按其他任意键继续' )
print ( '' . center( 40 , '=' ) )
if res== 'q' :
break
循环结构
a= 1
while a< 10 :
print ( a)
a+= 1
'''计算1到100之间的偶数和'''
a= 1
sum = 0
while a<= 100 :
if not a% 2 :
sum += a
a+= 1
print ( sum )
'''
for-in循环
in表达从字符串,序列,列表等中依次取值,又称为遍历
for-in遍历的对象必须是可迭代对象
for 变量 in 可迭代对象:
循环体
'''
for item in 'Python' :
print ( item)
for item in range ( 10 ) :
print ( item)
for _ in range ( 5 ) :
print ( '且将新火试新茶,诗酒趁年华' )
for item in range ( 100 , 1000 ) :
a1= item// 100
a2= item// 10 % 10
a3= item% 10
if item== a1** 3 + a2** 3 + a3** 3 :
print ( item)
邮件名的格式化
from email. header import Header
from email. MIMEMultipart import MIMEMultipart
from email. MIMEText import MIMEText
from email. MIMEBase import MIMEBase
from email. utils import parseaddr, formataddr
import smtplib, time, os
def filepath ( ) :
filepath = "D:\\Python27\\selenium_\\report"
listdirs = os. listdir( filepath)
listdir = sorted ( listdirs)
filename = os. path. join( filepath, listdir[ - 1 ] )
return filename
def sendmail ( reportfile) :
from_addr = "wupeng@formssi.com"
password = "xxxxxx"
to_addr = "qq32712784@163.com"
smtp_server = "smtp.formssi.com"
def _format_addr ( s) :
name, addr = parseaddr( s)
print ( name)
print ( addr)
return formataddr( ( \
Header( name, 'utf-8' ) . encode( ) , \
addr. encode( "utf-8" ) if isinstance ( addr, unicode ) else addr) )
def _format_addr ( s) :
name, addr = parseaddr( s)
print ( name)
print ( addr)
return formataddr( ( Header( name, 'utf-8' ) . encode( ) ,
addr) )
filepath = reportfile
with open ( filepath, 'rb' ) as f:
content = f. read( )
msg = MIMEText( content, 'html' , 'utf-8' )
msg[ 'From' ] = _format_addr( u'测试机 <%s>' % from_addr)
msg[ 'to' ] = _format_addr( u'吴鹏rhythm <%s>' % to_addr)
msg[ 'Subject' ] = Header( u'测试报告自动发送' , 'utf-8' ) . encode( )
msg[ 'date' ] = time. strftime( "%a,%d %b %Y %H:%M:%S %z" )
server = smtplib. SMTP( smtp_server, 25 )
server. set_debuglevel( 1 )
server. login( from_addr, password)
server. sendmail( from_addr, to_addr, msg. as_string( ) )
server. quit( )
if __name__ == "__main__" :
filedir = filepath( )
sendmail( filedir)
schedule
import functools
import logging
import threading
from datetime import timedelta, datetime
import schedule
import time
"""
# Scheduler作用就是在job可以执行的时候执行它. 对应方法功能:
#
# run_pending:运行所有可以运行的任务
# run_all:运行所有任务,不管是否应该运行
# clear:删除所有调度的任务
# cancel_job:删除一个任务
# every: 创建一个调度任务, 返回的是一个job
# _run_job:运行一个job
# next_run:获取下一个要运行任务的时间, 这里使用的是min去得到最近将执行的job, 之所以这样使用,是Job重载了__lt_方法,这样写起来确实很简洁.
# idle_seconds:还有多少秒即将开始运行任务.
# Job是整个定时任务的核心. 主要功能就是根据创建Job时的参数,得到下一次运行的时间
# interval:间隔多久,每interval秒或分等.
# job_func:job执行函数
# unit : 间隔单元,比如minutes, hours
# at_time :job具体执行时间点,比如10:30等
# last_run:job上一次执行时间
# next_run :job下一次即将运行时间
# period: 距离下次运行间隔时间
# start_day: 周的特殊天,也就是monday等的含义
"""
"""
# 周期任务
def job():
print("I'm working...")
# 通过调用 scedule.every(时间数).时间类型.do(job) 发布周期任务。
schedule.every(interval=10).minutes.do(job_func=job)
# 每个小时执行任务
schedule.every().hour.do(job)
# 每天的10:30执行任务
schedule.every().day.at("10:30").do(job)
# 每个月执行任务
schedule.every().monday.do(job)
# 每个星期三的13:15分执行任务
schedule.every().wednesday.at("13:15").do(job)
# 每分钟的第17秒执行任务
schedule.every().minute.at(":17").do(job)
while True:
# 发布后的周期任务需要用 run_pending 函数来检测是否执行,因此需要一个 While 循环不断地轮询这个函数
schedule.run_pending()
time.sleep(1)
"""
"""
# 单次任务
def job_that_executes_once():
# 此处编写的任务只会执行一次。。。
return schedule.CancelJob
# 可以看到CancelJob就是一个空类, 这个类的作用就是当你的job执行函数返回一个CancelJob类型的对象,
# 那么执行完后就会被Scheduler移除. 简单说就是只会执行一次
schedule.every().day.at("22:30").do(job_that_executes_once)
"""
"""
# 需要传参的任务
def greet(name):
print("Hello", name)
# do() 将额外的参数传递给job函数
schedule.every(2).seconds.do(greet, name='Alice')
schedule.every(4).seconds.do(greet, name='Bob')
"""
"""
# 此处有错误
def hello():
print('Hello world')
schedule.every().second.do(hello)
# all_jobs = schedule.get_jobs() # 报错
# print(all_jobs)
# schedule.clear() # 清除程序的所有任务
"""
"""
def greet(name):
print('Hello {}'.format(name))
# .tag 打标签
schedule.every().day.do(greet, 'Andrea').tag('daily-tasks', 'friend')
schedule.every().hour.do(greet, 'John').tag('hourly-tasks', 'friend')
schedule.every().hour.do(greet, 'Monica').tag('hourly-tasks', 'customer')
schedule.every().day.do(greet, 'Derek').tag('daily-tasks', 'guest')
# get_jobs(标签):可以获取所有该标签的任务
# friends = schedule.get_jobs('friend') # 报错
# 取消所有 daily-tasks 标签的任务
# schedule.clear('daily-tasks')
"""
"""
# 让某个作业到某个时间截止
def job():
print('Boo')
# 每个小时运行作业,18:30后停止
schedule.every(1).hours.until("18:30").do(job)
# 每个小时运行作业,2030-01-01 18:33 today
schedule.every(1).hours.until("2030-01-01 18:33").do(job)
# 每个小时运行作业,8个小时后停止
schedule.every(1).hours.until(timedelta(hours=8)).do(job)
# 每个小时运行作业,11:32:42后停止
schedule.every(1).hours.until(time(11, 33, 42)).do(job)
# 每个小时运行作业,2020-5-17 11:36:20后停止
schedule.every(1).hours.until(datetime(2020, 5, 17, 11, 36, 20)).do(job)
"""
"""
# 如果某个机制触发了,你需要立即运行所有作业,可以调用 schedule.run_all()
def job_1():
print('Foo')
def job_2():
print('Bar')
schedule.every().monday.at("12:40").do(job_1)
schedule.every().tuesday.at("16:40").do(job_2)
schedule.run_all()
# 立即运行所有作业,每次作业间隔10秒
schedule.run_all(delay_seconds=10)
"""
"""
# 多线程的形式来运行每个作业实现并行执行
def job1():
print("I'm running on thread %s" % threading.current_thread())
def job2():
print("I'm running on thread %s" % threading.current_thread())
def job3():
print("I'm running on thread %s" % threading.current_thread())
def run_threaded(job_func):
job_thread = threading.Thread(target=job_func)
job_thread.start()
schedule.every(10).seconds.do(run_threaded, job1)
schedule.every(10).seconds.do(run_threaded, job2)
schedule.every(10).seconds.do(run_threaded, job3)
"""
"""
# Schedule 模块同时也支持 logging 日志记录
logging.basicConfig()
schedule_logger = logging.getLogger('schedule')
# 日志级别为DEBUG
schedule_logger.setLevel(level=logging.DEBUG)
def job():
print("Hello, Logs")
schedule.every().second.do(job)
schedule.run_all()
schedule.clear()
"""
def catch_exceptions ( cancel_on_failure= False ) :
def catch_exceptions_decorator ( job_func) :
@functools. wraps ( job_func)
def wrapper ( * args, ** kwargs) :
try :
return job_func( * args, ** kwargs)
except :
import traceback
print ( traceback. format_exc( ) )
if cancel_on_failure:
return schedule. CancelJob
return wrapper
return catch_exceptions_decorator
@catch_exceptions ( cancel_on_failure= True )
def bad_task ( ) :
return 1 / 0
schedule. every( 5 ) . minutes. do( bad_task)
while True :
schedule. run_pending( )
time. sleep( 1 )
验证码识别
import tesserocr
from PIL import Image
def code2str ( filename, threshold= 210 ) :
img= Image. open ( filename)
img= img. convert( 'L' )
table= [ ]
for i in range ( 256 ) :
if i < threshold:
table. append( 0 )
else :
table. append( 1 )
img= img. point( table, '1' )
result= tesserocr. image_to_text( img)
print ( result)
return result
常用代码
input . send_keys( Keys. ENTER)
from selenium import webdriver
import selenium. webdriver. common. keys as keys
element= driver. by. . . .
element. click( )
element. send_keys( keys. RIGHT)
element. send_keys( keys. BACKSPAC)
from selenium import webdriver
import selenium. webdriver. common. keys as keys
element= driver. by. . . .
element. clear( )
注意事项