最近在自学python,第一次在博客上写东西,放上一个自己做出来的非常简单的小程序:
# @Author: Joseph.Jostar
# @Time:2020/1/3 9:44
salary = 5000
commodity_dict = {"iphone11": 4800, "mac book": 10000, "coffee": 18, "book": 80, "bicycle": 1500}
commodity_list = []
while salary > 0:
msg = '''
---------商品信息----------
1. iphone11 : 4800
2. mac book : 10000
3. coffee : 18
4. book : 80
5. bicycle : 1500
您的余额为:%d
''' % salary
print(msg)
a = int(input("请输入您需要的商品编号"))
if a == 1:
salary = salary - commodity_dict["iphone11"]
commodity_list.append("iphone11")
print("您购买了iphone11,余额为%d" % salary)
elif a == 2:
salary = salary - commodity_dict["mac book"]
commodity_list.append("mac book")
print("您购买了mac book,余额为%d" % salary)
elif a == 3:
salary = salary - commodity_dict["coffee"]
commodity_list.append("coffee")
print("您购买了coffee,余额为%d" % salary)
elif a == 4:
salary = salary - commodity_dict["book"]
commodity_list.append("book")
print("您购买了book,余额为%d" % salary)
elif a == 5:
salary = salary - commodity_dict["bicycle"]
commodity_list.append("bicycle")
print("您购买了bicycle,余额为%d" % salary)
else:
print("您输入的编号有误,请重新输入")
continue
print("您的余额为:%d,您购买了 %s,是否还要购买[y/n]" % (salary, commodity_list))
continue_buy = input()
if continue_buy == "y":
continue
else:
print("您购买了%s \n 感谢购买,再见!" % commodity_list)
break
else:
print("您的余额为:%d" % salary, "如需购买请充值")
我第一次写代码的时候把msg放到了while外面,导致每次输出都是5000,后来打断点发现在外面的msg在进行while循环时不再进行运算,也就是即使改变salary也不会写入msg。下面是我简单的测试,证明了我的想法:
# @Author: Joseph.Jostar
# @Time:2020/1/3 11:02
count = 0
msg = "%d" % count
i = 0
while i <= 15:
count += 1
print(msg)
i += 1