+10 XP
For Loops in Python
A for loop repeats code for every value in a sequence. In neuroscience simulations, we loop through time: for each millisecond, update the neuron state.
range(n) generates numbers 0, 1, 2, …, n−1. Why n−1? Python starts counting at 0. range(5) gives [0, 1, 2, 3, 4] — that's 5 numbers total.
python
# Loop through time stepsdt = 1e-3for step in range(5):→ range(5) gives steps: 0, 1, 2, 3, 4
t = step * dt # convert step number to time in seconds→ step * dt converts integer step → actual time in seconds
print(f"Step {step}: t = {t*1000:.1f} ms")In the NMA simulation we use range(int(t_max/dt)) to get all steps. With t_max = 150e-3 and dt = 1e-3, that's range(150) — 150 time steps covering 150 ms.
python
import numpy as npt_max = 150e-3dt = 1e-3num_steps = int(t_max / dt)print(f"Total steps: {num_steps}")for step in range(3): # show first 3 steps only t = step * dt print(f" step={step}, t={t*1000:.0f} ms")This pattern — range(int(t_max/dt)) — appears in every NMA time-series simulation.