I’m taking Web Application Engineering course on Udacity. I noticed that the instructor use and operator in return statement in his validation method. And I didn’t understand how it is possible to return 2 arguments. I think, it may be something like if statement. Could anyone explain what it actually is?
Here is the validation method:
USER_RE = re.compile(r"^[a-zA-Z0-9_-]{3,20}$")
def valid_username(username):
return username and USER_RE.match(username)
Thanks in advance.
The
andoperator evaluates whether both of its arguments are tru-ish, but in a slightly surprising way: First it examines its left argument. If it is truish, then it returns its right argument. If the left argument is falsish, then it returns the left argument.So the last line in your code:
is the same as:
Strings like
usernameare truish if they are not empty. The regexmatchfunction returns a truish match object if the pattern matches, and returnsNone, a falsish value, if it doesn’t match.The net result is that
valid_usernamewill return a truish value if username is not an empty string, and the username matches the given pattern.Note the “and” here has nothing to do with returning two values, it’s computing one value.