0

Python解释器说paintRequiredCeiling是未定义的。我无法在代码中找到任何错误。目标是让程序从用户那里获取输入,然后计算油漆工作所需的成本/小时数。

import math

def main():
    # Prompts user for sq and paint price
    totalArea = float(input("Total sq of space to be painted? "))
    paintPrice = float(input("Please enter the price per gallon of paint. "))

    perHour = 20
    hoursPer115 = 8

    calculate(totalArea, paintPrice, perHour, hoursPer115)
    printFunction()

def calculate(totalArea, paintPrice, perHour, hoursPer115):
    paintRequired = totalArea / 115
    paintRequiredCeiling = math.ceil(paintRequired)
    hoursRequired = paintRequired * 8
    costOfPaint = paintPrice * paintRequiredCeiling
    laborCharges = hoursRequired * perHour
    totalCost = laborCharges + costOfPaint

def printFunction():
    print("The numbers of gallons of paint required:", paintRequiredCeiling)
    print("The hours of labor required:", format(hoursRequired, '.1f'))
    print("The cost of the paint: $", format(costOfPaint, '.2f'), sep='')
    print("Total labor charges: $", format(laborCharges, '.2f'), sep='')
    print("Total cost of job: $", format(totalCost, '.2f'), sep='')

main()
4

2 回答 2

1

该变量paintRequiredCeiling仅在您的计算函数中可用。它在你身上不存在printFunction。与其他变量类似。您需要将它们移到函数之外,或传递它们,以使其正常工作。

于 2013-10-02T19:57:30.393 回答
1

您的函数中没有return声明calculate():您正在计算所有这些值,然后在函数结束时将它们丢弃,因为这些变量都是函数的本地变量。

同样,您的printFunction()函数不接受任何要打印的值。所以它期望变量是全局的,因为它们不是,你会得到你得到的错误。

现在您可以使用全局变量,但这通常是错误的解决方案。相反,学习如何使用该return语句来返回calculate()函数的结果,将这些结果存储在 中的变量中main(),然后将它们传递给printFunction().

于 2013-10-02T19:58:04.843 回答