Cog-Sci Bootcamp 2015 - iPython Notebook - Intro to Python - Basic

This is a quick overview of some of the basic features of python. There are many good resources for learning python, and you should check them out if you want more information.

Python has an official style guide, called Pep-8. This is how you should write python!

iPython Notebook is


In [1]:
## iPython Notebook magic commands!
# iPython notebooks have what it calls 'magic commands', which are predefined functions you can run 
# The syntax is like running in a shell, and looks like'% command args'

# To access some documentation about magic commands from within iPython, use '% quickref'
% quickref

In [36]:
## Python, whether run from a terminal or in iPython is always running in some directory
# iPython defaults to launching in your user home directory
# The cd (current directory) command is one of the magic commands, and will print out the current directory. 
% cd


/Users/thomasdonoghue

In [37]:
## Help in iPython
# Another one of the magic commmands is the help command. 
# This is used by adding a question mark ('?') to end of a function name. 
# For example: (See if you can now use the round function)
round?

In [38]:
## Python Types - Basic
# Python (like Matlab) is also a non-explicitly typed language. 
# You can use the type() function to check the type of a variable
int_number = 1                 # The integer type is for number without a decimal place (positive or negative)
float_number = 1.0             # The float type is for numbers 
string = 'Hello!'              # The string type is for characters
boolean = True                 # Booleans are for True or False

print type(int_number)
print type(float_number)
print type(string)
print type(boolean)


<type 'int'>
<type 'float'>
<type 'str'>
<type 'bool'>

In [39]:
# Notice that integers and decimals numbers (floats) are different kinds of variables
# Be careful with this, they act differently!
print 10/4
print 10.0/4


2
2.5

In [40]:
# You can also cast variable (force them to be a certain type)
cast_float = float(int_number)       # Cast a integer into a float
print cast_float
cast_int = int(float_number)         # Cast a float into an integer
print cast_int
cast_boolean = int(boolean)          # Cast a boolean into an integer (remember: False=0, True=1)
print cast_boolean


1.0
1
1

In [41]:
## Other python types
# Lists - a list is a mutable list of things, which can be of mixed types
# Lists use square brackes
list_of_stuff = [1, 6.4, 'Banana', True, 6.]
print type(list_of_stuff)
print 'List item: ', list_of_stuff[2]

# Tuple - a tuple is set of unmutable things, which can be of mixed types
# Tuples use parentheses
tuple_of_stuff = (1, 6.4, 'Banana', True, 6.)
print type(tuple_of_stuff)
print 'Tuple item: ', tuple_of_stuff[2]

# Dictionary - a dictionary is a set of things, indexed and accessed by keys
dictionary_of_stuff = {'delta': 2, 'theta': 6, 'alpha': 8, 'beta': 13, 'gamma': 25}
print type(dictionary_of_stuff)
# Things in a dictionary are accessed by their key
print 'Dictionary element: ', dictionary_of_stuff['delta']
# To check the keys of a dict, run the 'keys()' function on a dict, like so:
print 'Dictionary Keys: ', dictionary_of_stuff.keys()

## NOTES
# Note that these data types are all created with different characters ('()', '[]', '{}')
# However, they are all called (accessed) with square brackets '[]'
# Tuples are immutable. Try re-assigning an index in an already defined tuple.


<type 'list'>
List item:  Banana
<type 'tuple'>
Tuple item:  Banana
<type 'dict'>
Dictionary element:  2
Dictionary Keys:  ['theta', 'alpha', 'beta', 'gamma', 'delta']

In [42]:
## Dir function
# The dir function does lots of useful things. Check out the help. Called without an argument, it prints out names in scope. 
dir?

# Notice above that we called a function directly on our dictionary.
# Types and objects (well get to those later) have functions that can be called on them. 
# Dir with an argument, prints out the attributes & functions of the given object/function/variable
dir(dictionary_of_stuff)


Out[42]:
['__class__',
 '__cmp__',
 '__contains__',
 '__delattr__',
 '__delitem__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getitem__',
 '__gt__',
 '__hash__',
 '__init__',
 '__iter__',
 '__le__',
 '__len__',
 '__lt__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__setitem__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 'clear',
 'copy',
 'fromkeys',
 'get',
 'has_key',
 'items',
 'iteritems',
 'iterkeys',
 'itervalues',
 'keys',
 'pop',
 'popitem',
 'setdefault',
 'update',
 'values',
 'viewitems',
 'viewkeys',
 'viewvalues']

Note that Python is a whitespace language. Spacing matters, and is used to delineate sections of code Unlike matlab, there is no 'end' statement for sections of code. The end of a block of code is marked by the spacing. Lines of code inside a block are tabbed. To open a block of code (in a conditional, loop, function etc.) us the colon (':')


In [43]:
## Conditionals
# Python has an if, elif, else conditional block

x = 5
if (x > 4):
    print 'X is Big!'
elif (x < 4):
    print 'X is Small!'
else:
    print 'I don\'t know what is going on'


X is Big!

In [50]:
## Loops
# Python has a for loop and while loop

# You can use a loop by running through a list of numbers
for x in range(0, 4):
    print x

print '\n'        # The '\' is an escape character in a string. Here, '\n' prints a new line.
    
# You can also loop through all the indexes in a variable (for example, loop through a list)    
v = ['V1', 'V2', 'V3', 'V4']
for i in v:
    print i

print '\n'
    
# The while loop uses a conditional, and will run until it is False
y = 1
while y < 5:
    print y
    y += 1         # This is shorthand for 'y = y + 1'


0
1
2
3


V1
V2
V3
V4


1
2
3
4

In [51]:
## Functions

# Example of how functions are set up
#
# def function_name(input1, input2, ...):
#     """ Docstring - this describes the function"""
#     'code that does stuff'
#     return variable_to_return

# Example with a real function
# 
def add(a, b):
    """ This function adds two numbers, and returns the result"""
    out = a+b
    return out

sum_of_numbers = add(4, 5)
print sum_of_numbers


9