Python中的乘法函数

Python中的乘法函数,python,function,definition,multiplication,Python,Function,Definition,Multiplication,我正在为我的班级写一个简短的程序,我被最后一部分卡住了。当我运行程序时,所有函数都会正常运行,直到代码结束,我试图乘以两个单独函数的成本,以定义另一个函数。我怎样才能纠正这个问题 以下是完整的代码: def main(): wall_space = float(input('Enter amount of wall space in square feet: ')) gallon_price = float(input('Enter the cost of paint per g

我正在为我的班级写一个简短的程序,我被最后一部分卡住了。当我运行程序时,所有函数都会正常运行,直到代码结束,我试图乘以两个单独函数的成本,以定义另一个函数。我怎样才能纠正这个问题

以下是完整的代码:

def main():
    wall_space = float(input('Enter amount of wall space in square feet: '))
    gallon_price = float(input('Enter the cost of paint per gallon: '))
    rate_factor = wall_space / 115
    total_gallons(rate_factor, 1)
    total_labor_cost(rate_factor, 8)
    total_gal_cost(rate_factor, gallon_price)
    total_hourly_cost(rate_factor, 20)
    total_cost(total_hourly_cost, total_gal_cost)
    print()

def total_gallons(rate1, rate2):
    result = rate1 * rate2
    print('The number of gallons of required is: ', result)
    print()

def total_labor_cost(rate1, rate2):
    result = rate1 * rate2
    print('The hours of labor required are: ', result)
    print()

def total_gal_cost(rate1, rate2):
    result = rate1 * rate2
    print('The cost of the paint in total is: ', result)
    print()

def total_hourly_cost(rate1, rate2):
    result = rate1 * rate2
    print('The total labor charges are: ', result)
    print()

def total_cost(rate1, rate2):
    result = rate1 * rate2
    print('This is the total cost of the paint job: ', result)
    print()

main()

我在这里绝望了,伙计们

最初的问题是,您将total_hourly_cost和total_gal_cost函数本身传递给total_cost,后者希望数字作为参数,而不是函数

真正的问题是,您的函数只是在打印,而您可能希望它们返回计算的值

def total_hourly_cost(rate1, rate2):
    result = rate1 * rate2
    print('The total labor charges are: ', result)
    print()

    return result
调用函数时,将结果存储在变量中,就像对输入所做的那样

然后将该结果传递给最终函数:

total_cost(per_hour, per_gallon)
不要在所有功能中使用打印;让它们返回值:

def total_hourly_cost(rate1, rate2):
    result = rate1 * rate2
    return result
然后,您可以从main打印结果:

print('The total labor charges are: {}'.format(total_hourly_cost(rate_factor, 20)))
但是如果你看看你的函数,它们都在做同样的事情:乘以两个参数。您不需要多个函数都执行相同的工作。事实上,您根本不需要任何函数。 放弃函数并使用变量:

total_hourly_cost = rate_factor * 20
print('The total labor charges are: {}'.format(total_hourly_cost))

您应该了解如何从python中的函数返回值,将它们存储在变量中,然后将它们重新用于其他计算


我们可以通过以下方式将多个参数相乘:

>>> def mul(*args):
    multi = 1
    for i in args:
          multi *=i
    return multi
mul2,8

十六,

mul2,8,3 四十八


这太棒了,谢谢你。使用return肯定解决了我的问题。问题是,我是从Tony Gaddis的Python开始的,这本书还没有提到使用return来发送信息。我想有一种更复杂的方法可以做到这一点?你可以使用globals,但我不敢相信它没有提到函数的返回值。这是编程最基本的部分之一。哇,Python 1.5.1?我推荐。
>>> def mul(*args):
    multi = 1
    for i in args:
          multi *=i
    return multi