A Boolean expression with multiple conditions can get quite long. How can we keep things concise?
Answer
If you have a long expression with multiple expressions combined with and and or, what you can do is “nest” other if/elif/else statements.
This can be helpful when you want to continue checking other conditions given that some previous condition is met. If the previous condition is not met, then it would not check any further into the nested statements.
Example
# if statement with nested if/else statement
if time == 8:
if weekend:
snooze()
else:
wakeup()
What sort of example would be helpful? The above given example if fairly concise and describes nesting very well. Do you have any specific scenario in mind?
For the review on control flow, this is how I kept things concise:
def applicant_selector(gpa, ps_score, ec_count):
if (gpa >= 3.0) and (ps_score >= 90):
if (ec_count >= 3):
return “This applicant should be accepted.”
else:
return “This applicant should be given an in-person interview.”
else:
return “This applicant should be rejected.”
However, we cannot see them to be noted in the post. It’s all left-justified. Seems there is some boilerplate literature given to new users of the forums that may have missed your attention. In it is described how to mark down code samples so they appear as we intend them to. Walking away from code samples that don’t look right is pure irresponsibility.
I’ve just started to learn how to code and finished this section but wanted to test out your code to see if it worked any better and it appears to be broken on my end? the code I entered for this module here:
def applicant_selector(gpa, ps_score, ec_count):
if gpa >= 3.0 and ps_score >= 90 and ec_count >= 3:
return "This applicant should be accepted."
# printed if applicant meets all three criteria
elif gpa >= 3.0 and ps_score >= 90 and ec_count <= 2:
return "This applicant should be given an in-person interview."
else:
return "This applicant should be rejected."
print(applicant_selector(3.1, 91, 3))
print(applicant_selector(3.1, 91, 2))
print(applicant_selector(3.1, 89, 2))
When I imported your code I received a few errors and even after some trail and error they didnt work for me, but I liked what you did and modified my code to the following
def applicant_selector2(gpa, ps_score, ec_count):
if gpa >= 3.0 and ps_score >= 90:
if ec_count >= 3:
return "This applicant should be accepted."
# printed if applicant meets all three criteria
elif ec_count <= 2:
return "This applicant should be given an in-person interview."
else:
return "This applicant should be rejected."
print(applicant_selector(3.1, 91, 3))
print(applicant_selector(3.1, 91, 2))
print(applicant_selector(3.1, 89, 2))
Instead of two ‘else’ statements, i used ‘elif’ and ‘else’. This definitely saves on re-writing lines, thanks!
Edit: I played around with it a little more and finally figured out how the lines should be indented.
Now you’re cooking with gas. Only thing I would suggest is using proper names as the keys. Users will be prone to input the capitalized name, as per proper grammar.
Python dict objects have a built-in method for querying entries by key. This helps us to prevent KeyError.
weight *= table.get(planet, 0)
return weight or "Invalid entry"
Notice the default value of zero if the key is not found? It will cause the return to be the error message.
Yes, Python does have a conditional expression that can be returned like the ternary expression above, as opposed to a conditional statement, but it is not a ternary.
return U if a else V if b else W if c else "Z"
where a, b and c are conditions, and U, V and W are return values.
Edited 5 November 2022 by mtf to correct syntax error
Hi. Your conditional expression example sounds like it would or at least should, work. However, after testing it with some code I keep getting a syntax error. I’m not sure what’s going on here. If you have any suggestions or if there is something I’m doing wrong, could you please point it out? Thank you.
Best regards, Juan
condition1 = False
condition2 = True
condition3 = False
def example():
return "Value1" if condition1 else "Value2" if condition2 else "Value3" if condition3
print(example())
I can relate. My example wasn’t as refined as I would have liked, either, because after writing it, I was looking for an answer on a similar forum and I missed it. Without your comment, I wouldn’t have been introduced to this syntax, at least not anytime soon. Thank you.
Yes, excessive nesting of if-then conditions can be problematic for a few reasons:
Readability: Deeply nested conditions can make code difficult to read and understand. When conditions are nested multiple levels deep, it becomes harder to follow the logic and see how different conditions interact.
Maintainability: Highly nested code can be more challenging to maintain and modify. Changes to one part of the nested conditions might have unintended effects on other parts of the code, increasing the risk of introducing bugs.
Complexity: Nested conditions can lead to complex logic that is difficult to debug. The more levels of nesting there are, the more complex the logic becomes, which can make it harder to trace the flow of execution.
To address these issues, consider the following practices:
Refactoring: Break down complex nested conditions into smaller, more manageable functions. Each function can handle a specific part of the logic, making the overall code easier to read and maintain.
Early Returns: Use early returns to handle special cases or errors before proceeding with the main logic. This can reduce the need for nested conditions by handling exceptional cases up front.
Switch Statements: For certain scenarios, switch statements can be more readable and maintainable than multiple if-then conditions.