I'm trying to figure out how to get the result of mpg for these cars and have them rounded down to 2 decimal points.
cars = [
{"make": "Ford", "model": "Fiesta", "mileage": 23000, "fuel_consumed": 460},
{"make": "Ford", "model": "Focus", "mileage": 17000, "fuel_consumed": 350},
{"make": "Mazda", "model": "MX-5", "mileage": 49000, "fuel_consumed": 900},
{"make": "Mini", "model": "Cooper", "mileage": 31000, "fuel_consumed": 235},
]
def calculate_mpg(car):
mpg = car ["mileage"] / car["fuel_consumed"]
return mpg
def car_name(car):
name = f"{car['make']} {car['model']}"
return name
def print_car_info(car):
name = car_name(car)
mpg = calculate_mpg(car)
print(f"{name} does {mpg} miles per gallon.")
for car in cars:
print_car_info(car)
CodePudding user response:
You could also use something like
round(x, y)
with x
being the number you want to round and y
being the number of decimal places.
CodePudding user response:
Use numpy
np.round(mpg, 2) ## Rounds to two decimal places