0

Looking at the first answer in the link: convert number words to Integers Python Code

The author uses

for idx, word in enumerate(scales):
   numwords[word] = (10 ** (idx * 3 or 2), 0)

How has the author used 'or' with multiply (*) here:

10 ** (idx * 3 or 2)
  • `X or Y` means `if X then X, otherwise Y`. So if `idx*3` is zero, `idx*3 or 2` is 2. Otherwise, it's `idx*3`. – khelwood Aug 25 '17 at 19:33
  • @khelwood there is definitely a duplicate which explains this all in detail – juanpa.arrivillaga Aug 25 '17 at 19:34
  • @juanpa.arrivillaga Then by all means find it. – khelwood Aug 25 '17 at 19:34
  • wouldn't you want to put this into parentheses to make it more obvious? Or will `((idx*3) or 2)` not work? – patrick Aug 25 '17 at 19:35
  • @khelwood Hi! how did you figure out that the condition to be compared against is 0? Where does it say that? – Tejit Pabari Aug 25 '17 at 19:37
  • Possible duplicate of [Is False == 0 and True == 1 in Python an implementation detail or is it guaranteed by the language?](https://stackoverflow.com/questions/2764017/is-false-0-and-true-1-in-python-an-implementation-detail-or-is-it-guarante) – Davy M Aug 25 '17 at 19:37
  • @patrick I think it would be the same with or without parenthesis. cause its multiply that we are using – Tejit Pabari Aug 25 '17 at 19:38
  • 1
    @TejitPabari `or` tests the truthiness of the left argument. In the case of numbers, `0` is falsey and all other numbers are truthy. – Barmar Aug 25 '17 at 19:38
  • 1
    @TejitPabari In Python, `0` is falsey, and all other numbers are truthy. – khelwood Aug 25 '17 at 19:38

2 Answers2

3

In the expression 10 ** (idx * 3 or 2), if the value idx is zéro, then 0 * 3 = 0.

In Python, all values like 0, 0.0, "", [], (), {}, False, None are evaluated to False. See the official documentation: Truth Value Testing.

So the equation idx * 3 or 2 is equivalent to False or 2 if ixd is 0. The result is 2.

If idx is not 0, the result is idx * 3, the or operator is not evaluated.

Laurent LAPORTE
  • 21,958
  • 6
  • 58
  • 103
1

It's because of the positioning of idx.

For example: if we omit "or 2" in the code and idx = 0, then...

10 ** (0 * 3) will give us 1 instead of the correct answer.

A better example:

Lets say the number is "one hundred". The position of idx for "hundred" in scales is 0. So without "or 2" in the code, "hundred" would be equal to... 10 ** (0 * 3) = 1 which isn't logically true, so you have to square 10 (hence where "or 2" comes into play) making the correction... 10 ** (2) = 100.

ecarl
  • 19
  • 3