while 1:
pie = 50
pieR = pie
pieRem = pieR - buy
print("We have ", pieRem, "pie(s) left!")
buy = int(input("How many pies would you like? "))
pieCost = 5
Pie = pieCost * buy
if buy == 1:
print(pieCost)
pieS = pieR - buy
elif buy > 1:
print(Pie * 0.75)
else:
print("Please enter how many pies you would like!")
当我打开控制台时,它会询问我想要买多少馅饼,然后我就这样做了我们剩下的馅饼数量,但每次都会刷新馅饼的价值。因此,如果我选择了我想要2个馅饼第一次它会说我们剩下48个馅饼(默认馅饼值是50)然后它再次问我第二次然后输入3而不是降到45,它会刷新并且下降到47。
我希望我解释得很好,希望有人知道如何解决这个问题,谢谢。
答案 0 :(得分:3)
每次代码循环回到开头时,pie
都会重新定义为50.您需要在pie
循环之外定义变量while
:
pie = 50
while 1:
...
很抱歉,但是您的代码很乱,尤其是变量名称。我为你清理了一下:
buy = 0
pies = 50
cost = 5
while 1:
print("We have ", pies, "pie(s) left!")
buy = int(input("How many pies would you like? "))
price = cost * buy
if buy == 1:
print(price)
pies -= 1
elif buy > 1:
print(buy * 0.75)
pies -= buy
else:
print("Please enter how many pies you would like!")
答案 1 :(得分:1)
来自@Haidros代码
buy,pies,cost = 0,50,5
while 1:
if pies<1:
print ('Sorry no pies left' )
break
print("We have ", pies, "pie(s) left!")
buy = int(input("How many pies would you like? "))
if pies-buy<0:buy = int(input("Only %s pies remaining How many pies would you like?"%pies))
if buy>0:
if buy==1:print(cost*buy)
else:print(cost*buy * 0.75)
pies-=buy
else:
print("Please enter how many pies you would like!")
答案 2 :(得分:0)
如果您使用类和对象,则可以使用全局变量,并且可以轻松地将代码扩展到其他产品(例如:羊角面包,百吉饼,汤,咖啡,三明治或其他任何产品......)
class pies:
""" Object To Sell Pies """
def __init__(self):
""" Constructor And Initialise Attributes """
self.pies=50
self.amount = 0
self.cost = 5
def buy(self,buy):
""" Method To Buy Pies """
if (buy > self.pies):
print "Sorry Only %d Pies in Stock" % self.pies
elif (self.pies >= 1):
self.pies =self.pies - buy
print "Cost is : %.02f" % ( 0.75 * buy )
print "We have %d and pies in stock" % (self.pies)
elif (self.pies == 1):
self.pies =self.pies - buy
print "Cost is : %.02f" % ( self.cost * buy )
print "We have %d pies in stock now" % (self.pies)
else:
print "Sorry Pies Out of Stock !"
self.buy = 0
self.pies = 0
将上面的代码保存为pieobject.py,然后使用以下代码调用它:
#!/usr/bin/env python
import os
from pieobject import pies
p = pies()
while True:
try:
amount=int(raw_input('Enter number of pies to buy:'))
except ValueError:
print "Not a number"
break
os.system('clear')
p.buy(amount)