J.jaques J.jaques - 2 months ago 8
Python Question

Find a more efficient way to code an If statement in python

it's the second time I'm confronted to this kind of code :

if "associé" in gender or "gérant" in gender or "président" in gender or "directeur" in gender:
gen = "male"
elif "associée" in gender or "gérante" in gender or "présidente" in gender or "directrice" in gender:
gen = "female"
else:
gen = "error"


I'd like to find a more efficient way to write this code because it looks really bad.

Answer

Using lists and any:

males = ["associé", "gérant", "président", "directeur"]
females = ["associée", "gérante", "présidente", "directrice"]

if any(m in gender for m in males):
    gen = "male"
elif any(m in gender for m in females):
    gen = "female"
else:
    gen = "Error"
Comments