Python - Same if statement multiple times in one code block

Why not just reverse the order of if statements?

def say_hi(english: bool, name: str) -> str:
    if english:
        if name != "":
                greeting = f"Hi, {name}!"
        else:
                greeting = "Hey there!"
        greeting = greeting + "foo bar"
    else:
        greeting = "I speak only English, sorry."
    return greeting

You could do something like this:

def say_hi(english: bool, name: str) -> str:
    if not english:
        greeting = "I speak only English, sorry."
    else:
        greeting = (f"Hi, {name}!" if name else "Hey there!") + "foo bar"
    return greeting

  • Failing fast. i.e Put the code that fails fast at the top.
  • boolen variables should start with "is" where possible
# Without Foo bar
def say_hi_2(is_english_speaker: bool, name: str):
    if not is_english_speaker:
        return "I speak only English, sorry."

    if not name:
        return "Hey There"

    return f"Hi, {name}"

# With foo bar
def say_hi(is_english_speaker: bool, name: str):
    if not is_english_speaker:
        return "I speak only English, sorry."

    greeting_template = "{} foo bar"
    if not name:
        return greeting_template.format("Hey There")

    return greeting_template.format(f"Hi, {name}")