购物车程序
基础要求:
1、启动程序后,输入用户名密码后,让用户输入工资,然后打印商品列表
2、允许用户根据商品编号购买商品
3、用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒
4、可随时退出,退出时,打印已购买商品和余额
5、在用户使用过程中,
关键输出,如余额,商品已加入购物车等消息,需高亮显示
扩展需求:
1、用户下一次登录后,输入用户名密码,直接回到上次的状态,即上次消费的余额什么的还是那些,再次登录可继续购买
2、允许查询之前的消费记录
goods =[
{"name":
"电脑", "price": 1999},
{"name":
"鼠标", "price": 10},
{"name":
"游艇", "price": 20},
{"name":
"美女", "price": 998}
]
f = open('records')
li = f.readlines()
list1 = []
remaining = 0
for i in li:
i = eval(i.strip())
list1.append(i)
#print(list1)
buy = []
for i in list1:
buy.append(i[0])
remaining = i[1]
#print(buy,'--------',remaining)
f.close()
shopping_chart = []
exit_flag = False
username = input('username:')
password = input('password:')
if username == 'mary' and password == '123456':
print('login successfully')
if not list1:
salary = int(input('your salary:'))
remaining = salary
else:
salary = remaining
while not exit_flag:
print('商品列表'.center(30, '-'))
for k, v in enumerate(goods):
print('%s. %s %s' % (k, v['name'], v['price']))
choice = input('what do you want to buy ? please input SKU:(查询消费记录:inq 退出:q )')
if choice.isdigit():
choice = int(choice)
# print(type(choice))
if choice >= 0 and choice < len(goods):
if salary > goods[choice]['price']:
shopping_chart.append(goods[choice])
print(goods[choice]['name'], '\033[1;31;44m已加入购物车\033[0m')
salary -= goods[choice]['price']
# print(salary)
else:
print('\033[1;31;44m抱歉,您的余额不足!\033[0m')
else:
print('商品不在列表里')
elif choice == 'q':
exit_flag = True
if shopping_chart:
print('\033[1;31;44m已购买商品\033[0m'.center(44, '-'))
for k, v in enumerate(shopping_chart):
print('''%s. %s %s''' % (k, v['name'], v['price']))
print('\033[1;31;43m余额\033[0m'.center(49, '-'))
print(salary)
f = open('records','a')
f.write('[%s,%s]\n' % (shopping_chart,salary))
f.close()
elif choice == 'inq':
f = open('records','a')
print('\033[1;31;44m此前消费记录\033[0m'.center(44, '-'))
for k in buy:
for i in k:
print(i['name'],i['price'])
print('\033[1;31;43m余额\033[0m'.center(49, '-'))
print(remaining)
f.close()
else:
print('请输入正确的商品编号')
else:
print('username or password is wrong')
get 知识点:
eval()可以转换字符串,但是不能转换本身类型就是字符串的元素
举例:
>>> a = '[1,2,3]'
>>> type(a)
<class 'str'>
>>> b = eval(a)
>>> b
[1, 2, 3]
>>> type(b)
<class 'list'>
>>> eval('abc')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'abc' is not defined
因为本身就是字符串了