Skip to content
Pat Gunn edited this page Nov 28, 2017 · 1 revision

Python features

  • types are enforced
  • you don't have to declare variables
  • case sensitive
  • object-oriented
  • indentation is part of the language (do not mess with indentation)

BUT you can use it like MATLAB.

Getting help

  • from interactive shell, keyword plus ? or help(keyword) Example:
print?

or

help(print)

From Spyder, most of the times you can get a much nicer format from the object inspector if you highlight the word in the editor and type COMMAND + i.

importing

Python needs to import all the packages that are used in a function. Very few things are defined by default. Even the array class needs to be imported. Some syntax examples of the command are:

import scipy
import numpy as np
import caiman as cm
from sklearn.decomposition import PCA
from matplotlib import pylab as pl

Types

  • variables
  • lists
  • arrays
  • dictionaries
  • tuples
import numpy as np

variable_1 = a
variable_2 = 'ciao'

list_1 = [1,2,3,4,5] # mutable, can change the size
list_2 = [1,2,'ciao','bello']
list_3 = [[1,2],[3,4],5,'6']

array_1 = np.array([1,2,3,4])
array_2 = np.arange(1,10,2)
array_3 = np.array([[1,2,3,4],[1,2,3,4]])

dictionary_1={'number':10,'string':'hug','my_field':[2,5,6]}
print(dictionary_1['number'])
dictionary_1['number'] += 10
print(dictionary_1['number'])

tuple_1 = (10,20) # immutable, cannot change the size, example: vector size.
print (array_3.shape)

function = len
print(function(tuple_1))

You can slice lists and vector like in matlab with regular patterns. However notice that numbering in Python starts from 0 and not 1.

Examples:

list_sl = range(20)
print(list_sl[0]) # first element of list/vector
print(list_sl[-1]) # last element of list/vector
print(list_sl)
print(list_sl[::2]) # every two
print(list_sl[::-2]) # every two from the end
print(list_sl[1:10:2]) # from 1st to 10th every two

print(list_sl[-1]) # last element of list/vector

If you want to slide with irregular indexes you cannot use list. Try

print(list_sl[[1,3,4]])

and then

print(np.array(list_sl)[[1,3,4]])

only arrays can be sliced irregularly.

Flow control

  • for
  • while
  • if
  • elif

Similar to MATLAB, but there is no end keyword, the indentation indicates blocks. Example: experiment_work = True

experiment_worked = False

if 'NIN' in 'NINE-INCH-NAILS':

   print('Neuroscience rocks!!')

elif experiment_worked:

   print('Neuroscience is 98% Failure')

Notice the colon to signify end of the condition!

Function definition

There are both required and optional arguments. A fantastic feature of Python is that it lets you define the default values for optional parameters (lol).

def sloppy_sum(input_number_1, input_number_2, real_math = True):

    if real_math:

          result = input_number_1 + input_number_2

    else:

          result = input_number_1 + input_number_2*np.random.random()

    return result

print(sloppy_sum(1., 1.))
print(sloppy_sum(1., 1., real_math = False))    

Saving and loading

In Python

#saving 
import numpy as np
arr_1 = np.ones(10)
arr_2 = np.zeros(10)
np.save('ones.npy',arr_1)
np.savez('ones_and_zeros.npz',arr_zeros = arr_1, arr_ones = arr_2)

#loading 
arr_1 = np.load('ones.npy')
with np.load('ones_and_zeros.npz') as ld:
   print(ld['arr_zeros'])
   print(ld['arr_ones'])

In Matlab format

#saving
import scipy
import numpy as np
arr_1 = np.ones(10)
arr_2 = np.zeros(10)
scipy.io.savemat('ones_and_zeros.mat',{'arr_zeros': arr_1, 'arr_ones' : arr_2})

#loading 
ld = scipy.io.loadmat('ones_and_zeros.mat')
print(ld['arr_zeros'])