Python control flow - Boolean Operators: and - parenthesis reasoning?

Working on task 7 of Python Control Flow “Boolean Operators: and”

My code below worked and printed the correct statement:

def graduation_reqs(gpa, credits):
if gpa >= 2.0 and credits >= 120:
return “You have enough credits to graduate!”
print(graduation_reqs(2.0, 120))

However it was marked as incorrect. I ran the solution and got this given code:

def graduation_reqs(gpa, credits):
if (gpa >= 2.0) and (credits >= 120):
return “You meet the requirements to graduate!”

The only difference being the parentheses. I know that using parentheses will change the operator priority, but in this example I can’t see a reason why the parentheses would be necessary. Am I misunderstanding something?

The major difference I can see is that return string. As for the code itself operator precedence would result in the expressions evaluating to the same value. It’s a bit harder to see since this code is only partially formatted and without indentation and such, see this FAQ for more details.

Could you format the code and provide a link to the lesson itself?

1 Like

Sorry - had the link to the lesson all ready to go in my clipboard but failed to include. Here it is.

And formatted code:

def graduation_reqs(gpa, credits):
  if gpa >= 2.0 and credits >= 120:
    return "You have enough credits to graduate!"

def graduation_reqs(gpa, credits):
  if (gpa >= 2.0) and (credits >= 120):
    return "You meet the requirements to graduate!"

I think you might have spotted the problem though. I hadn’t spotted the change in return text. Have gone back and run the exercise with the correct return text and no parentheses and it works. Also noted the task was to print “None” using print(graduation_reqs(0.0, 120)). Doubling up on my missed mistakes.

Thank you - going back over the code has allowed me to spot these errors.

Still not sure why the given solution includes parenthesis though. Is writing it like this, even when there’s no priority to be made, best practice?

Ah, that makes more sense. Some of the lessons are a little strict when it comes to returning values and printing outputs but being exact is a good habit to get into as small errors can snowball on you.

I would assume they’re included here purely for readability. If you glanced at this quickly would you find it easier to determine what’s happening with or without parantheses? It’s a litte bit opinion based. For this one I quite like their inclusion as it saves me a little bit of effort when scanning the code but I’ve seen nightmare experssions with more than could ever be necessary which serve only to confuse the situation. Making the code as clear as possible is another good habit to get into but as for including them or not will probably be best to consider on a case by case basis, either side of a conditional like and is quite common though.