Привет, я немного новичок в кодировании python, и я подготовил псевдокод, но я не могу правильно писать свой код на Python. Это мой псевдокод:
Input(Item)
Item = Item.split()
numberOfItem = count(Item)
until numberOfItem == 2:
output("Please select two Item")
input(Item)
itemCostDic = {"wood":200, "paper":100, "pen":10, "eraser":5}
specificItemCost = {}
for value in Item:
specificItemCost[value] = itemCostDic[value]
totalItemCost = sum(specificItemCost.value)
print(totalItemCost)
Я не уверен, как зацикливать "до" в моих кодах python.
"До" не может быть достигнут с помощью while
не равной петлю питона:
while numberOfItem != 2:
...
Но вам нужно будет включить изменяющееся значение numberOfItem
в сам цикл, чтобы он мог сломаться в какой-то момент:
#initialise variable
nuberOfItem=0
while numberOfItem != 2:
Item = input("Please select two items: ").split()
numberOfItem = len(Item)
while numberOfItem != 2:
будет зацикливаться до тех пор, пока вы не получите 2 элемента. Это не будет работать с телом цикла, если вначале у вас есть 2 элемента - этот тип проверки используется, когда вы добавляете/удаляете вещи в свой список внутри тела цикла и хотите остановить ровно 2 элемента в списке.
Вам нужно каким-то образом изменить значение, которое вы проверяете в своем состоянии внутри вашего цикла (или прямо сделать while len(yourList) != 2:
динамическая проверка в то время - lvl) или у вас бесконечный цикл.
Вы уточняете свой код с помощью своего дикта, чтобы проверить только действительные элементы. Вы можете хранить входы во второй dict вместе с суммами и суммировать их после завершения всех входов:
(В код входит запрос пользователя на ввод, пока не будут приведены действительные методы ответа для проверки ввода пользователя)
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))
Выход:
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
Никаких сумм:
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) ))
Выход:
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
item,amount = input("Item and amount, space between").split()
- это приведет к сбою, если задан только элемент, вам нужно будет добавить try: except ValueError:
вокруг этого, чтобы отловить ошибки путем ввода только элемента или номера. затем перейдите к пункту «is item in dict check» и «is действительно номер int».