Home > Enterprise >  Decreasing the code by many successive "elif"
Decreasing the code by many successive "elif"

Time:01-25

How can I decrease lines of code when I enter a number in text format and I need to assign a code consecutively to that number?

Attached is an example:

def plataformaVSTP(id):
    codigoFalla = "N/A"
    if id == "70000":
        codigoFalla = "VSTP020"
    elif id == "70002":
        codigoFalla = "VSTP021"
    elif id == "70005":
        codigoFalla = "VSTP022"
    elif id == "70007":
        codigoFalla = "VSTP023"
    elif id == "70008":
        codigoFalla = "VSTP024"
    elif id == "70010":
        codigoFalla = "VSTP025"
    elif id == "70011":
        codigoFalla = "VSTP026"
    elif id == "70015":
        codigoFalla = "VSTP027"
    elif id == "70020":
        codigoFalla = "VSTP028"
    elif id == "70031":
        codigoFalla = "VSTP029"
    elif id == "70050":
        codigoFalla = "VSTP030"
    elif id == "70457":
        codigoFalla = "VSTP031"
    elif id == "70505":
        codigoFalla = "VSTP032"

and so on...

I currently have more than 450 elif, of how the code is displayed.

I don't know if the above slows down the execution of my script.

CodePudding user response:

The use of a dictionary would great improve the writeability and readability of the code. This you would implement such dictionary.

dictionary = {"70000":"VSTP020","70002":"VSTP021"..... and so on}

the check what value the variable codigoFalla

should get use this code:

codigoFalla = dictionary["70000"] # sets the value of codigoFalla to the value corresponding to the key "70000"

CodePudding user response:

def plataformaVSTP(id_):
    default = "N/A"
    codigoFalla = {
        "70000": "VSTP020",
        "70002": "VSTP021",
        "70005": "VSTP022",
        "70007": "VSTP023",
        "70008": "VSTP024",
        "70010": "VSTP025",
        "70011": "VSTP026",
        "70015": "VSTP027",
        "70020": "VSTP028",
        "70031": "VSTP029",
        "70050": "VSTP030",
        "70457": "VSTP031",
        "70505": "VSTP032",
    }
    return codigoFalla.get(id_, default)
  •  Tags:  
  • Related