Control Flow: The if, elif, else Statements

Calculate Fare

Consider the following public transportation fare table:

Type Distance ≤ 10 km Distance > 10 km Additional
Regular 0.5 0.3
Student 0.3 0.1
Teacher 0.4 0.2
Senior Citizens 0.3 0.2

Let's define a function that returns a price of travel to be used for refund, with respect to the given table. If the distance is less than 10 km the users will be charged according to the left column of the table and for any distance more than 10 km, additional charges will apply with respect to the right column for the excess distance traveled.

def calculateFare(distance, student, teacher, senior):    
    
    if(distance <= 10 and (student or senior)):
        return distance * 0.3    
    
    if(distance <= 10 and teacher):
        return distance * 0.4    
  
    if(distance <= 10):
        return distance * 0.5    
    
    if(distance > 10 and student):
       return calculateFare(10, student, teacher, senior) + (distance - 10) * 0.1    
    
    if(distance > 10 and (teacher or senior)):
       return calculateFare(10, student, teacher, senior) + (distance - 10) * 0.2       
  
    if(distance > 10):
       return calculateFare(10, student, teacher, senior) + (distance - 10) * 0.3
  

print (calculateFare(10, False, False, False))
print (calculateFare(10, False, False, True))
print (calculateFare(10, False, True, False))
print (calculateFare(10, False, True, True))
print()
print (calculateFare(10, True, False, False))
print (calculateFare(10, True, False, True))
print (calculateFare(10, True, True, False))
print (calculateFare(10, True, True, True))
print()
print (calculateFare(20, False, False, False))
print (calculateFare(20, False, False, True))
print (calculateFare(20, False, True, False))
print (calculateFare(20, False, True, True))
print()
print (calculateFare(20, True, False, False))
print (calculateFare(20, True, False, True))
print (calculateFare(20, True, True, False))
print (calculateFare(20, True, True, True))

Changing the order of conditional statements in the code may result in a different calculation, e.g. check the case for a senior teacher with the modified code below where the first two conditional controls are swapped:

def calculateFare(distance, student, teacher, senior):    

    if(distance <= 10 and teacher):
        return distance * 0.4    
      
    if(distance <= 10 and (student or senior)):
        return distance * 0.3    
  
    if(distance <= 10):
        return distance * 0.5    
    
    if(distance > 10 and student):
       return calculateFare(10, student, teacher, senior) + (distance - 10) * 0.1    
    
    if(distance > 10 and (teacher or senior)):
       return calculateFare(10, student, teacher, senior) + (distance - 10) * 0.2       
  
    if(distance > 10):
       return calculateFare(10, student, teacher, senior) + (distance - 10) * 0.3
  


print (calculateFare(10, False, True, True))