Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Beginner: Selective Printing in loops

I'm a very new python user (had only a little prior experience with html/javascript as far as programming goes), and was trying to find some ways to output only intermittent numbers in my loop for a basic bicycle racing simulation (10,000 lines of biker positions would be pretty excessive :P).

I tried in this loop several 'reasonable' ways to communicate a condition where a floating point number equals its integer floor (int, floor division) to print out every 100 iterations or so:

 for i in range (0,10000):
  i = i + 1
  t = t + t_step #t is initialized at 0 while t_step is set at .01
  acceleration_rider1 = (power_rider1 / (70 * velocity_rider1)) - (force_drag1 / 70)
  velocity_rider1 = velocity_rider1 + (acceleration_rider1 * t_step)
  position_rider1 = position_rider1 + (velocity_rider1 * t_step)
  force_drag1 = area_rider1 * (velocity_rider1 ** 2) 
  acceleration_rider2 = (power_rider2 / (70 * velocity_rider1)) - (force_drag2 / 70)
  velocity_rider2 = velocity_rider2 + (acceleration_rider2 * t_step)
  position_rider2 = position_rider2 + (velocity_rider2 * t_step)
  force_drag2 = area_rider1 * (velocity_rider2 ** 2)

  if t == int(t): #TRIED t == t // 1 AND OTHER VARIANTS THAT DON'T WORK HERE:(
   print t, "biker 1", position_rider1, "m", "\t", "biker 2", position_rider2, "m" 
like image 300
Jonathan Straus Avatar asked Apr 25 '10 18:04

Jonathan Straus


1 Answers

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: ..."
like image 129
Stephen Avatar answered Oct 17 '22 03:10

Stephen