What happens if I nest if statements?

Hi guys/girls. I successful completed the exercise and then I tried to complete it using the ‘nest’ control flow suggested in the ‘question’ session at the and of the exercise.
I rewrote the ‘applicant_selector’ function this way:
nest%20attempt

The thing is, if I use an ‘elif’ statement (line 10) and I call the function, the output is ‘None’. If I replace the ‘elif’ statement with an ‘if’ statement the ouput is correct.
Why doesn’t the function work properly if I use an ‘elif’ statement? I don’t get it.
Thanks!

The if statement at line 8 has no else, so failing that condition results in the code pointer going to the end of the function, and returning None. The same can be said for line 12.

1 Like

Thanks for the hint. I changed the code in this way and it works:

def applicant_selector(gpa, ps_score, ec_count):
  if (gpa >= 3.0) and (ps_score >= 90):
      if (ec_count >= 3.0):
        return "This applicant should be accepted."
      elif not (ec_count >= 3.0):
        return "This applicant should be given an in-person interview."
  else:
  	return "This applicant should be rejected."
  

Nonetheless, I have to admit that I don’t entirely get it. Why the final else in my first block of code wasn’t enough to close my control flow? Shouldn’t else be optional in the in the ‘nest’ code?

1 Like

Each IF is its own block. When we nest them, we have blocks inside blocks. Each IF will need its own else to handle failed checks. The else of the if it is contained in will not be applied at that block level.

In you code above, the else only applies to the outer if.

There is no need for an elif in the code, just an inner else since that will be the default action of the inner if.

def applicant_selector(gpa, ps_score, ec_count):
  if (gpa >= 3.0) and (ps_score >= 90):
      if (ec_count >= 3.0):
        return "This applicant should be accepted."
      else:
        return "This applicant should be given an in-person interview."
  else:
  	return "This applicant should be rejected."
1 Like

Ok, you’ve been crystal-clear. Now I got it.
Thank you very much!

1 Like