通过循环访问列表

时间:2015-10-14 22:27:13

标签: python

我正在尝试创建一个程序,其中我有一个商店,其中包含设定价格的商品。用户以100美元开头,并提示输入将要购买的商品编号(鞋子为“1”,袜子为“2”等)。应从开头总数中减去项目项目的成本,并要求用户购买另一项目。如果成本超过剩余的金额,那么它应该打印出“资金不足的声明”并被要求再次购买另一个项目。输入“0”应该导致程序退出。我的代码的第一个循环只打印出可用的项目和价格,但我对如何设置其余的循环感到困惑,因此每次减去正确的总数并且不会最终成为无限循环。

到目前为止

代码:

def main():
    print("You have $100 in funds available")
    wallet = 100
    items = ["shoes", "socks", "hat", "belt", "blouse", "dress", "tie"]
    prices = [54.99, 7.11, 6.49, 22.58, 21.73, 38.99, 14.83]

    for i in range( len(items)):
        print(i+1, "-", items[i], "\t$",prices[i])

    #itemNum = input("Please choose an item # to purchase, or '0' to quit: ")
    itemNum = ""
    while itemNum != "0":
        itemNum = input("Please choose an item # to purchase, or '0' to quit: ")
        for x in items:
            if wallet > prices[x]:
                wallet = wallet - prices[x]
                print("You have $",wallet,"in funds left")


            else:
                print("Sorry but you are unable to afford that item")

main()

0 个答案:

没有答案