python基础二
一、pyc是什么?
Python的运行过程
在说这个问题之前,我们先来说两个概念,PyCodeObject和pyc文件。
我们在硬盘上看到的pyc自然不必多说,而其实PyCodeObject则是Python编译器真正编译成的结果。我们先简单知道就可以了,继续向下看。
当python程序运行时,编译的结果则是保存在位于内存中的PyCodeObject中,当Python程序运行结束时,Python解释器则将PyCodeObject写回到pyc文件中。
当python程序第二次运行时,首先程序会在硬盘中寻找pyc文件,如果找到,则直接载入,否则就重复上面的过程。
所以我们应该这样来定位PyCodeObject和pyc文件,我们说pyc文件其实是PyCodeObject的一种持久化保存方式。
pyc存储的是预编译后的字节。当python文件修改了则不会先载入pyc文件(通过比较pyc和python文件的时间)
二、模块
import sys
import os
#print(sys.path) #打印环境变量,安装模块的路径等
#print(sys.argv) # sys.argv 从外部传参数
#print(sys.argv[2]) #打印传递的第二个参数
#cmd_res = os.system("dir") #执行命令,不保存结果
#print("--->",cmd_res)
cmd_res = os.popen("dir").read()
print("--->",cmd_res)
#os.mkdir('test') #创建目录
msg = "中国" #str和bytes要转换
print(msg)
print(msg.encode('utf-8')) #encode 编译成密码,加密为二进制;decode 解密,解密成字符串
print(msg.encode(encoding='utf-8').decode(encoding='utf-8'))
三、列表与元组
#Author:Kevin Zou names = ['zou','test','kevin','chenchen'] #for i in names: # print(i) print(names) print(names[0]) #切片 print(names[1:3]) #切片,取头不取尾 print(names[:3]) #等同于name[0:3],取前三个 print(names[-1]) #取最后一个,等同于print(names[len(names)-1]) print(names[-2:]) #取最后两个 print(names[0::2]) #等同于names[::2] #z追加 names.append("xiaoli") print(names) #插入 names.insert(1,'xiaofeng') #前面表示插入的位置 print(names) #替换 names[1] = 'xiaoxiao' print(names) #names.remove('xiaoli') del names[4] print(names) names.pop() #默认删除最后一个,pop(0)则是删除第一个 print(names) print(names.index('xiaoxiao')) #根据值找位置 print(names[names.index('xiaoxiao')]) print(names.count('xiaoxiao')) #数量,字符串可重复 #names.clear() #清空 #names.reverse() #反转 names.sort() #特殊字符 数字 大写字符 小写字符,优先级按assii码排序 print(names) names2 = [1,2,3] names.extend(names2) #扩展 print(names) names[0] = ['A','B'] print(names[0][1]) #列表中的列表 print(names) print('-------') name3=names.copy() #复制,浅copy,只copy第一层, print(name3) import copy name4=copy.deepcopy(names) #深copy,全部复制,完全独立 names[0][1] = 'b' names[1] = 'TEST' print(names) print(name3) print('--------') #浅copy的用处, 第二个列表(复制后的)里面的内容每个元素是第一个列表每个列表的引用 person = ['name',['saving',100]] #三种浅copy方式 #p1=copy.copy(person) #p2=person[:] #p3=list(person) p1 = copy.copy(person) p2 = person[:] #等同于person[0:-1] p1[0]='kevin' p2[0]='chenchen' p1[1][1]=50 print(p1) print(p2)
元组其实跟列表差不多,也是存一组数,只不是它一旦创建,便不能再修改,所以又叫只读列表
语法
names = ("test,1,"kevin")
它只有2个方法,一个是count,一个是index。
程序:购物车程序
需求:
- 启动程序后,让用户输入工资,然后打印商品列表
- 允许用户根据商品编号购买商品
- 用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
- 可随时退出,退出时,打印已购买商品和余额
#Author:Kevin Zou shoplist = [("ipad",3000),('iphone 6',5000),('iphone 5',4000),('iphone 4s',3000),("mac pro",8000),('apple watch',2000)] yourcart = [] tag = 0 count = 0 while count < 3: salary = input("Please input your salary:") if salary.isdigit(): salary = int(salary) while True: #for item in shoplist: # print(shoplist.index(item),item) for index,item in enumerate(shoplist): print(index, item) num = input("Choose number you want to buy:") if num.isdigit(): num = int(num) if num >= 0 and num < len(shoplist): p_item = shoplist[num] if salary >= p_item[1]: salary = salary - p_item[1] yourcart.append(p_item) print("Add shop:%s,price:%s successful" % (p_item[0],p_item[1])) else: print("Your monery is not enough to buy {0},your balance monony is {1}".format(p_item[0],salary)) else: print("Please put the number between 0 ~ %s" % int(len(shoplist)-1)) elif num == 'q': print("List of your purchases:") for i in yourcart: print(i) print("Your remaining monoey:", salary) tag = 1 break else: print("Please input the correct number") else: print("Please input the correct number of your salary") if tag == 1: break count +=1 else: print("You try many times ,bye")
四、字符串
1 #Author:Kevin Zou 2 name = 'kevin' 3 print(name.capitalize()) #首字母大写 4 print(name.count('e')) #统计e的次数 5 print(name.encode()) #将字符串编码成bytes格式 6 print(name.endswith('in')) #判断字符串是否已in结尾 7 print(name.startswith('ke')) 8 print('kevin \t zou'.expandtabs(tabsize=22)) #将\t转换成多长的空格 9 #format三种用法 10 print("my name is {},and age is {}".format("kevin",25)) 11 print("my name is {name},and age is {age}".format(name="kevin",age=25)) 12 print("my name is {0},and age is {1}".format("kevin",25)) 13 #format_map用法 14 print("my name is {name},and age is {age}".format_map({'name':"kevin",'age':25})) 15 #find、index区别在于index在找不到字符串时候会抛出异常,影响程序使用。find则不会 16 print("test e".find('t')) 17 print("test".rfind('t')) #返回t所在的字符串的索引 18 print("test".rfind('0')) #返回-1,不报错 19 print("test".index('t')) #返回t所在的字符串的索引,从左第一个 20 print("test1t".rindex('t')) #返回t所在的字符串的索引,从右第一个 21 #print("test".rindex('0')) #报错 22 23 print('testT1'.isalnum()) #是否为字母或数字 24 print('test1'.isalpha()) #判断是否为英文字母 25 print('192'.isdecimal()) #判断字符串是否只包含十进制字符 26 print('1232'.isdigit()) #检查字符串是否只包含数字(全由数字组成) 27 print('test'.isidentifier()) #判断字符串是否是合法的标识符,字符串仅包含中文字符合法,实际上这里判断的是变量名是否合法 28 print('Test'.islower()) #判断字符串是否小写 29 print('TEST'.isupper()) #判断字符串是否大写 30 print(' '.isspace()) #是否空格 31 '''isdigit() 32 True: Unicode数字,byte数字(单字节),全角数字(双字节),罗马数字 33 False: 汉字数字 34 Error: 无 35 isdecimal() 36 True: Unicode数字,,全角数字(双字节) 37 False: 罗马数字,汉字数字 38 Error: byte数字(单字节) 39 isnumeric() 40 True: Unicode数字,全角数字(双字节),罗马数字,汉字数字 41 False: 无 42 Error: byte数字(单字节)''' 43 print('+'.join(['1','2','3'])) #1+2+3 44 print('1+2+3'.split('+')) #['1+2+3'] 45 print('te\nst'.splitlines()) # 按照行('\r', '\r\n', \n')分隔 46 47 print('Lest'.upper()) #转换大写 48 print('Lest'.lower()) #转换小写 49 50 print('\ntest space\n'.rstrip()) 51 print('\ntest space'.lstrip()) 52 print('\ntest space\n'.strip()) #首尾空格去掉 53 54 print('test'.replace('t',"T",1)) #替换 55 print('Test'.swapcase()) #大小写互换 56 57 print('hello'.ljust(40,'-')) 58 print('hello'.rjust(40,'-')) 59 print('hello'.center(40,'-'))
五、字典
字典的特性:
- dict是无序的
- key必须是唯一的
1 #Author:Kevin Zou 2 info = { 3 'stu01':'test1', 4 'stu02':'test2', 5 'stu03':'test3', 6 } 7 print(info) #打印字典info 8 print(info.values()) #打印所有的值 9 print(info.keys()) #打印所有的key 10 info.setdefault('stu01','Kevin') #先看看有没有这个key,有则不变,没有就新增这个key 11 print(info) 12 ''' 13 b = {2:3,'stu01':'kevin'} #合并 14 info.update(b) 15 print(info) 16 ''' 17 for key in info: #一样的,速度比下一个高效很多 18 print(key,info[key]) 19 for key,item in info.items(): #会先把dict转成list,数据里大时莫用 20 print(key,item) 21 22 print(info['stu01']) #查找,找不到则会报错。 23 print(info.get('stu011')) #查找,找不到返回None 24 print('stu01' in info) #判断key是否在字典info里。 info.has_key('stu01') in py2.x 25 26 info['stu01'] = 'TEST1' #修改 27 print(info) 28 info['stu04']='test4' #增加 29 print(info) 30 31 del info['stu01'] #删除 32 print(info) 33 info.pop('stu04') #标准删除 34 info.popitem() #随机删除 35 print(info) 36 37 #多级字典嵌套及操作
程序练习
程序: 三级菜单
要求:
- 打印省、市、县三级菜单
- 按b可返回上一级
- 可随时退出程序
-
第一次写的lower代码#Author:Kevin Zou menu = { '湖南':{ '长沙':{ '雨花区':['湖南省科技馆','湖南省森林植物园 '], '天心区':['天心阁','白沙古井'], '芙蓉区':['长沙站','湖南农业大学'] }, '株洲':{ '天元区':['a','b'], '株洲县':['a','b'] } }, '湖北':{ '武汉':{ '武昌区':['a','b'], '汉口区':['a','b'] } } } tag = 0 tag2 = 0 while True: for pro in menu: print(pro) choice1 = input("选择进入1:") if choice1 == "q": break elif choice1 in menu: while True: for city in menu[choice1]: print(city) choice2 = input("选择进入2:") if choice2 == 'q': tag = 1 break elif choice2 == 'b': break elif choice2 in menu[choice1]: for distrit in menu[choice1][choice2]: print(distrit) while True: choice3 = input("选择进入3:") if choice3 == 'q': tag = 1 break elif choice3 == 'b': break elif choice3 in menu[choice1][choice2]: while True: for key in menu[choice1][choice2][choice3]: print(key) choice4 = input("最后一层,按b返回首层") if choice4 == 'b': tag2 = 1 break elif choice4 == 'q': tag = 1 break if tag2 == 1: break if tag == 1: break else: for distrit in menu[choice1][choice2]: print(distrit) if tag == 1: break if tag2 == 1: break if tag == 1: break
1 #Author:Kevin Zou 2 ''' 3 exit_flag = False 4 while not exit_flag: 5 str = input("请输入q退出:") 6 if str == 'q': 7 exit_flag = True 8 ''' 9 menu = { 10 '湖南':{ 11 '长沙':{ 12 '雨花区':['湖南省科技馆','湖南省森林植物园 '], 13 '天心区':['天心阁','白沙古井'], 14 '芙蓉区':['长沙站','湖南农业大学'] 15 }, 16 '株洲':{ 17 '天元区':['a','b'], 18 '株洲县':['a','b'] 19 } 20 }, 21 '湖北':{ 22 '武汉':{ 23 '武昌区':['a','b'], 24 '汉口区':['a','b'] 25 } 26 } 27 } 28 exit_flag = False 29 while not exit_flag: 30 for pro in menu: 31 print(pro) 32 choice1 = input("选择进入1:") 33 if choice1 == "q": 34 exit_flag = True 35 elif choice1 in menu: 36 while not exit_flag: 37 for city in menu[choice1]: 38 print(city) 39 choice2 = input("选择进入2:") 40 if choice2 == 'q': 41 exit_flag = True 42 elif choice2 == 'b': 43 break 44 elif choice2 in menu[choice1]: 45 while not exit_flag: 46 for distrit in menu[choice1][choice2]: 47 print(distrit) 48 choice3 = input("选择进入3:") 49 if choice3 == 'q': 50 exit_flag = True 51 elif choice3 == 'b': 52 break 53 elif choice3 in menu[choice1][choice2]: 54 while not exit_flag: 55 for key in menu[choice1][choice2][choice3]: 56 print(key) 57 choice4 = input("最后一层,按b返回上次") 58 if choice4 == 'b': 59 break 60 elif choice4 == 'q': 61 exit_flag = True
六、集合
#Author:Kevin Zou list_1 = [1,2,3,5,3,6,66] list_2 = [1,44,2] list_1 = set(list_1) #集合,去重,是无序的 list_2 = set(list_2) print(list_1,list_2,type(list_1)) print(list_1.intersection(list_2)) #交集 & print(list_1 & list_2) print(list_1.union(list_2)) #两个集合的并集 | print(list_1.issubset(list_2)) #子集 print(list_1.issuperset(set([1,2]))) #父集 print(list_1.difference(list_2)) #差集,in list_1 not in list_2 - print(list_1.symmetric_difference(list_2)) #对称差集 ^ #基本操作 list_1.add('x') print(list_1) list_1.update('b','c') print(list_1) list_1.remove('x') #remove不存在会报错,discard()不会报错,都是删除 # #pop()随机删除 print(list_1)
七、文件操作
打开文件的模式有:
- r,只读模式(默认)。
- w,只写模式。【不可读;不存在则创建;存在则删除内容;】
- a,追加模式。【可读; 不存在则创建;存在则只追加内容;】
"+" 表示可以同时读写某个文件
- r+,可读写文件。【可读;可写;可追加】
- w+,写读
- a+,同a
"U"表示在读取时,可以将 \r \n \r\n自动转换成 \n (与 r 或 r+ 模式同使用)
- rU
- r+U
"b"表示处理二进制文件(如:FTP发送上传ISO镜像文件,linux可忽略,windows处理二进制文件时需标注)
- rb
- wb
- ab
with open('test','r') as f: #data=f.readline() 读一行 #data=f.read() 读所有 for data in f: print(data.strip())
#data = open("yesterday",encoding='utf-8').read() f = open("yesterday",encoding='utf-8') #文件句柄,文件的内存对象,包含文件的文件名,字符集,大小,硬盘的起始位置 data = f.read() print(data) f.close() f2 = open("yesterday2",'w',encoding='utf-8') f2.write("hello, \n") f2.write("world") f2.close()
浙公网安备 33010602011771号