<p><code>while numberOfItem != 2:</code>将循环直到得到2个项目。
如果你最初有两个项目在循环体中,这不会运行循环体-当你在循环体中添加/删除<em>内容并希望在列表中正好有两个项目时,会使用这种检查。你知道吗</p>
<p>您需要以某种方式修改在循环中的条件中检查的值(或者直接在while-lvl中执行<code>while len(yourList) != 2:</code>动态检查),否则您将有一个无休止的循环。你知道吗</p>
<hr/>
<p>您可以使用dict优化代码,以验证是否只给出了有效项。
您可以将输入与金额一起存储到第二个dict中,并在所有输入完成后对其求和,例如:</p>
<p>(代码包含<a href="https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response/23294659">Asking the user for input until they give a valid response</a>方法来验证用户输入)</p>
<pre><code>itemCostDic = {"wood":200, "paper":100, "pen":10, "eraser":5}
print("Inventory:")
for k,v in itemCostDic.items():
print( " - {} costs {}".format(k,v))
print("Buy two:")
shoppingDic = {}
while len(shoppingDic) != 2:
# item input and validation
item = input("Item:").lower()
if item not in itemCostDic: # check if we have the item in stock
print("Not in stock.")
continue # jumps back to top of while
if item in shoppingDic: # check if already bought, cant buy twice
print("You bought all up. No more in stock.")
continue # jumps back to top of while
# amount input and validation
amount = input("Amount:")
try:
a = int(amount) # is it a number?
except ValueError:
print("Not a number.")
continue # start over with item input, maybe next time user is wiser
# add what was bought to the cart
shoppingDic[item] = a
s = 0
print("Bought:")
for k,v in shoppingDic.items():
print( " - {} * {} = {}".format(k,v, itemCostDic[k]*v))
s += itemCostDic[k]*v
print("Total: {:>12}".format( s))
</code></pre>
<p>输出:</p>
<pre><code>Inventory:
- wood costs 200
- paper costs 100
- pen costs 10
- eraser costs 5
Buy two:
Item:socks
Not in stock.
Item:paper
Amount:5
Item:paper
You bought all up. No more in stock.
Item:pen
Amount:k
Not a number.
Item:pen
Amount:10
Bought:
- paper * 5 = 500
- pen * 10 = 100
Total: 600
</code></pre>
<hr/>
<p>无金额:</p>
<pre><code>itemCostDic = {"wood":200, "paper":100, "pen":10, "eraser":5}
print("Inventory:")
for k,v in itemCostDic.items():
print( " - {} costs {}".format(k,v))
print("Buy two:")
shoppingCart = set() # use a list if you can shop for 2 times paper
while len(shoppingCart) != 2:
# item input and validation
item = input("Item:").lower()
if item not in itemCostDic: # check if we have the item in stock
print("Not in stock.")
continue # jumps back to top of while
if item in shoppingCart: # check if already bought, cant buy twice
print("You bought all up. No more in stock.")
continue # jumps back to top of while
# add what was bought to the cart
shoppingCart.add(item)
s = 0
print("Sum of shopped items: {:>6}".format( sum ( itemCostDic[i] for i in shoppingCart) ))
</code></pre>
<p>输出:</p>
<pre><code>Inventory:
- wood costs 200
- paper costs 100
- pen costs 10
- eraser costs 5
Buy two:
Item:socks
Not in stock.
Item:paper
Item:paper
You bought all up. No more in stock.
Item:wood
Sum of shopped items: 300
</code></pre>