Introduction to Python¶

Experimental Economics Data Workflow¶

  • A very short introduction to Python
    • Based on Learn X in Y minutes, where X=Python Attribution-ShareAlike 3.0 Unported (CC BY-SA 3.0)
    • Lutz, M. (2013). Learning python: Powerful object-oriented programming. " O'Reilly Media, Inc.".

Numbers and logical operators¶

In [ ]:
3+3
Out[ ]:
6
In [ ]:
10 * 3
Out[ ]:
30
In [ ]:
35 / 5
Out[ ]:
7.0
In [ ]:
35 % 6
Out[ ]:
5
In [ ]:
(1 + 3) * 2
Out[ ]:
8
In [ ]:
1 + 3 * 2
Out[ ]:
7

Boolean Operators¶

In [ ]:
True and False 
Out[ ]:
False
In [ ]:
False or True   
Out[ ]:
True
  • True and False are actually 1 and 0 but with different keywords
In [ ]:
True + True 
Out[ ]:
2
In [ ]:
True * 8    
Out[ ]:
8

Comparisons¶

  • Equality is ==
In [ ]:
1 == 1
Out[ ]:
True
In [ ]:
2 == 1
Out[ ]:
False
  • Inequality is !=
In [ ]:
1 != 1  
Out[ ]:
False
In [ ]:
2 != 1 
Out[ ]:
True

More comparisons¶

In [ ]:
1 > 10 
Out[ ]:
False
In [ ]:
1 > 10 or 1 < 10 
Out[ ]:
True
In [ ]:
2 <= 2
Out[ ]:
True

Strings and variables¶

Strings are an ordered collection of characters

In [ ]:
'This is a string.'
Out[ ]:
'This is a string.'
In [ ]:
"Hello " + "world!"
Out[ ]:
'Hello world!'
  • Variables can be declared
In [ ]:
name = "oTree"
  • Variables (strings) can be sliced and indexed
In [ ]:
name[0] 
Out[ ]:
'o'
In [ ]:
name[-3]  
Out[ ]:
'r'

Lists and tuples¶

In [ ]:
li = []
In [ ]:
li
Out[ ]:
[]
  • Add stuff to the end of a list with append
In [ ]:
li = [2,3,4]
In [ ]:
li
Out[ ]:
[2, 3, 4]
  • Add stuff to the end of a list with append
In [ ]:
li.append(5)
In [ ]:
li
Out[ ]:
[2, 3, 4, 5]
  • Access a list like you would any array
In [ ]:
li[0] 
Out[ ]:
2
In [ ]:
len(li)
Out[ ]:
4
In [ ]:
li [1:3]
Out[ ]:
[3, 4]
In [ ]:
del li[2]
In [ ]:
li
Out[ ]:
[2, 3, 5]
  • Check for existence in a list with "in"
In [ ]:
1 in li
Out[ ]:
False

Dictionaries¶

  • Useful way to collect and organize information
    • As an example, payoffs of players
    • They are used in settings.py to control apps
  • Storage of mappimngs from keys to values
In [ ]:
empty_dict = {}
In [ ]:
filled_dict = {"one": 1, "two": 2, "three": 3}
In [ ]:
filled_dict["one"]
Out[ ]:
1

Get all keys as an iterable with "keys()". We need to wrap the call in list()

In [ ]:
list(filled_dict.keys())
Out[ ]:
['one', 'two', 'three']

Get all values as an iterable with "values()". Once again we need to wrap it

In [ ]:
list(filled_dict.values())
Out[ ]:
[1, 2, 3]

Check for existence of keys in a dictionary with "in"

In [ ]:
"one" in filled_dict
Out[ ]:
True
In [ ]:
1 in filled_dict
Out[ ]:
False
  • Adding to an existing dictionary
In [ ]:
filled_dict.update({"four": 4})

Control flow and iteration¶

  • Often you need to iterate through variables
    • As an example, collect all choice sof participants in a group

Iterations¶

In [ ]:
some_var = 5


if some_var > 10:
    print("some_var is totally bigger than 10.")
elif some_var < 10:    # This elif clause is optional.
    print("some_var is smaller than 10.")
else:                  # This is optional too.
    print("some_var is indeed 10.")
some_var is smaller than 10.

Loops¶

In [ ]:
for i in range(4):
    print(i)
0
1
2
3
In [ ]:
for animal in ["dog", "cat", "mouse"]:
    # You can use format() to interpolate formatted strings
    print("{} is a mammal".format(animal))
dog is a mammal
cat is a mammal
mouse is a mammal
  • We can use list comprehensions to loop or filter
In [ ]:
numbers = [3, 4, 5, 6, 7]
[x for x in numbers if x > 5]   # => [6, 7]
Out[ ]:
[6, 7]

Indenting is important!

Functions¶

  • Use "def" to create new functions
In [ ]:
def add(x, y):
    print("x is {} and y is {}".format(x, y))
    return x+y  # Return values with a return statement
In [ ]:
add(5, 6)
x is 5 and y is 6
Out[ ]:
11

Classes¶

  • Classes are main object-oriented-programming (OOP) in Python
    • Class objects provide default behavior
      • The class statement creates a class object and assigns it a name
      • Assignments inside class statements make class attributes
      • Class attributes export object state and behavior
        • def statements inside class generate a method
    • Instance objects are generated from classes
      • Calling a class object makes a new instance object
      • Each instance object inherits class attributes and gets its own namespace
      • Assignments to self in methods make per-instance attributes
        • self refers to the instance being processed

Classes: An Example¶

  • Pokemon is a class with some properties

    • Height
    • Weight
    • Category
  • Two instances of the class →

Charmander:

  • Height: 2' 00";

  • Weight 18.7 lbs;

  • Category: Lizard

Bulbasaur:

  • Height: 2' 04";

  • Weight: 15.2 lbs;

  • Category: Seed

In [ ]:
class Pokemon:
    nature = "Pokemon"  # this property is shared by all instances

    def __init__(self, name, height, weight, category):
        # Assign the argument to the instance's name attribute
        self.name = name
        self.height = height
        self.weight = weight
        self.category = category
        self.comment = []
    # to add a comment

    def add_comment(self, comment):
        self.comment.append(comment)
    # convert height and weight into metric

    def convert_metric(self):
        # conversion rates
        feet_conv_cm = 30.5
        inch_conv_cm = 2.54
        lbs_conv_kg = 0.453592
        self.height_cm = int(self.height.split(
            "'")[0])*feet_conv_cm+int(self.height.split("'")[1])*inch_conv_cm
        self.weight_kg = self.weight*lbs_conv_kg
        # print the result
        print("Height (cm): %f, Weight (Kg): %f" %
              (self.height_cm, self.weight_kg))
  • Create two instances of the class
In [ ]:
p_1 = Pokemon("Charmander", "2' 5''", 18.7, "Lizard")
p_2 = Pokemon("Bulbasaur", "2' 04''", 15.2, "Seed")

p_1.name
p_2.name
Out[ ]:
'Bulbasaur'
  • Add a comment
In [ ]:
p_1.add_comment("Its ability is Blaze")
p_2.add_comment("Its ability is Overgrow")
  • Convert their measures in metric system
In [ ]:
p_1.convert_metric()
p_2.convert_metric()
Height (cm): 73.700000, Weight (Kg): 8.482170
Height (cm): 71.160000, Weight (Kg): 6.894598
  • Who is taller?
In [ ]:
if p_1.height > p_2.height:
    print(p_1.name + " is taller")
elif p_1.height < p_2.height:
    print(p_2.name + " is taller")
else:
    print(p_2.name + " and" + p_1.name + "are equally taller")
Charmander is taller

Further material¶

  • Take a look at the official Beginner's Guide for suggestions/ideas