Python: 自动售货机
Python: vending machine
该程序提供商品,让用户为商品付款,'gives' 商品,并更新每个商品的库存。它似乎或多或少起作用。我有 2 个问题:
1) 在用户回答'n'到'buy something else? (y/n): '后,我不知道如何退出自动售货机程序。
2) 有没有办法制作代码 simpler/better?
def vend():
a = {'item': 'choc', 'price': 1.5, 'stock': 2}
b = {'item': 'pop', 'price': 1.75, 'stock': 1}
c = {'item': 'chips', 'price': 2.0, 'stock': 3}
d = {'item': 'gum', 'price': 0.50, 'stock': 1}
e = {'item': 'mints', 'price': 0.75, 'stock': 3}
items = [a, b, c, d, e]
cim = 0 # cash in machine
print('welcome to vending machine! \n***************')
# show items, prices
def show(items):
print('\nitems available \n***************')
for item in items:
if item.get('stock') == 0:
items.remove(item)
for item in items:
print(item.get('item'), item.get('price'))
print('***************\n')
# have user choose item
while True:
show(items)
selected = input('select item: ')
for item in items:
if selected == item.get('item'):
selected = item
price = selected.get('price')
while cim < price:
cim = float(input('insert ' + str(price - cim) + ': '))
else:
print('you got ' + selected.get('item'))
selected['stock'] -= 1
cim -= price
print('cash remaining: ' + str(cim))
a = input('buy something else? (y/n): ')
if a == 'n':
if cim != 0:
print(str(cim) + ' refunded')
cim = 0
print('thank you, have a nice day!\n')
break
else:
print('thank you, have a nice day!\n')
break
else:
continue
vend()
1) I don't know how to exit the the vending machine program after the
user answers 'n' to 'buy something else? (y/n): '.
break语句在Python中跳出第一个for或while 包含它的循环。您只是退出显示的 for 循环。 while True 条件让你永远循环。
但是,您做了一些聪明的事情,您在 vend 函数中包含了所有自动售货机功能。如果您使用 return 语句代替 break,您不仅会退出 vend 函数,您将到达整个程序的末尾并退出。
return 语句也用于 return 来自函数调用的值,但在您的情况下您不需要这样做。
另外,您不需要也不应该有两个独立的函数出口。删除这三行:
else:
print('thank you, have a nice day!\n')
break
缩减您删除的三行上方的两行,并将 break 替换为 return.
您还可以进行其他改进,但这只是一个开始。
您只需要添加一个布尔变量,如果用户的答案是n
,您将其设置为false。另请注意,代码中存在问题,您没有以正确的方式更新 cim
的值。你要考虑到一个人可能需要投入不止一枚硬币,所以你必须累计投入的硬币总数:
def vend():
a = {'item': 'choc', 'price': 1.5, 'stock': 2}
b = {'item': 'pop', 'price': 1.75, 'stock': 1}
c = {'item': 'chips', 'price': 2.0, 'stock': 3}
d = {'item': 'gum', 'price': 0.50, 'stock': 1}
e = {'item': 'mints', 'price': 0.75, 'stock': 3}
items = [a, b, c, d, e]
cim = 0 # cash in machine
print('welcome to vending machine! \n***************')
# show items, prices
def show(items):
print('\nitems available \n***************')
for item in items:
if item.get('stock') == 0:
items.remove(item)
for item in items:
print(item.get('item'), item.get('price'))
print('***************\n')
continueToBuy = True
# have user choose item
while continueToBuy == True:
show(items)
selected = input('select item: ')
for item in items:
if selected == item.get('item'):
selected = item
price = selected.get('price')
while cim < price:
cim = cim + float(input('insert ' + str(price - cim) + ': '))
print('you got ' + selected.get('item'))
selected['stock'] -= 1
cim -= price
print('cash remaining: ' + str(cim))
a = input('buy something else? (y/n): ')
if a == 'n':
continueToBuy = False
if cim != 0:
print(str(cim) + ' refunded')
cim = 0
print('thank you, have a nice day!\n')
break
else:
print('thank you, have a nice day!\n')
break
else:
continue
vend()
此外,我认为这是介绍面向对象编程的一个很好的例子。它可以让你拥有更好的结构化代码,让你专注于你想要开发的逻辑。这是一个可能的实现:
class Item:
def __init__(self, name, price, stock):
self.name = name
self.price = price
self.stock = stock
def updateStock(self, stock):
self.stock = stock
def buyFromStock(self):
if self.stock == 0:
# raise not item exception
pass
self.stock -= 1
class VendingMachine:
def __init__(self):
self.amount = 0
self.items = []
def addItem(self, item):
self.items.append(item)
def showItems(self):
print('\nitems available \n***************')
for item in self.items:
if item.stock == 0:
self.items.remove(item)
for item in self.items:
print(item.name, item.price)
print('***************\n')
def addCash(self, money):
self.amount = self.amount + money
def buyItem(self, item):
if self.amount < item.price:
print('You can\'t but this item. Insert more coins.')
else:
self.amount -= item.price
item.buyFromStock()
print('You got ' +item.name)
print('Cash remaining: ' + str(self.amount))
def containsItem(self, wanted):
ret = False
for item in self.items:
if item.name == wanted:
ret = True
break
return ret
def getItem(self, wanted):
ret = None
for item in self.items:
if item.name == wanted:
ret = item
break
return ret
def insertAmountForItem(self, item):
price = item.price
while self.amount < price:
self.amount = self.amount + float(input('insert ' + str(price - self.amount) + ': '))
def checkRefund(self):
if self.amount > 0:
print(self.amount + " refunded.")
self.amount = 0
print('Thank you, have a nice day!\n')
def vend():
machine = VendingMachine()
item1 = Item('choc', 1.5, 2)
item2 = Item('pop', 1.75, 1)
item3 = Item('chips', 2.0, 3)
item4 = Item('gum', 0.50, 1)
item5 = Item('mints',0.75, 3)
machine.addItem(item1)
machine.addItem(item2)
machine.addItem(item3)
machine.addItem(item4)
machine.addItem(item5)
print('Welcome to the vending machine!\n***************')
continueToBuy = True
while continueToBuy == True:
machine.showItems()
selected = input('select item: ')
if machine.containsItem(selected):
item = machine.getItem(selected)
machine.insertAmountForItem(item)
machine.buyItem(item)
a = input('buy something else? (y/n): ')
if a == 'n':
continueToBuy = False
machine.checkRefund()
else:
continue
else:
print('Item not available. Select another item.')
continue
vend()
有关 OOP 的详细信息,请参阅 a resource like this。
该程序提供商品,让用户为商品付款,'gives' 商品,并更新每个商品的库存。它似乎或多或少起作用。我有 2 个问题:
1) 在用户回答'n'到'buy something else? (y/n): '后,我不知道如何退出自动售货机程序。
2) 有没有办法制作代码 simpler/better?
def vend():
a = {'item': 'choc', 'price': 1.5, 'stock': 2}
b = {'item': 'pop', 'price': 1.75, 'stock': 1}
c = {'item': 'chips', 'price': 2.0, 'stock': 3}
d = {'item': 'gum', 'price': 0.50, 'stock': 1}
e = {'item': 'mints', 'price': 0.75, 'stock': 3}
items = [a, b, c, d, e]
cim = 0 # cash in machine
print('welcome to vending machine! \n***************')
# show items, prices
def show(items):
print('\nitems available \n***************')
for item in items:
if item.get('stock') == 0:
items.remove(item)
for item in items:
print(item.get('item'), item.get('price'))
print('***************\n')
# have user choose item
while True:
show(items)
selected = input('select item: ')
for item in items:
if selected == item.get('item'):
selected = item
price = selected.get('price')
while cim < price:
cim = float(input('insert ' + str(price - cim) + ': '))
else:
print('you got ' + selected.get('item'))
selected['stock'] -= 1
cim -= price
print('cash remaining: ' + str(cim))
a = input('buy something else? (y/n): ')
if a == 'n':
if cim != 0:
print(str(cim) + ' refunded')
cim = 0
print('thank you, have a nice day!\n')
break
else:
print('thank you, have a nice day!\n')
break
else:
continue
vend()
1) I don't know how to exit the the vending machine program after the user answers 'n' to 'buy something else? (y/n): '.
break语句在Python中跳出第一个for或while 包含它的循环。您只是退出显示的 for 循环。 while True 条件让你永远循环。
但是,您做了一些聪明的事情,您在 vend 函数中包含了所有自动售货机功能。如果您使用 return 语句代替 break,您不仅会退出 vend 函数,您将到达整个程序的末尾并退出。
return 语句也用于 return 来自函数调用的值,但在您的情况下您不需要这样做。
另外,您不需要也不应该有两个独立的函数出口。删除这三行:
else:
print('thank you, have a nice day!\n')
break
缩减您删除的三行上方的两行,并将 break 替换为 return.
您还可以进行其他改进,但这只是一个开始。
您只需要添加一个布尔变量,如果用户的答案是n
,您将其设置为false。另请注意,代码中存在问题,您没有以正确的方式更新 cim
的值。你要考虑到一个人可能需要投入不止一枚硬币,所以你必须累计投入的硬币总数:
def vend():
a = {'item': 'choc', 'price': 1.5, 'stock': 2}
b = {'item': 'pop', 'price': 1.75, 'stock': 1}
c = {'item': 'chips', 'price': 2.0, 'stock': 3}
d = {'item': 'gum', 'price': 0.50, 'stock': 1}
e = {'item': 'mints', 'price': 0.75, 'stock': 3}
items = [a, b, c, d, e]
cim = 0 # cash in machine
print('welcome to vending machine! \n***************')
# show items, prices
def show(items):
print('\nitems available \n***************')
for item in items:
if item.get('stock') == 0:
items.remove(item)
for item in items:
print(item.get('item'), item.get('price'))
print('***************\n')
continueToBuy = True
# have user choose item
while continueToBuy == True:
show(items)
selected = input('select item: ')
for item in items:
if selected == item.get('item'):
selected = item
price = selected.get('price')
while cim < price:
cim = cim + float(input('insert ' + str(price - cim) + ': '))
print('you got ' + selected.get('item'))
selected['stock'] -= 1
cim -= price
print('cash remaining: ' + str(cim))
a = input('buy something else? (y/n): ')
if a == 'n':
continueToBuy = False
if cim != 0:
print(str(cim) + ' refunded')
cim = 0
print('thank you, have a nice day!\n')
break
else:
print('thank you, have a nice day!\n')
break
else:
continue
vend()
此外,我认为这是介绍面向对象编程的一个很好的例子。它可以让你拥有更好的结构化代码,让你专注于你想要开发的逻辑。这是一个可能的实现:
class Item:
def __init__(self, name, price, stock):
self.name = name
self.price = price
self.stock = stock
def updateStock(self, stock):
self.stock = stock
def buyFromStock(self):
if self.stock == 0:
# raise not item exception
pass
self.stock -= 1
class VendingMachine:
def __init__(self):
self.amount = 0
self.items = []
def addItem(self, item):
self.items.append(item)
def showItems(self):
print('\nitems available \n***************')
for item in self.items:
if item.stock == 0:
self.items.remove(item)
for item in self.items:
print(item.name, item.price)
print('***************\n')
def addCash(self, money):
self.amount = self.amount + money
def buyItem(self, item):
if self.amount < item.price:
print('You can\'t but this item. Insert more coins.')
else:
self.amount -= item.price
item.buyFromStock()
print('You got ' +item.name)
print('Cash remaining: ' + str(self.amount))
def containsItem(self, wanted):
ret = False
for item in self.items:
if item.name == wanted:
ret = True
break
return ret
def getItem(self, wanted):
ret = None
for item in self.items:
if item.name == wanted:
ret = item
break
return ret
def insertAmountForItem(self, item):
price = item.price
while self.amount < price:
self.amount = self.amount + float(input('insert ' + str(price - self.amount) + ': '))
def checkRefund(self):
if self.amount > 0:
print(self.amount + " refunded.")
self.amount = 0
print('Thank you, have a nice day!\n')
def vend():
machine = VendingMachine()
item1 = Item('choc', 1.5, 2)
item2 = Item('pop', 1.75, 1)
item3 = Item('chips', 2.0, 3)
item4 = Item('gum', 0.50, 1)
item5 = Item('mints',0.75, 3)
machine.addItem(item1)
machine.addItem(item2)
machine.addItem(item3)
machine.addItem(item4)
machine.addItem(item5)
print('Welcome to the vending machine!\n***************')
continueToBuy = True
while continueToBuy == True:
machine.showItems()
selected = input('select item: ')
if machine.containsItem(selected):
item = machine.getItem(selected)
machine.insertAmountForItem(item)
machine.buyItem(item)
a = input('buy something else? (y/n): ')
if a == 'n':
continueToBuy = False
machine.checkRefund()
else:
continue
else:
print('Item not available. Select another item.')
continue
vend()
有关 OOP 的详细信息,请参阅 a resource like this。