using logic in a return statement

I just ran into this in lesson 13 problem set 4 of cs253 where he has an interesting way of combining some logic into a return statement.

What it does is if the variable and the function are true, return the variable. if either is False or None, return False or None.

# return_bool_andFunc

def myFunc():
return "wine"

def myFunc2():
return "dine"

variable = True

def return_func():
return myFunc2() and variable and myFunc()

print (return_func())
>>> wine

  • if all elements are true, return the last thing
  • if any elements are false or None , return False or None
  • in python, strings are evaluated as True, so it basically checks for “is string not None”

In the video Steve uses this as a way to call a function that validates a cookie (called “check_secure_val(cookie)”). If check_secure_val(cookie) returns true, then the return loop returns the actual cookie value (as opposed to the boolean returned by the function)

I’m still unsure as to why he didn’t return the actual value from check_secure_val() (or None if the test fails) and the run that function in the return line. It may have to do with code reusability, or where he wants that functionality. I’ve been blown away by how many classes and methods he has made in this project. My mind has been moving closer to oop, but it still hangs on to the idea of putting everything in one method (or even class)

Tell me what you think.

This site uses Akismet to reduce spam. Learn how your comment data is processed.