Trimax Trimax - 6 months ago 10
Python Question

Selecting range limits of a scale in Python

I want to apply a fee to an amount according with this scale:

AMOUNT FEE
------- ---
0 24.04 €
6010.12 0.00450
30050.61 0.00150
60101.21 0.00100
150253.03 0.00050
601012.11 0.00030


From 0 to 6010.13€ is a fix fee of 24.04€

My code:

def fee(amount):
scale = [[0, 24.04],
[6010.12, 0.00450],
[30050.61, 0.00150],
[60101.21, 0.00100],
[150253.03, 0.00050],
[601012.11, 0.00030]]
if amount <= scale[1][0]:
fee = scale[0][1]
else:
for i in range(0, 5):
if amount >= scale[i][0] and amount < scale[i+1][0]:
fee = amount * scale[i][1]
break
return fee

print(fee(601012.12))


This code works fine from 0€ to 601012.11€, but for 601012.12€ or greater fails.


return fee UnboundLocalError: local variable 'fee' referenced before assignment



I suppose that the problem is here:
amount < scale[i+1][0]
when i=4 the
fee
variable isn't assigned.

Are there any methods more pythonic to select range limits of a scale?

Answer

I think a better way would be to use a while loop to check if amount is lesser then scale[i+1][0] so that you may just use scale[i][1]. And also give an else to handle anything greater than scale[len(scale)][0].

Comments