69.4k views
0 votes
Write a function called farecalc that computes the bus fare one must pay in Lawrence Transit based on the distance travelled. Here is how the fare is calculated: the first mile is $3. Each additional mile up to a total trip distance of 10 miles is 25 cents per mile. Each additional mile over 10 miles is 10 cents per mile. Miles are rounded to the nearest integer other than the first mile which must be paid in full once a journey begins. The input to the function would be the distance of the journey. Return the fare in dollars

User Tomassilny
by
6.3k points

2 Answers

3 votes

Answer:

#SECTION 1

#Define the function

def farecalc(distance_of_journey):

#declare all constants

distTraveled = int(distance_of_journey)

firstmile = 3#dolars

lessThan10miles = 0.25#dollars

greaterThan10miles = 0.10#dollars

fare = 0

#SECTION 2

#for every distance greater than 1 mile the while loop will execute

while distTraveled > 1:

if distTraveled <= 10:

fare = fare + lessThan10miles

distTraveled = distTraveled - 1

else:

fare = fare + 0.10

distTraveled = distTraveled - 1

#SECTION 3

round(fare)

fare = fare + firstmile

return fare

print('Your fare is $',farecalc(1),)

Step-by-step explanation:

#SECTION 1:

The functions is defined and it receives an argument which is the distance that is traveled. All the constants that will be used to calculate this distance are also defined.

#SECTION 2:

This is where the calculation takes place, The while loop ensures that every distance greater than 1 mile will be calculated because the first mile has a constant price of 3 dollars.

In your question, you specified the fare should be returned in dollars therefore, 25 cents = 0.25 dollars and 10 cents = 0.1 dollars.

"Each additional mile up to a total trip distance of 10 miles is 25 cents per mile"

the statement above is is handled by the if statement, it executes the if block for all distances less than or equal to 10.

" Each additional mile over 10 miles is 10 cents per mile"

the statement above is is handled by the else block, it executes when the distance traveled is greater than 10.

#SECTION 3 :

  • The fare is rounded up to its nearest integer
  • The first mile (3 dollars) is added to the existing fare
  • The fare final value is returned i.e when the function is called it will return the value of the fare as the answer.
  • The function is then called to test the code
Write a function called farecalc that computes the bus fare one must pay in Lawrence-example-1
User Cuonglm
by
7.7k points
4 votes

Answer:

Step-by-step explanation:

Let's do this in python. The quickest way to do this is by separating to different cases of distance ranges:

farecalc(distance):

distance = round(distance, 0) # round the distance to the nearest integer

if distance <= 1:

return 3

elif distance <= 10:

return 3 + (distance - 1)*0.25

else:

return 3 + 9*0.25 + (distance - 10)*0.1

User Metablocks Corp
by
6.8k points