Python绘制作业估计器无法获取函数

2024-04-28 04:48:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试了几种不同的配置,但不明白为什么最后的行没有打印出来。其他一切似乎都如期而至。 这个程序要求用户输入要粉刷的墙壁空间的平方英尺和每加仑油漆的价格。然后程序应显示以下内容:

  • 所需加仑数
  • 所需工时
  • 油漆成本
  • 人工费
  • 总成本(人工+油漆)

     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()
    

Tags: of程序returnmaindeffloatprintpaint
1条回答
网友
1楼 · 发布于 2024-04-28 04:48:02

您对scope函数调用return有一个根本性的误解。在

函数调用

main中,您将设置一组变量,如下所示:

gallonsRequired = calcGallons

这实际上是将变量gallonsRequired设置为函数calgGallons而不是该函数的结果。在

你应该做的是:

^{pr2}$

对所有其他函数调用也要这样做。在

范围

每个功能都有自己的作用域。如果你把每个函数看作一个框,那么它的作用域就是它内部的任何东西:变量、语句等。从函数中声明的任何变量都在该函数的作用域内。因此,当您在main中执行此操作时:

squareFeet = float(input("Enter square feet of wall space to be painted: "))

squareFeet被“卡住”在里面。其他函数无法访问它。这是为了允许代码的封装。如果希望其他函数可以访问某个变量,则必须将该变量传递到函数中。在

在这种情况下,您需要从calcGallons访问squareFeet。为此,您需要在如下调用时传入squareFeet

gallonsRequired = calcGallons(squareFeet)

您需要告诉Python,您希望从calcGallons的定义中得到一个参数,如下所示:

def calcGallons(squareFeet):
    return squareFeet / 115 # no need to set an extra variable
                            # just return the result of the statement

您需要对所有函数调用执行此操作,但只将所需的值传递到每个函数中。如果您需要多个参数(这就是您传入的值),只需用逗号分隔它们。在

返回

当您从函数内调用return时,该函数立即退出,并且(如果指定返回值)将结果返回给调用者。例如,在这种情况下:

def foo():
    return 1
    print(5)

print(foo())

1将被打印到控制台。为什么?因为当从foo内调用return 1时,foo退出,然后print函数获取返回的1,并使用它打印到控制台。在


  • 根据Pep8样式指南,变量名使用snake_case而不是camelCase

相关问题 更多 >