+10 XP
Defining Functions
A function is a named block of code you can run any time, with different inputs. In NMA, almost every computation is a function.
python
# Define a function
def firing_rate(n_spikes, duration_ms):
"""Calculate mean firing rate in Hz."""
return (n_spikes / duration_ms) * 1000
# Call the function
rate = firing_rate(42, 1000) # 42 spikes in 1 second
print(f'Firing rate: {rate} Hz') # 42.0 Hzdef starts a function. Parameters go in parentheses. return sends back the result.
Functions can have default parameters — values used if you don't provide them. They also have a docstring (triple quotes) that explains what they do:
python
def lif_neuron(I, R=10, V_rest=-70, threshold=-55):
"""Simple model of a neuron firing.
Think of it like this: a neuron sits at rest, gets stimulated by input,
and if it gets stimulated enough, it fires a spike.
Parameters (inputs you provide):
I: input current — how much stimulation the neuron gets (YOU change this)
R: resistance — how the neuron's biology responds (preset: 10)
V_rest: resting voltage — voltage when neuron is relaxed (preset: -70 mV)
threshold: spike threshold — voltage needed to fire (preset: -55 mV)
Returns:
True if neuron fires (voltage crosses threshold)
False if neuron stays quiet (voltage below threshold)
"""
# Calculate the neuron's voltage based on input
V = V_rest + I * R # voltage = rest + (stimulation × resistance)
# Check: did this voltage cross the threshold?
return V > threshold # Returns True or False (not the voltage itself)The docstring explains what the function does in plain English. Only I (input) usually changes — the rest are preset based on the neuron's biology.
Always write a docstring for your functions! It tells other scientists (and future you) what the code does. In NMA notebooks, you'll see this pattern constantly.