Variables#
A simple problem as motivation - spike detection#
To have a problem to start with, let’s assumer we want to detect the spikes in this voltage trace.
A spike is a peak in the voltage trace exceeding a threshold value.
More specifically, we are interested in when the spikes occur - the spikes times.
How would you solve this?#
Let’s break this down into a sequence of simple steps, like a recipe:
weigh 100 grams flour
take 3 eggs
mix eggs and floor in a bowl
beat it!
…
Now try to explain to your grandma or a 5-year old how you would extract the time of each spike:
Presenting data in code#
Why have variables?#
You can work directly with numbers and use python as a calculator:
1 + 4
5
Try it yourself by clicking into the cell above and changing the numbers.
You can execute the code using Control+Enter.
Variables abstract away specific data “types”/”roles” from the specific data values#
Working with numeric values directly isn’t very general, since you tie your code to specific numeric values.
Variables are a way to make your code more general (and thereby more useful), by separating specific data values from the general computation. You can think of the variable as a storage container: it can store information that you can access via its name and manipulate in your program.
A variable is created with the syntax name = value
.
name
can be any combination of characters, underscores and numbers (as long as it does not start with a number)value
can be a number, text (or an arbitrary “python object”).
That way, you can express your program’s computation in general terms - as the manipulation of variables.
What is a Variable? In computer programming, a variable has a name and contains a value. A variable is like a box. If you labeled the box as
toys
and put a yo-yo inside it, in programming terms,toys
is the variable name, and yo-yo is the value.
In math, the
=
is used to test for equality (\(a = b\)). In python, we use it for assigning values to variables. Double equal signs==
test for equality in python.
Computing firing rates#
Back to neuroscience: Say we want to compute the firing rate of a neuron. We have counted the number of spikes (132) our neuron fired during a recording of 16 seconds. The firing rates - the number of spikes per second (1/s=Hz) - is given by the ratio of both:
132 / 16
8.25
But this is
not very general and
not very readable.
First, we directly tie the computation - calculating the ratio - to the data values, if we want to compute the firing rate for another neuron, we have to meddle with the code. This becomes more relevant if the computation becomes more complicated.
Second, it’s unclear what 132 / 16
means without knowing the context of the code - these numbers could mean anything.
Variables with informative names provide context - it’s clear from looking at the code what is being computed!
A variable is created and assigned a value, using the =
character, like in math:
x = 10
. Here, x
is the name of the variable and 10
is it’s value.
We can assign the number of spikes and the duration of experiments to two variables, n_spikes
and duration
and compute the firing rate as their ratio:
n_spikes = 132
duration = 16 # seconds
firing_rate = n_spikes / duration # 1/seconds=Hz
firing_rate
8.25
Note 1: The #
character allows you to comment your code - everything following #
will be treated as a comment and not as code that is executed by python.
Note 2: The value of the last line in a cell, in this case firing_rate
, is printed below the cell automatically.
By changing the value of the different variables, n_spikes
and duration
, you can run the same computation, n_spikes / duration
, on different data (for instance, different trials from the same experiment). This is useful if the computation is more complicated.
Whenever you type a variable name in code it will be replaced by the value (in this case, the number) it is referring to.
Above, the expression firing_rate = n_spikes / duration
is treated the following by Python:
The value of the variable
n_spikes
is looked up as132
n_spikes
inn_spikes / duration
is replaced by132
. The expression is now132 / duration
the value of the variable
duration
is looked up as16
duration
in132 / duration
is replaced by16
. The expression is now132 / 16
The computation is performed and the result,
8.25
assigned the variablefiring_rate
.
Clicker question “my_var” (Click me!)
What will be the value of x after executing this code?
my_var = 2
my_var = my_var + 1
Working with numerical variables - arithmetics on numbers#
Back to numbers. To perform computations, you need mathematical operations. These are common (and not so common) operations defined in python:
Symbol |
Computation performed |
---|---|
+ |
addition |
- |
subtraction |
* |
multiplication |
/ |
division |
** |
power (\(2^3\)= |
// |
floor division (yields the integer part of the division) |
% |
modulo (yields the remainder of the division) |
# Examples
a = 16
b = 3
print(a + b, '= a + b (addition)')
print(a - b, '= a - b (subtraction)')
print(a * b, '= a * b (multiplication)')
print(a / b, '= a / b (division)')
print(a ** b, ' = a ** b (power)')
print('Plus some weird stuff that we will ignore for now:')
print(a // b, '= a // b (Floor Division yields the integer part of the quotient.)')
print(a % b, '= a % b (Modulo yields the remainder of division.)')
19 = a + b (addition)
13 = a - b (subtraction)
48 = a * b (multiplication)
5.333333333333333 = a / b (division)
4096 = a ** b (power)
Plus some weird stuff that we will ignore for now:
5 = a // b (Floor Division yields the integer part of the quotient.)
1 = a % b (Modulo yields the remainder of division.)
Dealing with text#
How about data that is not numeric, like names? The simplest example would be a phone book, in which we need to represent the names of our contacts.
Simply assigning the name to a variable does not work - this will throw an error:
name_of_the_whale = Keiko
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[28], line 1
----> 1 name_of_the_whale = Keiko
NameError: name 'Keiko' is not defined
Note on errors: When you write “invalid” code, python does not make your computer crash, but generates an error with a (sometimes cryptic) description of the cause of the error.
This is because single letters and words are interpreted as variable names.
In the above example, python assumes that Keiko
is a variable and looks up the value of the Keiko
variable, but a variable with the name Keiko
does not exist! Hence the NameError
To tell python that the value of your variable is text, we wrap it in '...'
or "..."
.
Variables with text as values are called strings.
name_of_the_whale = 'Keiko'
speed = "Mach 2"
year = "1968"
Types of variables#
Variables come in different flavors - so far, we have encountered three types of variables:
integer numbers:
int
- number without a decimal point (1, 2, 103241)floating point numbers:
float
- number with a decimal point (3.141)string:
str
: sequence of characters (“yes”, ‘no’)
These types of variables exist in every programming language!
Determining the type of variables#
Wrong variable types can be a source of errors in your code.
Below, an error is raised because one cannot add a variable of type string to a number in python.
a = 15.6
b = '12.4'
a + b
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[30], line 3
1 a = 15.6
2 b = '12.4'
----> 3 a + b
TypeError: unsupported operand type(s) for +: 'float' and 'str'
It is therefore often useful to determine the type of a variable.
The type
function returns the type of a variable:
Note: Functions#
Functions are used via their name, followed by the input argument in parentheses:
function_name(argument)
Many functions also return a result, that can be assigned to a new variable:
result = function_name(argument)
We can now use the function type
by providing the variable as an argument in parentheses:
type(a), type(b)
(float, str)
Changing variable types#
You can change the type of a variable - cast it to another type - using the functions int
, float
, str
, and bool
, with the variable you want to cast as the argument:
You can turn a string to a number using int
or float
. But this works only if the string variable contains only numerical data:
b = '12.4'
b_as_float = float(b) # cast a from a string to a floating point
type(b), type(b_as_float)
(str, float)
age_as_str = '10'
age_as_int = int(age_as_str)
age_as_str, age_as_int, type(age_as_str), type(age_as_int)
('10', 10, str, int)
You can turn a number into a text using str
:
a = 10
str(a), type(a), type(str(a))
('10', int, str)
age_as_str = '10years'
age_as_number = int(age_as_str)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[19], line 2
1 age_as_str = '10years'
----> 2 age_as_number = int(age_as_str)
ValueError: invalid literal for int() with base 10: '10years'
age_as_str = '10 0'
age_as_number = int(age_as_str)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[20], line 2
1 age_as_str = '10 0'
----> 2 age_as_number = int(age_as_str)
ValueError: invalid literal for int() with base 10: '10 0'
Naming variables#
You can name a variable almost anything you want.
It needs to start with a letter or “_” and can contain alphanumeric characters (letters or numbers) plus underscores (“_”):
# Valid names
cool_variable = 10
_cool_variable = 10
password_123 = 'bad'
# Invalid names
10th_number = 3.34 # variables can't start with a number
Cell In[22], line 2
10th_number = 3.34
^
SyntaxError: invalid decimal literal
a+b = 27 # variables should contain operands like +, -, / etc.
Cell In[23], line 1
a+b = 27 # variables should contain operands like +, -, / etc.
^
SyntaxError: cannot assign to expression here. Maybe you meant '==' instead of '='?
In addition, special key words are reserved for the language (no need to remember them - just keep this in mind so you know how to interpret the resulting error): and
, as
, assert
, break
, class
, continue
, def
, del
,
elif
, else
, except
, exec
, finally
, for
, from
, global
, if
, import
, in
, is
, lambda
, not
, or
, pass
, raise
, return
, try
, while
, with
, yield
# Example
if = 3
Cell In[25], line 2
if = 3
^
SyntaxError: invalid syntax
Names should be short (but not too short) and descriptive#
a
is very short but meaningless - it is unclear what type of informationa
stores.concentration
orsubject_name
is a bit longer but its meaning is evident from the name.name_of_the_first_subject_on_monday_morning
is too long.
a = 1 # assign value 1 to variable with name a
concentration = 0.1 # mM
subject_name = "Mabel" # better variable name as it is descriptive
name_of_the_first_subject_on_monday_morning = "Thelonious" # too long
Exercise “Variables…” #4.
Spike detection with python#
Present data in code (individual voltage values, manipulate them and store the results) - variables
Compare variables (voltage to threshold) - boolean values
Perform different actions based on the value of a variable (only keep the position if the voltage exceeds the threshold) - if-else statements
Present and access data in a time series of voltage values - lists
Perform an action for each element in a sequence of values (inspect voltage values one-by-one) - for loops
Separate data and logic so we can use the same code for new recordings - functions
Apply this to multi data files
Plot and save the results