'Decreasing the code by many successive "elif"
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.
Solution 1:[1]
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"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | gerda die gandalfziege |
