I didn't see this question already, and I'm curious to find out what's going on here. Please forgive me if it's been asked and answered already.
While taking a course on Udacity, the instructor quickly mentioned a line he used in the Python code that looked like this:
n = n and int(n)
He said that it's basically equivalent to:
if n:
n = int(n)
The statement works just as he described, but I'm curious about how it works, because I've never seen this kind of construction in Python before. Can anyone explain what it is about using and
in this casting assignment that makes it work this way?
Also, having never seen it before, I would have no idea that this statement is functioning the way it is, which makes me think that it may not be the most Pythonic way to write this code. Is this a widely known and accepted shortcut, or should I generally stick with the explicit if
statement when I need to do something like this?
Edit: Ok, initial question is a duplicate, and has been clearly answered elsewhere, and now here as well. Thanks to all for those answers. One final question I have: which way should I prefer in my code (aka which is more Pythonic)?