在Python中传递参数

2024-09-29 23:23:54 发布

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

我试图弄清楚如何在Python中传递参数,以及为什么我的代码不能工作。为什么说论点没有定义?我需要每个函数中的参数,以便能够相互对话。我只能通过将变量放入已定义的主函数中来解决这个问题,这不是我想要设计程序的方式。你知道吗

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

Tags: oftheto函数参数returnthat定义
1条回答
网友
1楼 · 发布于 2024-09-29 23:23:54

main中,调用getNumDoughnuts时确实没有定义numDougnuts。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()

看到参数和返回值之间的区别了吗?参数是将带入函数的内容(它们的值必须在调用该函数时定义)。返回值是从函数中得到的,通常需要绑定到变量,或者由函数的调用者使用。你知道吗

当然,您还需要调用main,否则什么都不会发生!-)你知道吗

相关问题 更多 >

    热门问题