0

What is (if) used for when it is not followed by comparison or logical operators? I mean this line if magic_square[newi , newj]: in the following code

import numpy as np
N = 5
magic_square = np.zeros((N, N), dtype=int)
n = 1
i, j = 0, N//2 
while n <= N**2: 
 magic_square[i, j] = n 
 n += 1 
 newi , newj = (i - 1) % N, (j + 1)% N 
 if magic_square[newi , newj]:
  i += 1 
 else:
  i, j = newi , newj
print(magic_square)
Youssef
  • 13
  • 1

1 Answers1

1

The if statement will evaluate the result of the expression magic_square[newi, newj] for "truthy"-ness. In python, a value will evaluate to as true in a boolean context when it is

  • True
  • A non-empty collection
  • A numeric non-zero value
  • An object who's class defines a __bool__() or __len__() method which doesn't return the bool value False or integer 0 respectively.

In this case, if magic_square is a 2-dimensional array of numbers, the if statement is equivalent to if magic_square[newi, newj] != 0

Chad S.
  • 6,252
  • 15
  • 25
  • `None` and `0` are objects, but they are not truthy. – mkrieger1 Jan 21 '22 at 19:17
  • 1
    I believe [this answer](https://stackoverflow.com/a/39984051/6045800) (and the rest on that page) explains this much better (no offence)... Instead of repeating the same answers, maybe it is better to close as a duplicate (seeing you have over 3k rep) – Tomerikoo Jan 21 '22 at 19:25
  • The *default* truthiness for an object (inherted from `object`) is `True` unless the type overrides `__bool__` (or `__len__`) to provide a different value. – chepner Jan 21 '22 at 19:45
  • I have edited the answer to be more accurate – Chad S. Jan 28 '22 at 20:41