1

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)?

coralvanda
  • 6,431
  • 2
  • 15
  • 25
  • wouldn't that even be equivalent to `n = int(n)`? the boolean value of most types (which don't implement `__nonzero__` to be `True` even when `int(type)==0`) is `int(type)!=0`! – Marcus Müller Jun 05 '16 at 12:57

2 Answers2

1

condition1 and condition2.

condition2 is executed only if the condition1 passes. If n resolves to a True in Boolean context then n is converted to int by the statement int(n) and assigned to n

In context of Boolean operations the following are considered as false - False, None, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets)

From doc

gaganso
  • 2,914
  • 2
  • 26
  • 43
1

This is caused by python's lazy evaluation (or more accurately, short-circuit boolean expressions), see: https://docs.python.org/2/reference/expressions.html#boolean-operations :

The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.

Also see the answer to: Does Python evaluate if's conditions lazily?

Community
  • 1
  • 1
Ofir
  • 8,194
  • 2
  • 29
  • 44