Python Beginner: Selective Printing in loops
To print out every 100 iterations, I'd suggest
if i % 100 == 0: ...
If you'd rather not print the very first time, then maybe
if i and i % 100 == 0: ...
(as another answer noted, the i = i + 1
is supererogatory given that i
is the control variable of the for loop anyway -- it's not particularly damaging though, just somewhat superfluous, and is not really relevant to the issue of why your if
doesn't trigger).
While basing the condition on t
may seem appealing, t == int(t)
is unlikely to work unless the t_step
is a multiple of 1.0 / 2**N
for some integer N
-- fractions cannot be represented exactly in a float unless this condition holds, because floats use a binary base. (You could use decimal.Decimal
, but that would seriously impact the speed of your computation, since float
computation are directly supported by your machine's hardware, while decimal computations are not).
The for loop auto increments for you, so you don't need to use i = i + 1
.
You don't need t
, just use %
(modulo) operator to find multiples of a number.
# Log every 1000 lines.
LOG_EVERY_N = 1000
for i in range(1000):
... # calculations with i
if (i % LOG_EVERY_N) == 0:
print "logging: ..."