Home > database >  How to use lookup or hashmap instead of if else?
How to use lookup or hashmap instead of if else?

Time:11-25

if Profit<=10000:
    print('Profit Rating is 1')
elif 10001<=Profit<=20000:
    print('Profit Rating is 2')
elif 20001<=Profit<=30000:
    print('Profit Rating is 3')
elif 30001<=Profit<=40000:
    print('Profit Rating is 4')
elif 40001<=Profit<=50000:
    print('Profit Rating is 5')
elif 50001<=Profit<=60000:
    print('Profit Rating is 6')
elif 60001<=Profit<=70000:
    print('Profit Rating is 7')
elif 70001<=Profit<=80000:
    print('Profit Rating is 8')
elif 80001<=Profit<=90000:
    print('Profit Rating is 9')
else:
    print('Profit Rating is 10')

please help me removing above if else. I tried with lookup and mapping but it is not working.

I want to get rid of if, elif and else.

CodePudding user response:

Use simple maths:

import math

if Profit > 90000:
    profit_rating = 10
else:
    profit_rating = math.ceil(Profit / 10000)

print(f"Profit Rating is {profit_rating}")

It divides your number by 10,000, then rounds it up. That's basically what you are trying to do (manually) in your original if/else solution.

  • Related