简体   繁体   English

我如何解决这个功能?

[英]How to I solve this function?

This is the assignment ive been given and im having trouble making it work properly.这是我被赋予的任务,我无法使其正常工作。 But it says that im having an error in the last line at "print(total)" - but im not sure what is wrong here.但它说我在“print(total)”的最后一行有错误 - 但我不确定这里有什么问题。 Does someone know the answer to this ?有人知道这个问题的答案吗?

Change the code below to create a function that calculates the cost of a trip.更改下面的代码以创建一个计算旅行成本的函数。 It should take the miles, milesPerGallon, and pricePerGallon as parameters and should return the cost of the trip.它应该将里程、英里每加仑和价格每加仑作为参数,并返回行程成本。

miles = 500
milesPerGallon = 26
numGallons = miles / milesPerGallon
pricePerGallon = 3.45
total = numGallons * pricePerGallon
print(total)  

The code ive come to so far is this :我到目前为止的代码是这样的:

def costOfTrip(miles,milesPerGallon,pricePerGallon):
    miles = 500
    milesPerGallon = 26
    numGallons = miles / milesPerGallon
    pricePerGallon = 3.45
    total = numGallons * pricePerGallon
    print(total)

depends on where you're writing the code, it may be print total .取决于您编写代码的位置,它可能是print total But just swap out the print for a return, so it would be lie:但只要换掉打印出来的回报,那就是谎言:

return total

Also, you're always assigning 500 to miles, 26 to imlesPerGallon and 3.45 to pricePerGallon.此外,您总是将 500 分配给英里,26 分配给 imlesPerGallon,3.45 分配给 pricePerGallon。 Try this out:试试这个:

def costOfTrip(miles,milesPerGallon,pricePerGallon=3.45):
    numGallons = miles / milesPerGallon
    total = numGallons * pricePerGallon
    return total

This means that you have to pass in the miles , milesPerGallon and the pricePerGallon parameters.这意味着您必须传入milesmilesPerGallonpricePerGallon参数。 The pricePerGallon is optional and defaults to 3.45 . pricePerGallon是可选的,默认为3.45 You can then call the function like this:然后,您可以像这样调用该函数:

total = costOfTrip(500,26)
print(total)

I think it should look like:我认为它应该是这样的:

def costOfTrip(miles, milesPerGallon, pricePerGallon):
    # miles, milesPerGallon and pricePerGallon are received args 
    numGallons = miles / milesPerGallon
    total = numGallons * pricePerGallon
    return total

Usage example使用示例

cost = costOfTrip(500, 26, 3.45)
print(cost)

You have to pass the values as arguments to function to get the values calculated and returned.您必须将值作为参数传递给函数以获取计算和返回的值。 you can refer below code.你可以参考下面的代码。

def costOfTrip(miles,milesPerGallon,pricePerGallon):
    numGallons = miles / milesPerGallon
    total = numGallons * pricePerGallon
    return total

miles = 500
milesPerGallon = 26
pricePerGallon = 3.45

print(costOfTrip(miles,milesPerGallon,pricePerGallon))

Output输出

66.34615384615385

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM