Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

reduce the a if-elif-else code in a function

I was writing a code using python. I am using if-elif-else condition. The code is not looking good. Is there any other way to write the code?

def my_fun(x):
    if x<=200:
        x=0.2
    elif 201<=x<=300:
        x=0.3
    elif 301<=x<=400:
        x=0.4
    elif 401<=x<=500:
        x=0.5  
    elif 501<=x<=600:
        x=0.6
    elif 601<=x<=700:
        x=0.7
    elif 701<=x<=800:
        x=0.8
    elif 801<=x<=900:
        x=0.9
    elif 900<=x<=1000:
        x=1
    else:
        x=1.5 
    return x
courier_invoice['x_weight_slab'] = courier_invoice['weight by company'].apply(my_fun)

Is there any other way to write this function?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

try this function which will calculate the value and return
it by rounding up to 1 decimal point

def func(x):
    if x <= 200:
        return .2;
    elif x <= 1000:
        return round(((x+99) // 100) * 0.1, 1);
    return 1;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading