def driving_cost(miles_per_gallon, dollars_per_gallon):
for i in range(len(driven_miles)):
cost = driven_miles / miles_per_gallon * dollars_per_gallon
return cost
if __name__ == '__main__':
driven_miles = [10, 50, 400]
miles_per_gallon = float(input())
dollars_per_gallon = float(input())
print(driving_cost(miles_per_gallon, dollars_per_gallon))
Above is code I have for this Question to write a program with a car's miles/gallon and gas dollars/gallon (both floats) as input, and output the gas cost for 10 miles, 50 miles, and 400 miles.
I understand there is a way to just print them out individually, but i believe there should be a for loop to do this, so even if you enter more driven_miles, it will iterate from the for loop,
could anyone help me? thank you!
CodePudding user response:
As it stands now, cost is a single value. You could initialize cost as an empty list, and append each individual cost to it, returning it at the end
def driving_cost(driven_miles, miles_per_gallon, dollars_per_gallon):
cost = []
for miles in driven_miles:
cost.append((miles / miles_per_gallon) * dollars_per_gallon)
return cost
CodePudding user response:
You have a very nice helper. Its signature is
def driving_cost(miles_per_gallon, dollars_per_gallon):
You want to embellish its signature so a 3rd arg is tacked on:
def driving_cost(miles_per_gallon, dollars_per_gallon, driven_miles):
That, or define the list down within the helper.
Iterating over indexes is certainly possible,
as your for i in range(len(driven_miles)):
loop currently does.
It would require a de-reference, such as driven_miles[i]
.
But it is more natural to ignore indexes and just iterate through the elements:
for dm in driven_miles:
Currently you loop over three values to compute three costs,
and you overwrite cost
each time.
So the 3rd cost value winds up being returned.
Consider moving the print
down within that loop.
Or restructure the code so the helper returns a single cost
and the looping / print responsibilities are up in the main function.