我试着写一个程序,计算出制作蛋糕需要多少特定的配料,然后把这些配料加在一起计算出每种配料总共需要多少。你知道吗
chocCupcake = int(input("How many chocolate cupcakes would you like to make? "))
lemonDrizzle = int(input("How many lemon drizzle cakes would you like to make? "))
def chocolate_cupcake():
plainFlour = 12
sugar = 14
unsaltButter = 4
freeRangeEgg = 0.1
totalFlour = float(plainFlour * chocCupcake)
totalSugar = float(sugar * chocCupcake)
totalButter = float(unsaltButter * chocCupcake)
totalEggs = float(freeRangeEgg * chocCupcake)
print("""You will need:
"""+str(totalFlour)+""" grams of plain flour
"""+str(totalSugar)+""" grams of sugar
"""+str(totalButter)+""" grams of unsalted butter
"""+str(totalEggs)+" free range eggs ")
chocolate_cupcake()
def lemon_drizzle():
plainFlour = 240
sugar = 300
unsaltButter = 80
freeRangeEgg = 4.5
totalFlour = float(plainFlour * lemonDrizzle)
totalSugar = float(sugar * lemonDrizzle)
totalButter = float(unsaltButter * lemonDrizzle)
totalEggs = float(freeRangeEgg * lemonDrizzle)
print("""You will need:
"""+str(totalFlour)+""" grams of plain flour
"""+str(totalSugar)+""" grams of sugar
"""+str(totalButter)+""" grams of unsalted butter
"""+str(totalEggs)+" free range eggs ")
lemon_drizzle()
所以我需要两种功能的面粉加在一起,还有总糖,等等。你知道吗
你现在写代码的方式-这是不可能做到的。局部变量是局部变量。它们属于函数,不存在于函数之外。你知道吗
你应该用不同的方法处理这个问题。不用在函数中存储成分,您可以将它们存储在数据结构(如map)中(我只显示了2种成分):
那么,要得到一些蛋糕的配料,只需要简单的词典理解:
您可以使用zip将它们相加:
如果你是一个初学者,这里有很多新的东西,但是这些方法对于Python来说是非常基本的,所以你一定要学习它们。你知道吗
有很多不同的方法可以做到这一点,因为这主要是一个重构的问题。在我看来,最简单的方法是将这些成分作为每个功能的结果返回,如下所示:
然后在调用每个函数时存储该信息
然后你可以把它们加起来
只是要补充一个警告,虽然这种方式需要改变现有的代码最少,但它绝对不是最好的方式。这不是最容易理解的。其中一个例子就是为什么recipe方法会以随机顺序返回配料列表。你知道吗
您正在寻找具有类的面向对象设计(OOP-面向对象编程)。dictionary或namedtuple方法可能是最简单、最适合您的项目。你知道吗
OOP非常强大,很好理解。我将向你展示一些更先进的东西,你可以做的类。您可以使类与python运算符+、-、/、*等一起工作。http://rafekettler.com/magicmethods.html
示例:
相关问题 更多 >
编程相关推荐