Normality - 10 days ago 4x
Python Question

# Creating a function for Road Pricing

The Transport Authority is implementing a new Road Pricing system. The authorities decided that the cars will be charged based on distance travelled, on a per mile basis. A car will be charged \$0.50/mi, a van \$2.1/mi and taxis travel for free. Create a function to determine how much a particular vehicle would be charged based on a particular distance. The function should take as input the type of the car and the distance travelled, and return the charged price.

The problem above is what I have to do and the code below is what I have so far. The issue I have is that I'm receiving an error for not identifying car, van, and taxi before. But if I do so, it would print out all 3 situations. How would I be able to print out 1 outcome depending on the input for y?

``````    def Road_Pricing():
x = float(input("How many miles is driven?"))
y = (input("What car was driven?"))
if "car":
print (.50*x)
if "van":
print (2.1*x)
if "taxi":
print ("Free")
Road_Pricing()
``````

Answer

The requirement is(emphasis mine):

...... The function should take as input the type of the car and the distance travelled, and return the charged price.

This means:

1. The function should take two parameters: one for the type of the car and one for the distance travelled.
2. You must return the price(which I suspect is a floating point number), rather than simply printing it.

Another problem in your code is that expressions in your statements isn't checking the value of `car_type`. Also, you should use more meaningful variable names(for example, `distance` and `car_type` instead of `x` and `y`).

``````def road_pricing(car_type, distance):
if car_type == "car":
return .50 * distance
if car_type == "van":
return 2.1 * distance
if car_type == "taxi":
return 0

car_type = raw_input("What car was driven? ")
distance = float(input("How many miles is driven? "))
print road_pricing(car_type, distance)
``````
Source (Stackoverflow)
Comments