购物车小程序:
知识点:
1. input()函数,while循环, if...elseif...else语句,for循环
2. 字符串方法 .isdigit()和.center()
3. 枚举 enumerate()
4. 列表切片与列表方法追加.append()
5. 词典的使用
6. 字符串格式化输出
#! /usr/bin/env python3
# -*- coding:UTF-8 -*-
# Author:F.W
salary = input("input your salary:")
if salary.isdigit():
salary = int(salary) 输入的字符串如果是数字,强制转换为整型,方便后续比较大小
else:
exit("invalid data type!") 输入如果不符合要求,提示退出程序
Welcome_msg = "Welcome to FAN shopping mall".center(50, '-')
print(Welcome_msg)
exit_flag = False
Product_List = [('iphone', 5000), ('bike', 700), ('cloth', 300), ('basketball', 150)]
Shopping_car = []
while not exit_flag:
print('Product_List'.center(50, '-'))
for item in enumerate(Product_List):
index = item[0] 切片获得商品序号
P_Name = item[1][0] 切片获得商品名称
P_Price = item[1][1] 切片获得商品价格
print(index, '.', P_Name, P_Price) 统一打印商品清单的输出次序
User_Choice = input("What do you wanna buy? choose commodity's index or 'q'/'c' to do next(Note: q=quick,c=check)")
if User_Choice.isdigit():
User_Choice = int(User_Choice)
if User_Choice < len(Product_List): 用户选择在商品数量范围内
P_item = Product_List[User_Choice]
if P_item[1] <= salary: 购买能力的衡量 商品价格与薪资的对比
Shopping_car.append(P_item) 将商品追加到购物车列表中
salary -= P_item[1] 扣款
print("Added %s to Shopping_car, Your current balance is \033[1;43;31m %s \033[0m" % (P_item, salary))
else:
print("you current balance is %s, cannot afford this commodity %s your wanted." % (salary, P_item))
else: 如果选择超出范围,给予提醒!
print("you selected number is out of range, please check the Product_list then enter current number!")
else:
if User_Choice == 'c': 用户选择-查看购买信息及薪资结余情况以便下一步选择
print("Your purchased products as follows:".center(50, '-'))
for item in enumerate(Shopping_car):
print(item)
print("End".center(50, '-'))
print("your current balance is %s" % salary)
elif User_Choice == 'q':用户选择-决定结束购物,打印商品信息和薪资余额情况
print("Your purchased products as follows:".center(50, '-'))
for item in enumerate(Shopping_car):
print(item)
print("End".center(50, '-'))
print("your current balance is %s" % salary)
print("Thanks for your shopping! Bye!")
exit_flag = True 跳出while循环