semry
semry

Reputation: 1

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. 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)

Upvotes: 0

Views: 786

Answers (3)

LombardiD
LombardiD

Reputation: 340

depends on where you're writing the code, it may be 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. 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. The pricePerGallon is optional and defaults to 3.45. You can then call the function like this:

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

Upvotes: 2

Liju
Liju

Reputation: 2303

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

Upvotes: 0

stilManiac
stilManiac

Reputation: 464

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)

Upvotes: 1

Related Questions