在Python中传递参数

时间:2015-01-03 22:54:46

标签: python

我试图弄清楚如何在Python中传递参数以及为什么我的代码无效。为什么说这些论点没有定义?我需要每个函数中的参数能够彼此说话。我只能通过将变量放在定义的main函数中来解决这个问题,这不是我想要设计程序的方式。

#make computer program that takes amount of doughnuts that customer
#wants to order.
#second, multiply the number of doughnuts the customer wants to order
#by the price and the sales tax.
#next, print the price of the doughnut with the sales tax
DOUGHNUT=1.75
SALES_TAX=0.08625

def getNumDoughnuts(numDoughnuts):
    numDoughnuts= raw_input("How many donuts would you like to order?")
    return numDoughnuts

def calculateDoughnutPrice(numDoughnuts, doughnutPrice):
    doughnutPrice=DOUGHNUT*float(numDoughnuts)
    return doughnutPrice

def calculateSalesTax(doughnutPrice, priceWithTax):
    taxAmount= (doughnutPrice*(SALES_TAX))
    priceWithTax= taxAmount+doughnutPrice
    return priceWithTax

def displayPrice(priceWithTax):
    print(priceWithTax)

def main():
    getNumDoughnuts(numDougnuts)
    calculateDoughnutPrice(numDoughnuts, doughnutPrice)
    calculateSalesTax(doughnutPrice, priceWithTax)
    displayPrice(priceWithTax)

main()

1 个答案:

答案 0 :(得分:3)

main中,当您致电numDougnuts时,确实未定义getNumDoughnuts。 OTOH,后一个函数忽略它的参数并返回一个值main反过来忽略。等等 - 你需要区分参数和返回值!

因此,按照正确的顺序,您的程序将成为:

DOUGHNUT = 1.75
SALES_TAX = 0.08625

def getNumDoughnuts():
    numDoughnuts = raw_input("How many donuts would you like to order?")
    return numDoughnuts

def calculateDoughnutPrice(numDoughnuts):
    doughnutPrice = DOUGHNUT * float(numDoughnuts)
    return doughnutPrice

def calculateSalesTax(doughnutPrice):
    taxAmount = doughnutPrice*(SALES_TAX)
    priceWithTax = taxAmount + doughnutPrice
    return priceWithTax

def displayPrice(priceWithTax):
    print(priceWithTax)

def main():
    numDoughnuts = getNumDoughnuts()
    doughnutPrice = calculateDoughnutPrice(numDoughnuts)
    priceWithTax = calculateSalesTax(doughnutPrice)
    displayPrice(priceWithTax)

main()

查看参数和返回值之间的区别?参数是进入函数(它们的值必须在您调用该函数时定义)。返回值是函数的 out - 通常需要被函数的调用者绑定到变量或以其他方式使用。

此外,当然,您需要致电main,否则没有任何反应! - )