python练习题2
练习题2
1.统计元组中所有数据属于字符串串的个数,提示:isinstance()
数据:t1 = (1, 2, ‘3’, ‘4’, 5, ‘6’)
结果:3
t1 = (1, 2, '3', '4', 5, '6')
num = 0
for i in t1:
if isinstance(i, str):
num += 1
print("总共有%s个字符串" % num)
2.将以下数据存储为字典类型
数据:info = “name:Owen|age:18|gender:男”
结果:{‘name’: ‘Owen’, ‘age’: 18, ‘gender’: ‘男’}
注:年年龄存储为数字类型
info = "name:Owen|age:18|gender:男"
new_dic = {}
for i in info.split("|"):
l1 = i.split(":")
if l1[1].isdecimal():
new_dic[l1[0]] = int(l1[1])
else:
new_dic[l1[0]] = l1[1]
print(new_dic)
3.完成数据的去重
数据:t3 = (1, 2, 1, 2, 3, 5, 9)
结果:t3 = (1, 2, 3, 5, 9)
注:从不不考虑顺序、考虑顺序两⽅方⾯面完成
t3 = (1, 2, 1, 2, 3, 5, 9)
res = set()
for i in t3:
res.add(i)
print(tuple(res))
4.计算元组中所有可以转换为数字的数据的总和
数据:t4 = (10, ‘abc’, ‘100’, ‘3’)
运算结果:113
sum = 0
t4 = (10, 'abc', '100', '3')
for i in t4:
if isinstance(i, int) or i.isdecimal():
i = int(i)
sum += i
print("运算结果:", sum)
5.将数据转换类型存储
原数据:dic = {‘name’: ‘Owen’, ‘age’: 18, ‘gender’: ‘男’}
处理理后:info = [(‘name’, ‘Owen’), (‘age’, 18), (‘gender’, ‘男’)]
dic = {'name': 'Owen', 'age': 18, 'gender': '男'}
info = []
for k,v in dic.items():
info.append(tuple([k, v]))
print(info)
拓拓展:选做
1.计算元组中所有可以转换为数字的数据的总和
数据:t4 = (10, ‘abc’, ‘100’, ‘3’, ‘壹’, ‘肆’, [1000], (10000,))
运算结果:11118
提示:
– 利利⽤用字符串串isnumeric()判断汉字
– 利利⽤用字典{‘壹’: 1 …}将汉字转换为数字
– 利利⽤用isinstance()将list和tuple中数据取出来
– 先将所有转化为数字的数据存放在⼀一个单列列集合中,在做运算
t4 = (10, 'abc', '100', '3', '壹', '肆', [1000], (10000,))
res = []
dic = {'壹': 1, '肆': 4}
for i in t4:
if isinstance(i, int):
res.append(i)
elif isinstance(i, str):
if i.isdecimal():
res.append(int(i))
elif i.isnumeric():
res.append(dic[i])
elif isinstance(i, list):
for y in i:
res.append(y)
elif isinstance(i, tuple):
for y in i:
res.append(y)
print("运算结果: ", sum(res))
2.完成录⼊入电话本
需求:
‘’’
– 从键盘中录⼊入姓名(不不区分⼤大⼩小写):
– 姓名必须是全英⽂文组成,不不是则重新录⼊入姓名,如果是q,代表退出
– 从键盘中再录⼊入电话:
– 电话必须为数字且⻓长度必须是11位(不不能转换为数字)
– 如果出现姓名相同,则保留留最后⼀一次电话号码
– 形成的数据是有电话分组的,如:第⼀一次录⼊入Owen,13355667788,则会形成
– {
‘O’: {
‘Owen’: ‘13355667788’
}
}
最终数据,分组名⼀一定⼤大写:
{
‘E’: {
‘egon’: ‘17788990000’,
‘engo’: ‘16633445566’
},
‘O’: {
‘Owen’: ‘13355667788’
}
}
‘’’
dic = {}
flag = True
while flag:
flag1 = True
name = input("请输入英文名(按q退出):")
if name == "q":
print("退出")
flag = False
continue
for i in name:
if not (ord(i) in range(97,122) or ord(i) in range(65,90)):
print("不为英文名请重新输入")
continue
first_letter = name[0].upper()
if not dic.get(first_letter):
dic[first_letter] = {name: 0}
while flag1:
phone_num = input("请输入电话(按q退出):")
if name == "q":
print("退出")
flag = False
flag1 = False
continue
elif phone_num.isdecimal() and len(phone_num) == 11:
dic[first_letter][name] = phone_num
print(dic)
flag1 = False
continue
else:
print("电话格式有误,请重新输入(按q退出)")
continue
三级菜单
要求:
打印省、市、县三级菜单
可返回上一级
可随时退出程序
#傻瓜方式
menu = {
'北京': {
'海淀': {
'五道口': {
'soho': {},
'网易': {},
'google': {}
},
'中关村': {
'爱奇艺': {},
'汽车之家': {},
'youku': {},
},
'上地': {
'百度': {},
},
},
'昌平': {
'沙河': {
'老男孩': {},
'北航': {},
},
'天通苑': {},
'回龙观': {},
},
'朝阳': {},
'东城': {},
},
'上海': {
'闵行': {
"人民广场": {
'炸鸡店': {}
}
},
'闸北': {
'火车战': {
'携程': {}
}
},
'浦东': {},
},
'山东': {},
}
FLAG = True
shi = "省或直辖市"
qu = "区"
didian = "地点"
biaozhi = "标志物"
while FLAG:
print("输入b返回,q退出")
for k in menu.keys():
print("%s : " % shi, k)
input1 = input("请输入省或直辖市: ")
if input1 == "b":
print("无上级目录,退出")
break
elif input1 == "q":
break
elif input1 not in menu.keys():
print("\n输入错误,请重新输入")
continue
while FLAG:
menu1 = menu[input1]
for j in menu1.keys():
print("%s : " % qu, j)
input2 = input("请输入区市: ")
if input2 == "b":
break
elif input2 == "q":
FLAG = False
break
elif input2 not in menu1.keys():
print("\n输入错误,请重新输入")
continue
while FLAG:
menu2 = menu1[input2]
for l in menu2.keys():
print("%s : " % didian, l)
input3 = input("请输入地点: ")
if input3 == "b":
break
elif input3 == "q":
FLAG = False
break
elif input3 not in menu2.keys():
print("\n输入错误,请重新输入")
continue
while FLAG:
menu3 = menu2[input3]
for v in menu3.keys():
print("%s : " % biaozhi, v)
input4 = input("查询完成,可按q退出或按b返回上级菜单")
if input4 == "b":
break
elif input4 == "q":
FLAG = False
break
elif input4 not in menu3.keys():
print("\n查询完成,按q退出")
continue
version2
menu = {
'北京': {
'海淀': {
'五道口': {
'soho': {},
'网易': {},
'google': {}
},
'中关村': {
'爱奇艺': {},
'汽车之家': {},
'youku': {},
},
'上地': {
'百度': {},
},
},
'昌平': {
'沙河': {
'老男孩': {},
'北航': {},
},
'天通苑': {},
'回龙观': {},
},
'朝阳': {},
'东城': {},
},
'上海': {
'闵行': {
"人民广场": {
'炸鸡店': {}
}
},
'闸北': {
'火车战': {
'携程': {}
}
},
'浦东': {},
},
'山东': {},
}
list1 = [menu]
while True:
print("按b返回,按q退出")
for i in menu.keys():
print(i)
input1 = input("请输入所选项: ")
if input1 == "b":
list1.pop(-1)
if len(list1) == 0:
print("无上级目录,退出")
break
menu = list1[-1]
elif input1 == "q":
print("已退出")
break
elif input1 not in menu.keys():
print("输入值不存在请重新输入: ")
continue
elif isinstance(menu[input1], dict):
list1.append(menu[input1])
menu = menu[input1]
用户名和密码存放于文件中,格式为:egon|egon123
启动程序后,先登录,登录成功则让用户输入工资,然后打印商品列表,失败则重新登录,超过三次则退出程序
允许用户根据商品编号购买商品
用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
可随时退出,退出时,打印已购买商品和余额
import os
product_list = [
['Iphone7', 5800],
['Coffee', 30],
['疙瘩汤', 10],
['Python Book', 99],
['Bike', 199],
['ViVo X9', 2499]
]
def login():
i = 0
while i < 3:
with open("user.txt", 'r') as f:
if i > 0:
username = input("信息有误,请再输入您的用户名: ")
else:
username = input("请输入您的用户名: ")
for y in f.readlines():
if username == y.strip("\n").split("|")[0]:
password = input("请输入您的密码: ")
if (username == y.strip("\n").split("|")[0]) and (password == y.strip("\n").split("|")[1]):
print("登录成功")
balance = y.strip("\n").split("|")[2]
return username, balance
else:
print("密码错误,请重新输入用户名及密码")
i += 1
continue
i += 1
else:
print("信息错误3次,请重新登录")
exit(1)
def user_exist(username):
with open("user.txt", 'r') as f:
for i in f.readlines():
if username == i.strip("\n").split("|")[0]:
print("此用户名已存在,请重新输入")
return False
return True
def register():
while True:
username = input("请输入您的用户名: ")
if user_exist(username):
while True:
password1 = input("请输入您的密码: ")
password2 = input("请再输入您的密码: ")
if password1 == password2:
with open("user.txt", "a") as f:
balance = input("充值金额:")
f.write("%s|%s|%s\n" % (username, password1, balance))
print("注册完成, 注册完成后需重新登录")
return None
else:
print("密码不一致请重新输入")
continue
else:
continue
def shopping(product_list, user, balance):
user_cart = {} # 结构: {"0": ["商品名称", "商品数量", 商品单价,商品总价]}
flag = True
while flag:
print("当前用户:%s 账户余额:%s " % (user, balance))
print("如需充值,请按'b'直接返回上级菜单,按'q'退出")
for i, v in enumerate(product_list):
print("商品编号:%s, 商品名称:%s, 价格:%s" % (i, v[0], v[1]))
while flag:
input1 = input("产品选择(请按'b'直接返回上级菜单,按'q'退出):")
if input1 == "b":
return user,balance
elif input1 == "q":
print('''----已购买商品列表----
id 商品 数量 单价 总价''')
total_cost = 0
for k, v in user_cart.items():
print("%s %s %s %s %s" % (k, v[0], v[1], v[2], v[2]))
total_cost += v[2]
remain = int(balance) - total_cost
print("总计:%s ,交易行剩余为:%s" % (total_cost, remain))
input2 = input("请按'y'确认此订单: ")
if input2 not in ['Y', 'y', 'yes']:
return None
elif remain < 0:
print("余额不足,交易取消")
return False
else:
src_file = r'user.txt'
dst_file = r'user.txt.swap'
with open(src_file, 'r') as read_f, \
open(dst_file, 'w') as write_f:
for line in read_f:
if line.startswith(user): # 找到对应user 修改账户余额
l1 = line.strip('\n').split('|')
l1[-1] = str(remain)
line = '|'.join(l1) + '\n'
write_f.write(line)
os.remove(src_file)
os.rename(dst_file, src_file)
print("订单已生成,请耐心等待")
return user, remain
flag = False
continue
elif int(input1) in list(range(len(product_list))): # 判断是否有此商品
if user_cart.get(input1): # 存在的话,修改数量和总价
user_cart[input1][3] += user_cart[input1][3]
user_cart[input1][1] += 1
print("添加成功")
print(user_cart)
else:
user_cart[input1] = [product_list[int(input1)][0], 1, \
product_list[int(input1)][1], product_list[int(input1)][1]]
print(user_cart)
def main():
while True:
print('''
1. 注册
2. 登录
3. 购物
''')
select = input("请输入需要的服务(按q退出):")
if select == "q":
break
elif select == "1":
print("----注册用户----")
register()
elif select == "2":
print("----登录----")
user, balance = login()
elif select == "3":
print("----购物----")
if not user:
print("请先登录,再进行购物")
user, balance = shopping(product_list, user, balance)
else:
print("无此选项请重新输入")
continue
if __name__ == '__main__':
main()
上一篇: HttpURLConnection的使用
下一篇: JDBC连接的详细步骤&代码