Consider this code:
def say_hi(english: bool, name: str) -> str:
if name != "":
if english:
greeting = f"Hi, {name}!"
else:
if english:
greeting = "Hey there!"
if english:
greeting = greeting + "foo bar"
if not english:
greeting = "I speak only English, sorry."
return greeting
What is the best way to optimize this code to not have 3 times the same if statmenet (if english:) in one block of code? Or, perhaps a different question – does this repetitive if statement code match Python PEP standards?
>Solution :
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