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。

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

4

3 回答 3

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!")
于 2013-07-05T03:16:32.153 回答
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!")
于 2013-07-05T03:32:53.637 回答
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)
于 2013-07-05T10:43:37.897 回答