1

Right now my python code looks like this:

if imput == "con":
    print "%.6f" % (con_getinfo["balance"])
elif imput == "xra":
    print "%.6f" % (xra_getinfo["balance"])
elif imput == "neg":
    print "%.6f" % (neg_getinfo["balance"])
elif imput == "grf":
    print "%.6f" % (grf_getinfo["balance"])
elif imput == "ninja":
    print "%.6f" % (ninja_getinfo["balance"])

Now i would like it to make it look less repetitive, like this:

if imput == con or imput == xra or imput == neg or imput == grf or imput == ninja:

But i can't figure out how to assign to each of the conditions the proper reaction.

Angel Lox
  • 45
  • 7

2 Answers2

4

You can store references to the functions in a dictionary, then it's just a simple lookup:

response = {
    "con": con_getinfo,
    "neg": neg_getinfo,
    ...
}
print "%.6f" % (response[imput]["balance"])
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
1

This is arguably a dupe, but in a nutshell... the pythonic way is to use a dictionary. There are probably better ways to refactor this, but to start:

mydict = {"con": con_getinfo,
          "xra": xra_getinfo,
          "neg": neg_getinfo,
          "grf": grf_getinfo,
          "ninja" : ninja_getinfo}

lookup = mydict.get(imput)
if lookup: #won't fail if imput isn't on of the options
    print "%.6f" % (lookup["balance"])
Foon
  • 6,148
  • 11
  • 40
  • 42