Python进阶之路——简单购物代码
1.input 输入默认为string类型,如果需要使用输入的数字,要先转换为整型:
![](https://images2018.cnblogs.com/blog/901958/201803/901958-20180301221655855-407297557.png)
2.需要显示元组序号的有两种方式:
3.python里,比较符号可以简写:
4.python里几种输出变量的方式,注意空格:
5.python里可以高亮输出:
![](https://images2018.cnblogs.com/blog/901958/201803/901958-20180301222220921-305191052.png)
结果为
或者
结果为;
源代码:
product_list = [
('iphone', 5000),
('mac Pro', 12000),
('bike', 800),
('book', 120),
('watch', 10600),
('coffee', 20)
]
shopping_list = []
salary = input("input you salary:")
if salary.isdigit():
salary = int(salary)
while True:
# for item in product_list:
# print(product_list.index(item), item)
for index, item in enumerate(product_list):
print(index, item)
user_choice = input("请输入想要买的商品序号:")
if user_choice.isdigit():
user_choice = int(user_choice)
if 0 <= user_choice < len(product_list):
p_item = product_list[user_choice]
if p_item[1] <= salary:
shopping_list.append(p_item)
salary -= p_item[1]
print("%s is added into your shopping_list,the current balance is \033[31;1m%s\033[0m" % (p_item[0], salary))
else:
print("\033[41;1m余额不足\033[0m")
else:
print("\033[41;1m商品不存在,请重新输入\033[0m")
elif user_choice == 'q':
print("--------shopping_list--------")
for p in shopping_list:
print(p)
print("your current salary:",salary)
exit()
else:
print("\033[41;1m invalid input\033[0m")
else:
print("\033[41;1m invalid input\033[0m")