The For Loop
A for loop says: do this thing for every item in a list, one at a time.
Instead of writing the same line of code over and over, you write it once — and Python repeats it automatically for each item.
# Loop over a spike train
spike_times = [10, 25, 42, 67]
for t in spike_times:
print(f'Spike at {t} ms')
# Output:
# Spike at 10 ms
# Spike at 25 ms
# Spike at 42 ms
# Spike at 67 msEach time through the loop, t takes the next value from the list. It runs 4 times — once for t=10, once for t=25, and so on.
range() is a shortcut for generating a sequence of numbers. Instead of writing out [0, 1, 2, 3, 4] by hand, you just write range(5) and Python creates it for you.
for i in range(5):
print(i)
# prints: 0, 1, 2, 3, 4range(5) starts at 0 and stops before 5. It gives you exactly 5 numbers.
Why do neuroscientists love for loops?
The brain doesn't work all at once — it works step by step through time. Every millisecond, billions of neurons update their voltage, check if they should fire, and send signals.
When you build a neuron model in NMA, you simulate this exact process. You loop over every millisecond of time, and at each step you ask: did the neuron fire?
# Simulate a neuron for 1 second (1000 ms)
for t in range(1000):
# at each millisecond:
# - update membrane voltage
# - check if it crossed the threshold
# - if yes, record a spike
passEvery NMA neuron model you'll see is built around a loop like this. The loop IS the simulation.
Indentation matters in Python! Code inside a loop MUST be indented (4 spaces or 1 tab). It tells Python what's 'inside' the loop and what runs after it finishes.