元组及其操作 元组在很多地方与列表很像,都是有序的,都可以通过[]指定索引来获取元素,不过元组创建好之后就不可以变动。

names=('sheldon','penny','leonard')
print(names)
print(names[1])  # 切
print(names.count('penny'))  # 统计
print(names.index('penny'))  # 索引

# names[1]='潘妮'     # 替换  不可以
# names.remove('penny')   # 删  不可以
# names.append('潘妮')   # 增  不可以

购物车实例 1.简单的购物车 存在的缺点一旦,商品号输错就好运行失败;

salary=int(input('salary:'))
names1=('Iphone','Bike','Book','Car')
names2=('2500','800','60','3000')
names3=[]

print('-------------------')
for i in names1:
    num=names1.index(i )
    price=names2[names1.index(i) ]
    print(num,i,price)
print('-------------------')

_abc=input('你是否要购物:(add)or(other)')

while _abc=='add':
  num2=int(input("The shopping num:"))
  price2=int(names2[num2])
  if salary>price2:
      names3.append(names1[num2])
      names3.append(names2[num2])
      print('你刚刚购买了:',num2,names1[num2],names2[num2 ])
      salary=salary-price2
      print('-------------------')
      for i in names1:
          num = names1.index(i)
          price = names2[names1.index(i)]
          print(num, i, price)
      print('-------------------')
      _abc=input('你是否要继续购物:(add)or(other)')
  else:
      print("you money is not enougy")
      break

print("你购买的商品:",names3)
print('你的余额:',salary)

2.完善后的程序

product_list=[
    ('Iphone',5800),
    ('Mac pro',9800),
    ('Bike',8000),
    ('Book',20),
    ('Car',3000),
    ('Food',200)
]                       # 嵌套类型
shopping_list=[]
salary=input('input you salary:')

if salary.isdigit():
    salary=int(salary)
    while True:
        for index,item in enumerate (product_list):  # 取出列表的下标
            print(index,item)
        use_choice=input("你要买什么:")
        if use_choice.isdigit() :
            use_choice =int(use_choice )
            if use_choice >=0 and use_choice <len(product_list ):
                P_item=product_list [use_choice ]
                if P_item[1]<=salary :
                    shopping_list .append(P_item)
                    salary -=P_item[1]
                    print("Added %s into shopping car,you moneny is \033[31;1m%s\033[0m"%(P_item ,salary))
                else:
                    print("\033[41;1m你的余额不足,只剩%s\033[0m"%(salary ))
            else :
                print("没有该类产品...")

        elif use_choice =='q':
            print("----------shopping list-----------")
            for i in shopping_list :
                print(i)
            print('你的余额剩%s'%(salary))
            # break
            exit()
        else:
            print("invalid option")