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

Question:

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?

Asked By: Unicorn

||

Answers:

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.5;
Answered By: Nikhil

Try a simple mathematical logical function:

def my_fun(x):
    if 900 < x <= 1000:
        return 0.1
    elif x <= 200:
        return 0.2
    return min(((x // 100) / 10) + (x % 100 != 0 and 0.1), 1)
Answered By: ahmadjanan

Try this

import math
def my_fun(x):
    x = -x
    if x >= -200:
        return 0.2
    elif x >= -1000:
        return -math.floor(x/100)/10
    return 1.5
Answered By: codester_09
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.