2013-07-05 22 views
0
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.我如何使我的蟒食品计算器保持一致?

我希望我解释得很好,希望有人知道如何解决这个问题,谢谢。

回答

3

您的每一次代码循环回到起点,pie被重新定义为50.你要定义while循环的变量pie外:

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!") 
+0

我试过了,但它仍然刷新 –

+0

@SamirChahine我已经清理了你的代码 – TerryA

+0

检查我的答案itworks。 @Haidro有一些错误,比如'pies-buy'等 – suhailvs

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

这只是我的答案的副本,密集的代码,看起来很糟糕:'稀疏比密集好。' – TerryA

+0

@Haidro对不起,我会提及你的代码中的名称。抱歉!! :-( – suhailvs

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)