jeudi 31 mars 2016

More pythonic way for a conditional variable

This is what I am trying to do:

  1. Get few arguments
  2. Based on the arguments, form a string
  3. Return the string

However, for this, I could see 3 potential ways:

def form_statement(subject, verb, object):
    greetings = ""
    if subject in ("Paul", "Raj"):
        greetings = "mister"
    return "%s %s %s %s" % (subject, verb, object, greetings)

Second way of doing this is:

def form_statement(subject, verb, object):
    if subject in ("Paul", "Raj"):
        greetings = "mister"
    else:
        greetings = ""
    return "%s %s %s %s" % (subject, verb, object, greetings)

And third way is:

def form_statement(subject, verb, object):
    greetings = "mister" if subject in ("Paul", "Raj") else ""
    return "%s %s %s %s" % (subject, verb, object, greetings)

Is there any other better way to do something like this? Right now I am opting for the first way as the "processing" to get the greetings string is a function in itself and makes the line to go beyond 80 characters when third way is used.

Aucun commentaire:

Enregistrer un commentaire