In: Computer Science
Driving costs - functions
Driving is expensive. 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.
Output each floating-point value with two digits after the
decimal point, which
can be achieved as follows:
print('{:.2f}'.format(your_value))
Ex: If the input is:
20.0
3.1599
the output is:
1.58
7.90
63.20
Your program must define and call the following driving_cost()
function.
Given input parameters driven_miles, miles_per_gallon, and
dollars_per_gallon,
the function returns the dollar cost to drive those miles.
Use the following .py file to get started:
#variables
miles_per_gallon = float(input("Please enter the miles per
gallon: "))
dollars_per_gallon = float(input("PLease enter the cost per gallon:
"))
#calculations
dollars_20_miles = 20 * (1.0 / miles_per_gallon) *
dollars_per_gallon
dollars_75_miles = 75 * (1.0 / miles_per_gallon) *
dollars_per_gallon
dollars_500_miles = 500 * (1.0 / miles_per_gallon) *
dollars_per_gallon
print('{:.2f} {:.2f} {:.2f}'.format(dollars_20_miles, dollars_75_miles. dollars_500_miles))
Program:
def
driving_cost(miles_per_gallon,dollars_per_gallon,driven_miles):
#calculations
#calculating cost for given driven_miles miles
return driven_miles * (1.0 / miles_per_gallon) *
dollars_per_gallon
#input variables
miles_per_gallon = float(input("Please enter the miles per gallon:
"))
dollars_per_gallon = float(input("PLease enter the cost per gallon:
"))
#calling driving_cost() function with 10 driven_miles
driven_miles=10
c1 =
driving_cost(miles_per_gallon,dollars_per_gallon,driven_miles)
print('{:.2f}'.format(c1))
#calling driving_cost() function with 50 driven_miles
driven_miles=50
c2=driving_cost(miles_per_gallon,dollars_per_gallon,driven_miles)
print('{:.2f}'.format(c2))
#calling driving_cost() function with 400 driven_miles
driven_miles=400
c3=driving_cost(miles_per_gallon,dollars_per_gallon,driven_miles)
print('{:.2f}'.format(c3))
output:
Another way to get solution:
PROGRAM:
def driving_cost(miles_per_gallon,dollars_per_gallon):
#calculations
dollars_10_miles = 10 * (1.0 / miles_per_gallon) *
dollars_per_gallon
dollars_50_miles = 50 * (1.0 / miles_per_gallon) *
dollars_per_gallon
dollars_400_miles = 400 * (1.0 / miles_per_gallon) *
dollars_per_gallon
print('{:.2f}\n{:.2f}\n{:.2f}'.format(dollars_10_miles,
dollars_50_miles, dollars_400_miles))
#input variables
miles_per_gallon = float(input("Please enter the miles per gallon:
"))
dollars_per_gallon = float(input("PLease enter the cost per gallon:
"))
#calling driving_cost() function with arguments
driving_cost(miles_per_gallon,dollars_per_gallon)
OUTPUT: