![](/img/trans.png)
[英]How do I make a linear graphing calculator in Python with turtle graphics?
[英]How do i make my python food calculator consistent?
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!")
当我打开控制台时,它会询问我要购买多少个馅饼,而我做到了,因此,我们剩下的馅饼数量会显示出来,但是pie的值每次都会刷新。 因此,如果我第一次选择要2个饼,那就表示我们还剩48个饼(默认派值为50),然后在第二次问我之后,我输入3,而不是降到45,它会刷新下降到47。
我希望我解释得很好,希望有人知道如何解决此问题,谢谢。
每次您的代码循环回到开头时, 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!")
从下面的@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!")
如果使用类和对象,则无需使用全局变量,并且可以轻松地将代码扩展到其他产品(例如:羊角面包,百吉饼,汤,咖啡,三明治或其他。)
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.