A Boolean expression with multiple conditions can get quite long. How to keep things concise?

Question

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()
14 Likes

Can someone help giving other examples to his question?

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?

3 Likes

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.”

Make sure you pay close attention to the indents.

3 Likes

Welcome, @eliselehman528451969,

What indents should we be noticing?

Are we going to be able to find this exact example in the forums?

People should note the indents because there are a lot of them. (Ifs
embedded in ifs, and embedded within the function.)

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.

This is my first post in Codecademy and I am new. I didn’t know.

It would be a good idea to go over the material in the new user section. There is advice on how to post code samples in the forums.

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.


def
  if  
    if 
      return 
    else 
      return 
  else 
    return 

is how it should be.

1 Like

I actually tried to use dictionary to store the table, and it can avoid using if/else.

table = {

“venus”: 0.91,

“mars”: 0.38,

“jupiter”: 2.34,

“saturn”: 1.06,

“uranus”: 0.92,

“neptune”: 1.19

}

planet = ‘jupiter’

weight *= table[planet]

1 Like

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.

2 Likes

Yes, does Python have something similar to Javascript, where there is a conditional chain syntax that can be used?

Per this JS syntax example from MDN:

function example(…) {
    return condition1 ? value1
         : condition2 ? value2
         : condition3 ? value3
         : value4;
}

// Equivalent to:

function example(…) {
    if (condition1) { return value1; }
    else if (condition2) { return value2; }
    else if (condition3) { return value3; }
    else { return value4; }
}
1 Like

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

2 Likes

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())
1 Like

SyntaxError: expected 'else' after 'if' expression

def test(a=0, b=0, c=0):
    U, V, W = 'U', 'V', 'W'
    return U if a else V if b else W if c else 'Z'

test()
'Z'

Thanks for pointing this out. Seems the example was not tested but just thrown out there. My bad. Going to fix it, presently.

1 Like

Dear mtf,

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.

Kind regards, Juan

1 Like

what would this look like if it wasn’t nested?

I have heard from other programmers that nesting if-then conditional code can be poor practice if overused. Is that the case, why or why not?

Yes, excessive nesting of if-then conditions can be problematic for a few reasons:

  1. 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.
  2. 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.
  3. 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.
1 Like