samedi 7 novembre 2020

Reducing the use of if's / elif

I'm not a really experienced python user, so, to learn better, I'm doing a program of my own with some utility for my job ("quality inspector"). So, in my job, I deal with a lot of tolerances, usually, when I need to know, I have to read a document we have.

While that's ok, I lose a lot of time doing that, so I had the idea, to use what I have learned till now in python to make a small program in the interpreter to simplify that use.

Firstly, last month, I made it functional, with 1120 lines of code, a lot of elifs, a lot of repetitions, etc etc. I simplified it last week using some functions to 711 lines. Now, im trying to simplify it more, doing modularization and reducing if's/elifs. This is a example of my code:

cod =
    ['menu'],
    ['dimension 1"'],
    ['dimension 2”'],
    ['dimension 3”'],
    ['dimension 4'],
    ['dimension 5'],
    ['dimension 6'],
    ['dimension 7'],
    ['dimension 8'],
    ['dimension 9'],
    ['dimension 10']
]
return cod

    if choice == 1:
    quantify = float(input(('Quantify: ')))
    if 0 < quantify <= 6:
        print('± 0,1mm')
    elif 6 < quantify <= 30:
        print('± 0,2mm')
    elif 30 < quantify <= 120:
        print('± 0,3mm')
    elif 120 < quantify <= 400:
        print('± 0,5mm')
    elif 400 < quantify <= 1000:
        print('± 0,8mm')
    elif 1000 < quantify <= 2000:
        print('± 1,2mm')
    elif 2000 < quantify <= 4000:
        print('± 2mm')
    else:
        print('<<< Min = 0,5mm | Max = 4000mm >>>')
elif choice == 2:
    quantify = float(input(('Quantify: ')))
    if 0 < quantify <= 3:
        print('± 0,2mm')
    elif 3 < quantify <= 6:
        print('± 0,5mm')
    elif 6 < quantify:
        print('± 1mm')
    else:
        print('<<< Min = 0,5mm | Max = ∞ >>>')

*I had to change somethings to make it readable to you, cause, as I said, I'm using other functions, and it's in Portuguese.

I already tried dictionaries and lists, and couldn't make it. There is a lot of code like this in my program.

Any idea to simplify this code and reuse it on a function to don't repeat it again?

Thanks, soldcarvalho

Aucun commentaire:

Enregistrer un commentaire