python基础知识5---数据类型、字符编码、文件处理

阅读目录

  • 一 引子
  • 二 数字
  • 三 字符串
  • 四 列表
  • 五 元组
  • 六 字典
  • 七 集合
  • 八 数据类型总结
  • 九 运算符
  • 十 字符编码
  • 十一 文件处理
  • 十二 作业
 

一 引子

1 什么是数据?

  x=10,10是我们要存储的数据

2 为何数据要分不同的类型

  数据是用来表示状态的,不同的状态就应该用不同的类型的数据去表示

3 数据类型

  数字(整形,长整形,浮点型,复数)

  字符串

  字节串:在介绍字符编码时介绍字节bytes类型

  列表

  元组

  字典

  集合

4 按照以下几个点展开数据类型的学习

#======================================基本使用======================================
#1、用途 #2、定义方式 #3、常用操作+内置的方法 #======================================该类型总结====================================
#存一个值or存多个值 #有序or无序 #可变or不可变(1、可变:值变,id不变。可变==不可hash   2、不可变:值变,id就变。不可变==可hash)
#name = 'zhangsan'
#print(id(name))
#name = 'lisi'
#print(id(name))
#观察id在内存中的值是否发生变化

二 数字

整型与浮点型

#整型int
  作用:年纪,等级,身份证号,qq号等整型数字相关
  定义:
    age=10 #本质age=int(10) #浮点型float
  作用:薪资,身高,体重,体质参数等浮点数相关 salary=3000.3 #本质salary=float(3000.3) #二进制,十进制,八进制,十六进制

其他数字类型(了解)

#长整形(了解)
在python2中(python3中没有长整形的概念):      
>>> num=2L
>>> type(num)
<type 'long'> #复数(了解)  
>>> x=1-2j
>>> x.real
1.0
>>> x.imag
-2.0

三 字符串

#作用:名字,性别,国籍,地址等描述信息

#定义:在单引号\双引号\三引号内,由一串字符组成
name='egon' #优先掌握的操作:
#1、按索引取值(正向取+反向取) :只能取
#2、切片(顾头不顾尾,步长)
#3、长度len
#4、成员运算in和not in #5、移除空白strip
#6、切分split
#7、循环

需要掌握的操作

#1、strip,lstrip,rstrip
#2、lower,upper
#3、startswith,endswith
#4、format的三种玩法
#5、split,rsplit
#6、join
#7、replace
#8、isdigit
#strip
name='*egon**'
print(name.strip('*'))
print(name.lstrip('*'))
print(name.rstrip('*')) #lower,upper
name='egon'
print(name.lower())
print(name.upper()) #startswith,endswith
name='alex_SB'
print(name.endswith('SB'))
print(name.startswith('alex')) #format的三种玩法
res='{} {} {}'.format('egon',18,'male')
res='{1} {0} {1}'.format('egon',18,'male')
res='{name} {age} {sex}'.format(sex='male',name='egon',age=18) #split
name='root:x:0:0::/root:/bin/bash'
print(name.split(':')) #默认分隔符为空格
name='C:/a/b/c/d.txt' #只想拿到*目录
print(name.split('/',1)) name='a|b|c'
print(name.rsplit('|',1)) #从右开始切分 #join
tag=' '
print(tag.join(['egon','say','hello','world'])) #可迭代对象必须都是字符串 #replace
name='alex say :i have one tesla,my name is alex'
print(name.replace('alex','SB',1)) #isdigit:可以判断bytes和unicode类型,是最常用的用于于判断字符是否为"数字"的方法
age=input('>>: ')
print(age.isdigit())

其他操作(了解即可)

#1、find,rfind,index,rindex,count
#2、center,ljust,rjust,zfill
#3、expandtabs
#4、captalize,swapcase,title
#5、is数字系列
#6、is其他
#find,rfind,index,rindex,count
name='egon say hello'
print(name.find('o',1,3)) #顾头不顾尾,找不到则返回-1不会报错,找到了则显示索引
# print(name.index('e',2,4)) #同上,但是找不到会报错
print(name.count('e',1,3)) #顾头不顾尾,如果不指定范围则查找所有 #center,ljust,rjust,zfill
name='egon'
print(name.center(30,'-'))
print(name.ljust(30,'*'))
print(name.rjust(30,'*'))
print(name.zfill(50)) #用0填充 #expandtabs
name='egon\thello'
print(name)
print(name.expandtabs(1)) #captalize,swapcase,title
print(name.capitalize()) #首字母大写
print(name.swapcase()) #大小写翻转
msg='egon say hi'
print(msg.title()) #每个单词的首字母大写 #is数字系列
#在python3中
num1=b'' #bytes
num2=u'' #unicode,python3中无需加u就是unicode
num3='四' #中文数字
num4='Ⅳ' #罗马数字 #isdigt:bytes,unicode
print(num1.isdigit()) #True
print(num2.isdigit()) #True
print(num3.isdigit()) #False
print(num4.isdigit()) #False #isdecimal:uncicode
#bytes类型无isdecimal方法
print(num2.isdecimal()) #True
print(num3.isdecimal()) #False
print(num4.isdecimal()) #False #isnumberic:unicode,中文数字,罗马数字
#bytes类型无isnumberic方法
print(num2.isnumeric()) #True
print(num3.isnumeric()) #True
print(num4.isnumeric()) #True #三者不能判断浮点数
num5='4.3'
print(num5.isdigit())
print(num5.isdecimal())
print(num5.isnumeric())
'''
总结:
最常用的是isdigit,可以判断bytes和unicode类型,这也是最常见的数字应用场景
如果要判断中文数字或罗马数字,则需要用到isnumeric
''' #is其他
print('===>')
name='egon123'
print(name.isalnum()) #字符串由字母或数字组成
print(name.isalpha()) #字符串只由字母组成 print(name.isidentifier())
print(name.islower())
print(name.isupper())
print(name.isspace())
print(name.istitle()) 示例

练习

# 写代码,有如下变量,请按照要求实现每个功能 (共6分,每小题各0.5分)
name = " aleX"
# 1) 移除 name 变量对应的值两边的空格,并输出处理结果
# 2) 判断 name 变量对应的值是否以 "al" 开头,并输出结果

# 3) 判断 name 变量对应的值是否以 "X" 结尾,并输出结果

# 4) 将 name 变量对应的值中的 “l” 替换为 “p”,并输出结果
# 5) 将 name 变量对应的值根据 “l” 分割,并输出结果。
# 6) 将 name 变量对应的值变大写,并输出结果

# 7) 将 name 变量对应的值变小写,并输出结果

# 8) 请输出 name 变量对应的值的第 2 个字符?
# 9) 请输出 name 变量对应的值的前 3 个字符?
# 10) 请输出 name 变量对应的值的后 2 个字符?

# 11) 请输出 name 变量对应的值中 “e” 所在索引位置?

# 12) 获取子序列,去掉最后一个字符。如: oldboy 则获取 oldbo。
# 写代码,有如下变量,请按照要求实现每个功能 (共6分,每小题各0.5分)
name = " aleX"
# 1) 移除 name 变量对应的值两边的空格,并输出处理结果
name = ' aleX'
a=name.strip()
print(a) # 2) 判断 name 变量对应的值是否以 "al" 开头,并输出结果

name=' aleX'
if name.startswith(name):
print(name)
else:
print('no') # 3) 判断 name 变量对应的值是否以 "X" 结尾,并输出结果

name=' aleX'
if name.endswith(name):
print(name)
else:
print('no') # 4) 将 name 变量对应的值中的 “l” 替换为 “p”,并输出结果
name=' aleX'
print(name.replace('l','p')) # 5) 将 name 变量对应的值根据 “l” 分割,并输出结果。
name=' aleX'
print(name.split('l')) # 6) 将 name 变量对应的值变大写,并输出结果

name=' aleX'
print(name.upper()) # 7) 将 name 变量对应的值变小写,并输出结果

name=' aleX'
print(name.lower()) # 8) 请输出 name 变量对应的值的第 2 个字符?
name=' aleX'
print(name[1]) # 9) 请输出 name 变量对应的值的前 3 个字符?
name=' aleX'
print(name[:3]) # 10) 请输出 name 变量对应的值的后 2 个字符?

name=' aleX'
print(name[-2:]) # 11) 请输出 name 变量对应的值中 “e” 所在索引位置?

name=' aleX'
print(name.index('e')) # 12) 获取子序列,去掉最后一个字符。如: oldboy 则获取 oldbo。
name=' aleX'
a=name[:-1]
print(a)

四 列表

#作用:多个装备,多个爱好,多门课程,多个女朋友等

#定义:[]内可以有多个任意类型的值,逗号分隔
my_girl_friends=['alex','wupeiqi','yuanhao',4,5] #本质my_girl_friends=list([...])

l=list('abc') #优先掌握的操作:
#1、按索引存取值(正向存取+反向存取):即可存也可以取
#2、切片(顾头不顾尾,步长)
#3、长度
#4、成员运算in和not in #5、追加
#6、删除
#7、循环
#ps:反向步长
l=[1,2,3,4,5,6] #正向步长
l[0:3:1] #[1, 2, 3]
#反向步长
l[2::-1] #[3, 2, 1]
#列表翻转
l[::-1] #[6, 5, 4, 3, 2, 1]

练习:

1. 有列表data=['alex',49,[1900,3,18]],分别取出列表中的名字,年龄,出生的年,月,日赋值给不同的变量

2. 用列表模拟队列

3. 用列表模拟堆栈

4. 有如下列表,请按照年龄排序(涉及到匿名函数)
l=[
{'name':'alex','age':84},
{'name':'oldboy','age':73},
{'name':'egon','age':18},
]
答案:
l.sort(key=lambda item:item['age'])
print(l)

五 元组

#作用:存多个值,对比列表来说,元组不可变(是可以当做字典的key的),主要是用来读

#定义:与列表类型比,只不过[]换成()
age=(11,22,33,44,55)本质age=tuple((11,22,33,44,55)) #优先掌握的操作:
#1、按索引取值(正向取+反向取):只能取
#2、切片(顾头不顾尾,步长)
#3、长度
#4、成员运算in和not in #5、循环

练习:

#简单购物车,要求如下:
实现打印商品详细信息,用户输入商品名和购买个数,则将商品名,价格,购买个数加入购物列表,如果输入为空或其他非法输入则要求用户重新输入   msg_dic={
'apple':10,
'tesla':100000,
'mac':3000,
'lenovo':30000,
'chicken':10,
}
msg_dic={
'apple':10,
'tesla':100000,
'mac':3000,
'lenovo':30000,
'chicken':10,
}
goods_l=[]
while True:
for key,item in msg_dic.items():
print('name:{name} price:{price}'.format(price=item,name=key))
choice=input('商品>>: ').strip()
if not choice or choice not in msg_dic:continue
count=input('购买个数>>: ').strip()
if not count.isdigit():continue
goods_l.append((choice,msg_dic[choice],count)) print(goods_l)

六 字典

#作用:存多个值,key-value存取,取值速度快

#定义:key必须是不可变类型,value可以是任意类型
info={'name':'egon','age':18,'sex':'male'} #本质info=dict({....})

info=dict(name='egon',age=18,sex='male')

info=dict([['name','egon'],('age',18)])

{}.fromkeys(('name','age','sex'),None) #优先掌握的操作:
#1、按key存取值:可存可取
#2、长度len
#3、成员运算in和not in #4、删除
#5、键keys(),值values(),键值对items()
#6、循环

练习:

1 有如下值集合 [11,22,33,44,55,66,77,88,99,90...],将所有大于 66 的值保存至字典的第一个key中,将小于 66 的值保存至第二个key的值中

即: {'k1': 大于66的所有值, 'k2': 小于66的所有值}
2 统计s='hello alex alex say hello sb sb'中每个单词的个数

结果如:{'hello': 2, 'alex': 2, 'say': 1, 'sb': 2}
1.

a={'k1':[],'k2':[]}
c=[11,22,33,44,55,66,77,88,99,90]
for i in c:
if i>66:
a['k1'].append(i)
else:
a['k2'].append(i)
print(a) 2. s='hello alex alex say hello sb sb' l=s.split()
dic={}
for item in l:
if item in dic:
dic[item]+=1
else:
dic[item]=1
print(dic) 3.其他做法 s='hello alex alex say hello sb sb'
dic={}
words=s.split()
print(words)
for word in words: #word='alex'
dic[word]=s.count(word)
print(dic) #利用setdefault解决重复赋值
'''
setdefault的功能
1:key存在,则不赋值,key不存在则设置默认值
2:key存在,返回的是key对应的已有的值,key不存在,返回的则是要设置的默认值
d={}
print(d.setdefault('a',1)) #返回1 d={'a':2222}
print(d.setdefault('a',1)) #返回2222
'''
s='hello alex alex say hello sb sb'
dic={}
words=s.split()
for word in words: #word='alex'
dic.setdefault(word,s.count(word))
print(dic) #利用集合,去掉重复,减少循环次数
s='hello alex alex say hello sb sb'
dic={}
words=s.split()
words_set=set(words)
for word in words_set:
dic[word]=s.count(word)
print(dic) 其他做法(重点看setdefault的用法)

七 集合

#作用:去重,关系运算,

#定义:
知识点回顾
可变类型是不可hash类型
不可变类型是可hash类型 #定义集合:
集合:可以包含多个元素,用逗号分割,
集合的元素遵循三个原则:
1:每个元素必须是不可变类型(可hash,可作为字典的key)
2:没有重复的元素
3:无序 注意集合的目的是将不同的值存放到一起,不同的集合间用来做关系运算,无需纠结于集合中单个值 #优先掌握的操作:
#1、长度len
#2、成员运算in和not in #3、|合集
#4、&交集
#5、-差集
#6、^对称差集
#7、==
#8、父集:>,>=
#9、子集:<,<=

练习:

一.关系运算
  有如下两个集合,pythons是报名python课程的学员名字集合,linuxs是报名linux课程的学员名字集合
  pythons={'alex','egon','yuanhao','wupeiqi','gangdan','biubiu'}
  linuxs={'wupeiqi','oldboy','gangdan'}
  1. 求出即报名python又报名linux课程的学员名字集合
  2. 求出所有报名的学生名字集合
  3. 求出只报名python课程的学员名字
  4. 求出没有同时这两门课程的学员名字集合
# 有如下两个集合,pythons是报名python课程的学员名字集合,linuxs是报名linux课程的学员名字集合
pythons={'alex','egon','yuanhao','wupeiqi','gangdan','biubiu'}
linuxs={'wupeiqi','oldboy','gangdan'}
# 求出即报名python又报名linux课程的学员名字集合
print(pythons & linuxs)
# 求出所有报名的学生名字集合
print(pythons | linuxs)
# 求出只报名python课程的学员名字
print(pythons - linuxs)
# 求出没有同时这两门课程的学员名字集合
print(pythons ^ linuxs)
二.去重

   1. 有列表l=['a','b',1,'a','a'],列表元素均为可hash类型,去重,得到新列表,且新列表无需保持列表原来的顺序

   2.在上题的基础上,保存列表原来的顺序

   3.去除文件中重复的行,肯定要保持文件内容的顺序不变
   4.有如下列表,列表元素为不可hash类型,去重,得到新列表,且新列表一定要保持列表原来的顺序 l=[
{'name':'egon','age':18,'sex':'male'},
{'name':'alex','age':73,'sex':'male'},
{'name':'egon','age':20,'sex':'female'},
{'name':'egon','age':18,'sex':'male'},
{'name':'egon','age':18,'sex':'male'},
]
#去重,无需保持原来的顺序
l=['a','b',1,'a','a']
print(set(l)) #去重,并保持原来的顺序
#方法一:不用集合
l=[1,'a','b',1,'a'] l1=[]
for i in l:
if i not in l1:
l1.append(i)
print(l1)
#方法二:借助集合
l1=[]
s=set()
for i in l:
if i not in s:
s.add(i)
l1.append(i) print(l1) #同上方法二,去除文件中重复的行
import os
with open('db.txt','r',encoding='utf-8') as read_f,\
open('.db.txt.swap','w',encoding='utf-8') as write_f:
s=set()
for line in read_f:
if line not in s:
s.add(line)
write_f.write(line)
os.remove('db.txt')
os.rename('.db.txt.swap','db.txt') #列表中元素为可变类型时,去重,并且保持原来顺序
l=[
{'name':'egon','age':18,'sex':'male'},
{'name':'alex','age':73,'sex':'male'},
{'name':'egon','age':20,'sex':'female'},
{'name':'egon','age':18,'sex':'male'},
{'name':'egon','age':18,'sex':'male'},
]
# print(set(l)) #报错:unhashable type: 'dict'
s=set()
l1=[]
for item in l:
val=(item['name'],item['age'],item['sex'])
if val not in s:
s.add(val)
l1.append(item) print(l1) #定义函数,既可以针对可以hash类型又可以针对不可hash类型
def func(items,key=None):
s=set()
for item in items:
val=item if key is None else key(item)
if val not in s:
s.add(val)
yield item print(list(func(l,key=lambda dic:(dic['name'],dic['age'],dic['sex']))))

八 数据类型总结

按存储空间的占用分(从低到高)

数字
字符串
集合:无序,即无序存索引相关信息
元组:有序,需要存索引相关信息,不可变
列表:有序,需要存索引相关信息,可变,需要处理数据的增删改
字典:无序,需要存key与value映射的相关信息,可变,需要处理数据的增删改

按存值个数区分

标量/原子类型 数字,字符串
容器类型 列表,元组,字典

按可变不可变区分

可变 列表,字典
不可变 数字,字符串,元组

按访问顺序区分

直接访问 数字
顺序访问(序列类型) 字符串,列表,元组
key值访问(映射类型) 字典

九 运算符

#身份运算(is ,is not)
is比较的是id,而双等号比较的是值
毫无疑问,id若相同则值肯定相同,而值相同id则不一定相同
>>> x=1234567890
>>> y=1234567890
>>> x == y
True
>>> id(x),id(y)
(3581040, 31550448)
>>> x is y
False

详见:https://www.cnblogs.com/lynn919/p/10621524.html#label8

十 字符编码

详见:https://www.cnblogs.com/lynn919/p/10621648.html

十一 文件处理

详见:https://www.cnblogs.com/lynn919/p/10621689.html

十二 作业

#作业一: 三级菜单
#要求:
打印省、市、县三级菜单
可返回上一级
可随时退出程序
menu = {
'北京':{
'海淀':{
'五道口':{
'soho':{},
'网易':{},
'google':{}
},
'中关村':{
'爱奇艺':{},
'汽车之家':{},
'youku':{},
},
'上地':{
'百度':{},
},
},
'昌平':{
'沙河':{
'老男孩':{},
'北航':{},
},
'天通苑':{},
'回龙观':{},
},
'朝阳':{},
'东城':{},
},
'上海':{
'闵行':{
"人民广场":{
'炸鸡店':{}
}
},
'闸北':{
'火车战':{
'携程':{}
}
},
'浦东':{},
},
'山东':{},
} tag=True
while tag:
menu1=menu
for key in menu1: # 打印第一层
print(key) choice1=input('第一层>>: ').strip() # 选择第一层 if choice1 == 'b': # 输入b,则返回上一级
break
if choice1 == 'q': # 输入q,则退出整体
tag=False
continue
if choice1 not in menu1: # 输入内容不在menu1内,则继续输入
continue while tag:
menu_2=menu1[choice1] # 拿到choice1对应的一层字典
for key in menu_2:
print(key) choice2 = input('第二层>>: ').strip() if choice2 == 'b':
break
if choice2 == 'q':
tag = False
continue
if choice2 not in menu_2:
continue while tag:
menu_3=menu_2[choice2]
for key in menu_3:
print(key) choice3 = input('第三层>>: ').strip()
if choice3 == 'b':
break
if choice3 == 'q':
tag = False
continue
if choice3 not in menu_3:
continue while tag:
menu_4=menu_3[choice3]
for key in menu_4:
print(key) choice4 = input('第四层>>: ').strip()
if choice4 == 'b':
break
if choice4 == 'q':
tag = False
continue
if choice4 not in menu_4:
continue # 第四层内没数据了,无需进入下一层 三级菜单面条版

三级菜单面条版

menu = {
'北京':{
'海淀':{
'五道口':{
'soho':{},
'网易':{},
'google':{}
},
'中关村':{
'爱奇艺':{},
'汽车之家':{},
'youku':{},
},
'上地':{
'百度':{},
},
},
'昌平':{
'沙河':{
'老男孩':{},
'北航':{},
},
'天通苑':{},
'回龙观':{},
},
'朝阳':{},
'东城':{},
},
'上海':{
'闵行':{
"人民广场":{
'炸鸡店':{}
}
},
'闸北':{
'火车战':{
'携程':{}
}
},
'浦东':{},
},
'山东':{},
} #part1(初步实现):能够一层一层进入
layers = [menu, ] while True:
current_layer = layers[-1]
for key in current_layer:
print(key) choice = input('>>: ').strip() if choice not in current_layer: continue layers.append(current_layer[choice]) #part2(改进):加上退出机制
layers=[menu,] while True:
if len(layers) == 0: break
current_layer=layers[-1]
for key in current_layer:
print(key) choice=input('>>: ').strip() if choice == 'b':
layers.pop(-1)
continue
if choice == 'q':break if choice not in current_layer:continue layers.append(current_layer[choice]) 三级菜单文艺青年版

三级菜单文艺青年版

#作业二:请闭眼写出购物车程序
#需求:
用户名和密码存放于文件中,格式为:egon|egon123
启动程序后,先登录,登录成功则让用户输入工资,然后打印商品列表,失败则重新登录,超过三次则退出程序
允许用户根据商品编号购买商品
用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
可随时退出,退出时,打印已购买商品和余额
import os

product_list = [['Iphone7',5800],
['Coffee',30],
['疙瘩汤',10],
['Python Book',99],
['Bike',199],
['ViVo X9',2499], ] shopping_cart={}
current_userinfo=[] db_file=r'db.txt' while True:
print('''
登陆
注册
购物
''') choice=input('>>: ').strip() if choice == '':
#1、登陆
tag=True
count=0
while tag:
if count == 3:
print('\033[45m尝试次数过多,退出。。。\033[0m')
break
uname = input('用户名:').strip()
pwd = input('密码:').strip() with open(db_file,'r',encoding='utf-8') as f:
for line in f:
line=line.strip('\n')
user_info=line.split(',') uname_of_db=user_info[0]
pwd_of_db=user_info[1]
balance_of_db=int(user_info[2]) if uname == uname_of_db and pwd == pwd_of_db:
print('\033[48m登陆成功\033[0m') # 登陆成功则将用户名和余额添加到列表
current_userinfo=[uname_of_db,balance_of_db]
print('用户信息为:',current_userinfo)
tag=False
break
else:
print('\033[47m用户名或密码错误\033[0m')
count+=1 elif choice == '':
uname=input('请输入用户名:').strip()
while True:
pwd1=input('请输入密码:').strip()
pwd2=input('再次确认密码:').strip()
if pwd2 == pwd1:
break
else:
print('\033[39m两次输入密码不一致,请重新输入!!!\033[0m') balance=input('请输入充值金额:').strip() with open(db_file,'a',encoding='utf-8') as f:
f.write('%s,%s,%s\n' %(uname,pwd1,balance)) elif choice == '':
if len(current_userinfo) == 0:
print('\033[49m请先登陆...\033[0m')
else:
#登陆成功后,开始购物
uname_of_db=current_userinfo[0]
balance_of_db=current_userinfo[1] print('尊敬的用户[%s] 您的余额为[%s],祝您购物愉快' %(
uname_of_db,
balance_of_db
)) tag=True
while tag:
for index,product in enumerate(product_list):
print(index,product)
choice=input('输入商品编号购物,输入q退出>>: ').strip()
if choice.isdigit():
choice=int(choice)
if choice < 0 or choice >= len(product_list):continue pname=product_list[choice][0]
pprice=product_list[choice][1]
if balance_of_db > pprice:
if pname in shopping_cart: # 原来已经购买过
shopping_cart[pname]['count']+=1
else:
shopping_cart[pname]={'pprice':pprice,'count':1} balance_of_db-=pprice # 扣钱
current_userinfo[1]=balance_of_db # 更新用户余额
print("Added product " + pname + " into shopping cart,\033[42;1myour current\033[0m balance " + str(balance_of_db)) else:
print("买不起,穷逼! 产品价格是{price},你还差{lack_price}".format(
price=pprice,
lack_price=(pprice - balance_of_db)
))
print(shopping_cart)
elif choice == 'q':
print("""
---------------------------------已购买商品列表---------------------------------
id 商品 数量 单价 总价
""") total_cost=0
for i,key in enumerate(shopping_cart):
print('%22s%18s%18s%18s%18s' %(
i,
key,
shopping_cart[key]['count'],
shopping_cart[key]['pprice'],
shopping_cart[key]['pprice'] * shopping_cart[key]['count']
))
total_cost+=shopping_cart[key]['pprice'] * shopping_cart[key]['count'] print("""
您的总花费为: %s
您的余额为: %s
---------------------------------end---------------------------------
""" %(total_cost,balance_of_db)) while tag:
inp=input('确认购买(yes/no?)>>: ').strip()
if inp not in ['Y','N','y','n','yes','no']:continue
if inp in ['Y','y','yes']:
# 将余额写入文件 src_file=db_file
dst_file=r'%s.swap' %db_file
with open(src_file,'r',encoding='utf-8') as read_f,\
open(dst_file,'w',encoding='utf-8') as write_f:
for line in read_f:
if line.startswith(uname_of_db):
l=line.strip('\n').split(',')
l[-1]=str(balance_of_db)
line=','.join(l)+'\n' write_f.write(line)
os.remove(src_file)
os.rename(dst_file,src_file) print('购买成功,请耐心等待发货') shopping_cart={}
current_userinfo=[]
tag=False else:
print('输入非法') else:
print('\033[33m非法操作\033[0m') 购物车程序面条版

购物车程序面条版

上一篇:linux makefile字符串操作函数 替换subst、模式替换patsubst、去首尾空格strip、查找字符串findstring、过滤filter、反过滤filter-out、排序函数sort、取单词word、取单词串wordlist、个数统计words


下一篇:Java常用正则表达式验证工具类RegexUtils.java