我尝试了几种不同的配置,但不明白为什么最后的行没有打印出来。其他一切似乎都如期而至。 这个程序要求用户输入要粉刷的墙壁空间的平方英尺和每加仑油漆的价格。然后程序应显示以下内容:
总成本(人工+油漆)
def main():
squareFeet = float(input("Enter square feet of wall space to be painted: "))
pricePerGallon = float(input("Enter price of gallon of paint: "))
gallonsRequired = calcGallons
hoursRequired = calcHours
paintCost = calcPaintCost
laborCost = calcLabor
totalCost = calcTotal
def calcGallons() :
gallonsRequired = (squareFeet / 115)
return gallonsRequired
def calcHours() :
hoursRequired = (squareFeet / 115) * 8
return hoursRequired
def calcPaintCost() :
paintCost = pricePerGallon * gallonsRequired
return paintCost
def calcLabor() :
laborCost = hoursRequired * 40
return laborCost
def calcTotal() :
totalCost = laborCost + paintCost
return totalCost
print(" Gallons of paint required: ", gallonsRequired)
print(" Hours of labor required: ", hoursRequired)
print("Cost of paint: ", paintCost)
print("Cost of labor: ", laborCost)
print("Total cost of paint job: ", totalCost)
main()
您对scope、函数调用和return有一个根本性的误解。在
函数调用
在
main
中,您将设置一组变量,如下所示:这实际上是将变量
gallonsRequired
设置为函数calgGallons
而不是该函数的结果。在你应该做的是:
^{pr2}$对所有其他函数调用也要这样做。在
范围
每个功能都有自己的作用域。如果你把每个函数看作一个框,那么它的作用域就是它内部的任何东西:变量、语句等。从函数中声明的任何变量都在该函数的作用域内。因此,当您在
main
中执行此操作时:squareFeet
被“卡住”在里面。其他函数无法访问它。这是为了允许代码的封装。如果希望其他函数可以访问某个变量,则必须将该变量传递到函数中。在在这种情况下,您需要从
calcGallons
访问squareFeet
。为此,您需要在如下调用时传入squareFeet
:您需要告诉Python,您希望从
calcGallons
的定义中得到一个参数,如下所示:您需要对所有函数调用执行此操作,但只将所需的值传递到每个函数中。如果您需要多个参数(这就是您传入的值),只需用逗号分隔它们。在
返回
当您从函数内调用
return
时,该函数立即退出,并且(如果指定返回值)将结果返回给调用者。例如,在这种情况下:1
将被打印到控制台。为什么?因为当从foo
内调用return 1
时,foo
退出,然后print函数获取返回的1
,并使用它打印到控制台。在相关问题 更多 >
编程相关推荐