如何使python食物计算器保持一致?

2024-04-26 10:52:43 发布

您现在位置:Python中文网/ 问答频道 /正文

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个。在

我希望我能解释清楚,我希望有人知道如何解决这个问题,谢谢。在


Tags: youbuymanylikeweprintpiewhile
3条回答

如果你使用类和对象,你就不需要全局变量了,你可以很容易地将代码扩展到其他产品(例如:牛角面包、百吉饼、汤、咖啡、三明治等等)在

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那就叫它:

^{pr2}$

每次代码循环回到开头,pie就会被重新定义为50。您需要在while循环之外定义变量pie

pie = 50
while 1:
    ...

抱歉,但是你的代码一团糟,尤其是变量名。我帮你清理了一下:

^{pr2}$

从下面的@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!")

相关问题 更多 >