# 13有两个列表
# l1 = [11, 22, 33, 44]
# l2 = [66, 77, 22, 33, 44, 55]
# a.获取内容相同的元素列表
# for l3 in l1:
# for l4 in l2:
# if l3 == l4:
# print(l4)
#
# for l3 in l1:
# if l3 in l2:
# print(l3)
# b.获取l1中有,l2中没有的元素列表
# for l3 in l1:
# if l3 in l2:
# continue
# else:
# print(l3)
# c.获取l2中有,l1中没有的元素列表
# for l4 in l2:
# if l4 not in l1:
# print(l4)
# d.获取l1和l2中都不同的元素。
# for l3 in l1:
# for l4 in l2:
# if l3 == l4:
# l1.remove(l3)
# l2.remove(l3)
# print(l1,l2)本题做的有错误,在22比较完删除后,第一个列表里的33索引会自动变成22,而第二个列表里循环还在进行,当遍历完第二个列表,第一个列表的33索引已经占据了原来删除掉的22索引,循环会直接跳过33接着取出44进行遍历比较。本方法修
改如下:
l4=l2.copy()
for l3 in l1:
if l3 in l2:
l2.remove(l3)
for i4 in l4:
if i4 in l1:
l1.remove(i4)
print(l1,l2)
# 14.利用for循环和range输出。
#
# a.for循环从大到小输出1-100.
# for a in range(1,101):
# print(a)
# b.for循环从小到大输出100-1
# for a in range(1,101):
# print(101-a)
# c.wile循环从小到大输出1-100
# a=0
# while a<100:
# a=a+1
# print(a)
# d.wile循环从大到小输出100-1
# a=0
# b=0
# while b<100:
# a=100-b
# b=b+1
# print(a)
# 15.购物车
# 功能要求:
# 要求用户输入总资产,比如:2000
# 显示商品列表,让用户根据序号选择商品,加入购物车。
# 购买,如果商品总额大于总资产,提示账户余额不足,否则购买成功。
goods = [
{"name": "电脑", "price": 1999},
{"name": "鼠标", "price": 10},
{"name": "电灯", "price": 20},
{"name": "椅子", "price": 899}]
inptotal = input("请输入持有金额:")
jici = 0
for good in goods:
print(jici, good.get("name"))
jici += 1
bool1 = True
buy = 0
while bool1:
listgm = input("请输入购买物品的序号,如购买完成请输入ok开始付款")
if listgm == "ok":
if int(inptotal) - buy >= 0:
print("购买成功,共付款:",buy)
break
else:
print("购买失败,你还需要:",buy-int(inptotal))
break
else:
if listgm.isdecimal() and int(listgm)<=len(goods):
sp = goods[int(listgm)]
buy = buy + sp.get("price")
else:
continue
二次修改
total = input("请输入所持有的总金额数:")
list_goods = {}
for k1, v1 in enumerate(goods, 1):
list_goods.setdefault(k1, v1)
print(list_goods)
buy = 0
while True:
xuhao = input("请输入要购买商品的序列号,输入ok结算:")
if xuhao == "ok":
break
else:
good = list_goods.get(int(xuhao),"none")
if good=="none":
print("无此商品,请重新选择。")
continue
sp = good.get("price")
buy = buy + sp
if buy == 0:
print("您什么也没有购买谢谢你的光临!")
elif buy > int(total):
print("您所持有的金额不够支持本次购物")
elif buy < int(total):
sy = int(total) -buy
print("你已经购买成功,你还生剩余金额:", sy)
print("欢迎您下次再来!")