Python : How to replace multiple if-elif-else with easy to write/read code

python @ Freshers.in

You can write the same logic in different ways. How smart you write the code explains how comfortable you in python. Your code should be easily understandable and easy to maintain. There are lot of programmers who write multiple if – elif for same sequence of code. In this article we will brief you an easy way to replace if-elif-else condition.

Normal if – elif – esle code

def displayGradePayAmount(level_number):
  if level_number   == "gp1":
    return 29200
  elif level_number == "gp2":
    return 30100
  elif level_number == "gp3":
    return 31000
  elif level_number == "gp4":
    return 31900
  elif level_number == "gp5":
    return 32900
  else:
    return 0

Enhanced version of the same logic with easy to maintain and understandable code 

We will be defining GradePay like a dict/json , and by passing the key , we can retrieve the value. In this way you can add multiple key-value pair. 

GradePay = {
    "gp1":29200,
    "gp2":30100,
    "gp3":31000,
    "gp4":31900,
    "gp5":32900,
}
def displayGradePayAmount(level_number):
  try:
    return GradePay[level_number]
  except Exception as e: 
    return 0

One great advantage of coding this method , is you can keep the GradePay to read from a data file. So that in future there is no need to update the actual code, you can update the data file to reflect the changes. So the maintenance of the code will be easy.

Get more post on Python, PySpark

Video Tutorial

Author: user

Leave a Reply