Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python – Same if statement multiple times in one code block

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading