我在python中做了一个小应用程序,但我不知道下一步该怎么做。
#!/usr/bin/env python
print("Welcome to the store!")
price_list = [['apple', 'orange', 'grapefruit', 'bomb', 'gun'], [3, 2, 5, 15, 10]]
inventory = []
print("You can buy the following things")
print(price_list[0][0])
print(price_list[1][0], 'dollars')
print(price_list[0][1])
print(price_list[1][1], 'dollars')
print(price_list[0][2])
print(price_list[1][2], 'dollars')
print(price_list[0][3])
print(price_list[1][3], 'dollars')
print(price_list[0][4])
print(price_list[1][4], 'dollars')
budget = 20
buy = input("What would you like to buy? Type in one of the previous options to buy something You only have 20 dollars to spend though! ")
print("You bought", buy)
if budget >= 0:
if buy == 'apple':
print("It cost 3 dollars")
budget -= 3
inventory.append('apple')
print("Your inventory is below")
print(inventory)
if buy == 'orange':
print("It cost 2 dollars")
budget -= 2
inventory.append('orange')
print("Your inventory is below")
print(inventory)
if buy == 'grapefruit':
print("It cost 5 dollars")
budget -= 5
inventory.append('grapefruit')
print("Your inventory is below")
print(inventory)
if buy == 'bomb':
print("It cost 15 dollars")
budget -= 15
inventory.append('bomb')
print("Your inventory is below")
print(inventory)
if buy == 'gun':
print("It cost 10 dollars")
budget -= 10
inventory.append('gun')
print("Your inventory is below")
print(inventory)
我想这样做,所以我可以添加一个东西,然后能够添加另一个东西,直到我已经减少我的预算,但如果我使用while语句,它只是不断添加我买的东西!请帮助!
答案 0 :(得分:0)
将if budget >= 0
更改为while budget >= 0
是正确的想法,您只需将用户输入请求移至while循环中。这样它会询问输入,检查商店中的项目,然后如果budget >= 0
它会再次执行,请求更多输入。
#!/usr/bin/env python
print("Welcome to the store!")
setup_price_list() #pseudocode
budget = 20
while budget >= 0:
buy = input("What would you like to buy?")
if buy == 'apple':
print("It cost 3 dollars")
budget -= 3
inventory.append('apple')
print("Your inventory is below")
print(inventory)
#the rest of the if statements
print("You bought", buy)
print("Your inventory is below")
print(inventory)
一旦你有了这个工作,我建议你看一下叫做字典的Python数据结构。它可以使这样的代码更简单,例如:
print("Welcome to the store!")
price_list = {'apple':3, 'orange':2, 'grapefruit':5, 'bomb':15, 'gun':10}
print("You can buy:")
for key in price_list:
item = key
price = price_list[key]
print(item, price)
budget = 20
while budget > 0:
buy = raw_input("What do you want to buy?")
price = price_list[buy] #You will get an error if you give it a key it doesn't have
budget -= price
print("You bought: ", buy)
print("It costed: $", price)
哦,你可能想加一张支票,看看你在购买之前是否还有足够的钱买这件物品,否则只要你没欠债,你还可以买任何东西,我会留给你弄清楚:)