概要:列表的操作,字典的操作,循环 ,购物车第一版程序
列表的基本操作:增 删 改 查
name = ["语文", "数学", "物理", "化学", "生物", "语文"]
#增
name = []
name.append()
name.insert(index,element) '''找到位置插入元素'''
name.extend(name1) 扩展
name = name + name1
#删
name.pop(index) '''默认最后一个删除'''
name.remove(element) '''直接删除元素'''
del name[index]
del name '''直接删除列表,定义都没了'''
name.clear()'''清空列表,定义还在'''
#改
name[index] = Newelement
name.reverse() 列表反转
name.sort() 按照ascii码排序,注意排序列表中不许不相同的数据值存在
#查
name.index(element) 反回元素的位置
name.count(element) 返回元素个数
name[index] 反回对应的元素值
name 反回整个列表
for循环跳出多层循环
break_flag = False
for i in range(10):
print("####第一层", i)
for j in range(10):
print("*****第二层", j)
# if j == 3:
# break_flag = True
# break
for k in range(10):
print("第三层", k)
if k == 2 :
break_flag = True
break
if break_flag:
print("++++++")
break
if break_flag:
print("第二层挂了,我也出去吧")
break
####第一层 0
*****第二层 0
第三层 0
第三层 1
第三层 2
++++++
第二层挂了,我也出去吧
while 循环跳出多层循环
break_flag = False
count = 0
while break_flag == False:
print("第一层")
while break_flag == False:
print("第二层")
while break_flag == False:
if count == 10:
break_flag = True
count +=1
print("第三层")
打印购物程序
购物车流程 图参考
https://www.processon.com/diagraming/596a2122e4b08e72e48bc2bb
product_list = [['phone', 5000],
['book1', 100],
['变形金刚模型', 500],
['小鱼仔一箱', 50],
['伊利牛奶', 100]
]
shopping_cart = []
salary = int(input("input you salary: "))
while True:
index = 0
for product in product_list:
print(index,product)
index +=1
choice = input("请输入要购买的商品编号>>>:").strip()
if choice.isdigit():
choice = int(choice)
if choice >= 0 and choice < len(product_list):
product = product_list[choice]
if product[1] <= salary:
shopping_cart.append(product)
salary -= product[1]
print("添加商品" + product[0] +"到购物车", "你现在的余额为" + str(salary))
else:
print("您的余额不足,产品的价格是" + str(product[1]) + "你还差" + str(product[1] - salary))
else:
print("商品不存在")
elif choice == "q":
print("---------已购买商品列表-------")
for i in shopping_cart:
print(i)
print("您的余额为:",salary)
print("......end......")
break
else:
print("无此选项")
Python isdigit() 方法检测字符串是否只由数字组成。如果字符串只包含数字则返回 True 否则返回 False
字典的使用方法
name = {
1:{"name":"want", "age":22},
2: {"name": "want2", "age": 23},
110:["hello word110"],
111:["hello word111"]
}
name2 = {
110:["i am name 2"],
118:["my home is name2 112"]
}
# print(name,name2)
# name.update(name2)#同key会更改,没有的key会追加
#print(name)
#改
# name[1][0] = "change want"
# name[110].append(28)
# name[113] = ["update dict 113 to name"]
#删除
#name.pop(110)
#如果110这个key不存在 就会报错如果不想报错 name.pop(110,none)
#del name[110]
#查
#print(name[111])#如果key没有会报错
#print(name.get(11111))#有返回值,没有返回none
#print(113 in name)#false,没有key返回false
#print (name)#查所有
# print(name.keys())#查所有的keys
print(name.values())#查所有的values
#------loop----循环查找
# for i in name:
# print(i,name[i])