Python Practice › Loop Programs › Program 49
Taxi bill by distance
Write a Python program to calculate a bill: first 5 km at Rs 15/km, next 20 km at Rs 12/km, after that Rs 10/km.
Input
3 km, 18 km, 40 km
Output
3 km -> 45 18 km -> 231 40 km -> 465
Approach
- Charge each kilometre at the rate of the slab it falls in.
Solution
def fare(km): total = 0 for k in range(1, km + 1): if k <= 5: total += 15 elif k <= 25: total += 12 else: total += 10 return total for km in [3, 18, 40]: print(km, "km ->", fare(km))Output
3 km -> 45 18 km -> 231 40 km -> 465
Line by line
Lines 3-9
The loop visits every kilometre and adds the rate for its position, which handles the slabs naturally.
Note
40 km = 5 × 15 + 20 × 12 + 15 × 10 = 465.
Learn the concept
New to this topic? Read the lesson, then come back.