Can this if else condition be replaced by any operator or can this be written using less code. If so then how?
if workingPeriod<3 and gender=="male":
return f"He is not experienced"
elif workingPeriod<3 and gender =="female":
return f"She is not experienced"
elif workingPeriod >=3 and gender =="male":
return f"He is experienced"
elif workingPeriod >=3 and gender =="female":
return f"She is experienced"
else:
pass
CodePudding user response:
You have two conditions (male or female and experienced or not). You are trying to resolve all combinations of conditions in the same block of if statements and therefore have 4 branches because there are 4 combinations.
Instead of 4 branches you can simplify to resolving each condition separately. That way you reduce the complexity and the lines of code.
prefix = "He" if gender == "male" else "She"
return prefix (" is experienced" if workingPeriod > 3 else " is not experienced")
CodePudding user response:
Assuming you have no other genders than 'male'
or 'female'
(and don't want to return None
if that isn't the case):
return f'{"He" if gender=="male" else "She"} is {"not " if workingPeriod<3 else ""}experienced'
In case you do have more genders (i.e. the pass
case`):
return f'{"He" if gender=="male" else "She" if gender=="female" else "They"} is {"not " if workingPeriod<3 else ""}experienced'