0

I've been working on a problem, and I'm not sure style/function wise which is generally considered best practice.

I have a function that serves multiple checks on the same string, and returns a value based on that string. Is it better style or function to use stacked if-statements or if-elif-else statements?

Example:

def f(s):
    if s == 'Hey':
        return 'Sup.'
    if s == "How's it going?"
        return 'Not bad.'
    return 'I have no idea what you said.'

or

def f(s):
    if s == 'Hey':
        return 'Sup.'
    elif s == "How's it going?"
        return 'Not bad.'
    else
        return 'I have no idea what you said.'
Mike
  • 6,813
  • 4
  • 29
  • 50
user2004245
  • 399
  • 1
  • 6
  • 16
  • 1
    `if/elif/else` implies `XOR` behavior, in other words, exactly one case should be `True`. Having stacked `if` statements suggests that multiple cases may be executed (even though in your example they won't). – Cory Kramer Sep 24 '14 at 13:54

2 Answers2

5

In this case, it is a style choice and I would use the second construction. This is because it most closely represents what I would view as better style if you didn't have return statements within each block. The premise here is that you want exactly one condition to be satisfied and exactly one block to be executed. Therefore, use the second construction that makes this explicit. The first construction (without return statements) leaves open the possibility that multiple conditions could be satisfied.

Micah Smith
  • 4,203
  • 22
  • 28
2

For your case this doesn't matter as the function will anyway return after a true condition, for non returning conditionals it is always advisable to write else..if structures as the program wont have to evaluate unnecessary conditions that way.

nilobarp
  • 3,806
  • 2
  • 29
  • 37