##Introduction to Object Orientated Programming Through Python.
####Vincent Knight
[www.vincent-knight.com](http://www.vincent-knight.com)
## This prepares you for a 2 day challenge
---
1. Be able to program using [Python](http://www.python.org).
2. Understand the basic ideas behind Object Orientated Programming.
3. Use your skills in a mini "hackathon" to solve a problem.
## 1. Basic Python
---
- Variables
- Flow Control
- Functions
- Data Structures
## 2. Basic OOP
---
- Classes
- Attributes
- Methods
- Inheritance
## 3. Challenge
---
- End of the day Thursday: Initial feedback
- End of the day Friday: results
##Guido van Rossum
---
##What is Python?
---
[![the python logo](http://www.python.org/images/python-logo.gif)](http://www.python.org)
- Simple
- Easy to Learn
- Free and Open Source
##What is Python?
---
[![the python logo](http://www.python.org/images/python-logo.gif)](http://www.python.org)
- High-level Language
- Portable
- Interpreted
- Libraries
##What is Python?
---
[![the python logo](http://www.python.org/images/python-logo.gif)](http://www.python.org)
- **Object Orientated**
##What do I need to use Python?
---
- [Python](www.python.org)
- A text editor (required for longer programs)
##IDLE (Mac)
---
##Terminal (Mac)
---
##IDLE (Windows)
---
##Terminal (Windows)
---
![Screenshot of terminal on Windows](Terminal_Screenshot_Win.png)
##Terminal (Linux)
---
![Screenshot of terminal on Lubuntu](Lubuntu_Screenshot.png)
##Hello world!
---
- Type the following in to the Interpreter:
print "Hello world!"
- Press Enter. (This should convince us that we have python running on our machines).
##IDLE Editor (Mac)
---
##IDLE Editor (Windows)
---
##Vim (Mac)
---
##Vim (Ubuntu)
---
##Notepad++ (Windows)
---
##Hello World! (again)
---
- Create a new Python file in IDLE. Type the following:
print "Hello world!"
- Run the script (F5). (This now convinces us that we have a text editor and that we can use it to write larger portions of Python code).
## Getting help
---
- [Google](https://www.google.com)
- Some great books:
- ["A byte of Python"](http://www.swaroopch.com/notes/python/)
- ["Thinking in Python"](http://mindview.net/Books/TIPython)
- The help command in Python:
help("range")
##Comments in code
---
- Python is known for the clarity of it's syntax: "interpretable pseudo code"
- **But** it is still important to write code with comments.
- Add the following to your Python script:
print "Hello world!"
#That was a command, this is a comment
print "Writing comments is awesome"#Here is another comment...
"Code tells you how, comments tell you why."
Style
[*A Foolish Consistency is the Hobgoblin of Little Minds*]("http://www.python.org/dev/peps/pep-0008)
##Variables
---
- Character variables.
string = "Hello world"
print string
- Numeric variables.
num_1 = 2
num_2 = 3.5
print num_1 + num_2
##String Manipulation
---
#We define a variable called String:
string = "My name is Vince"
#Let's print the 5th letter of String (Note that Python starts counting at 0):
print string[4]
##String Manipulation
---
#We print the elements in position 1 to 4 (not included) in String:
print string[1:4]
##String Manipulation
---
#We can use the "index" method to find the position of the first occurrence of an element in String:
a = string.index("V")
print a
##String Manipulation
---
#If we leave 1 position empty Python returns "everything":
print string[a:]
print string[:a]
##Numeric Manipulation
---
#We define a variable called Num:
num = 3
#We can add 1 to Num in 2 ways:
num = num + 1
num += 1
print num
##Numeric Manipulation
---
#We can carry out other numeric operations in a similar way:
num -= 2
num *= 3
num **= 2
print num
##Numeric Manipulation
---
#Note that we might not get what we expect with division:
num2 = 5
print num / num2
#Try (there are other ways):
print num / float(num2)
##Flow Control
---
There are 3 types of flow control that we shall consider:
- If statement
- While statement
- For statement
## If Statement
---
#We define a variable guess to be inputted at the prompt:
guess = input('Guess a number:')
#We use the if statement to check a condition.
#We're using modulo arithmetic to check if the guess is a multiple of 2:
if guess % 2 == 0:
#If the guess is a multiple of 2 we print a statement to the prompt:
print "Your guess was an even number"
#If the guess is not a multiple of 2 we print a different statement:
else:
print "Your guess was an odd number"
- **In Python indentation is important!**
- In all languages indentation is good practice, in Python it is a requirement.
## While Statement
---
#We set an initial guess:
correct_guess = 9
#We define a variable guess through input at the prompt:
guess = input('What is my favorite number:')
#We use the while command to repeatedly evaluate whether or not the user guesses correctly.
while guess != correct_guess:
#We embed an if statement within this while loop to help the user guess correctly.
if guess > correct_guess:
guess = input('Your previous guess was too high:')
else:
guess = input('Your previous guess was too low:')
#Note the indentation levels indicating that we are outside of the while loop.
print "Great guess!"
## For Statement
---
#The for statement is a very powerful statement that allows us to loop over elements in a list (we will look at lists closely shortly).
for i in [1, 2, 3, 4]:
print i
## For Statement
---
#We can iterate over all types of variables:
for i in ["Queueing Theory", "Game Theory", "Inventory Theory", "Reliability Theory", "Project Management", "Decision Analysis"]:
#We check if the string 'Theory' is contained within each element of the above list:
if "Theory" in i:
print i
## Functions
---
#To create a function we use the 'def' statement:
def hi():
"""
This function simply prints a short statement. (This is a shorter way of writing longer comments, it's good practice to always include a description of what a function does).
"""
print "Hello everybody!"
hi()
## Functions
---
#We can also pass arguments to a function:
def fibonacci_function(n):
"""
This returns the nth Fibonacci number.
"""
#We have 2 statements to check initial conditions
if n == 0:
return 1
#We use the 'else if' statement: "elif":
elif n == 1:
return 1
a, b = 0, 1
#We use a for statement with the range command.
for k in range(n):
#We here use simultaneous assignment:
a, b = b, a + b
return b
## 1.4 Data Structues
---
## Data Structures
---
The variables we saw earlier (and others) can be "contained" in various types of data structures:
- Lists
- Dictionaries
## Lists
---
A list is a data structure that holds an ordered collection of 'objects'.
#We define a list using the range command that gives us a collection of integers:
my_list = range(6)
print my_list
#We can index elements of a list in the same way we indexed strings:
print my_list[0]
#An important 'method' that can be used on lists is the 'append' method which lets us add an object to a list:
my_list.append(100)
print my_list
## Dictionaries
---
In Python Dictionaries are a type of "Hash Table":
- Unordered set of *key*:*value* pairs.
- A phone book
- An efficient way of storing data that needs to be queried often.
## Phonebook
---
A bad phone book:
pb = [["Vince", 3], ["Zoe", 2], ["Julien", 6], ["Thomas", 10], ["Mike", 1], ["Matt", 4]]
![A bad phone book](https://docs.google.com/drawings/pub?id=1QlxzX6QVWrWcsjvFQzmF5f3kPzs97jWG_xywX3lajNU&w=693&h=101)
## Phonebook
---
A good phone book:
#This is the syntax for a Python dictionary, made up of 'keys' and corresponding 'values':
pb = {"Vince": 3, "Zoe": 2, "Julien": 6, "Thomas": 10, "Mike": 1, "Matt": 4}
![A good phone book](https://docs.google.com/drawings/pub?id=1y4zAM01OZC76oxt2rf-6Ie-5AY1vLV8Q-mHdOwS920o&w=693&h=101)
## Dictionaries
---
#Creating a dictionary:
my_dictionary = {"Vince": 3, "Zoe": 2, "Julien": 6, "Thomas": 10, "Mike": 1, "Matt": 4}
#Adding 10 to the value associated to the key: "Zoe":
my_dictionary["Zoe"] += 10
print my_dictionary
## 2. Object Orientated Programming
## "I wanted to get rid of data"
---
[![Objects as cells](https://docs.google.com/drawings/pub?id=1Vg1NZ-n3KlLC5b10M0PEVwMeUTPjkUMX2zVNzwYYC8o&w=400)](http://userpage.fu-berlin.de/~ram/pub/pub_jf47ht81Ht/doc_kay_oop_en)
## Object Orientated Programming
---
![Summary](https://docs.google.com/drawings/pub?id=1bpeHjNnJRq4c8g8AgL3-J0QqgpnmcXmcr4AVte9EGLI&w=700)
## Defining a class
---
#We will define a new class called "Student"
class Student():
pass
## Creating an instance of our class
---
#We will define a new class called "Student"
class Student():
pass
#We create Vince, an instance of Student:
vince = Student()
#We can call Vince to see what "it" is:
print vince
Create another instance and verify that it is different.
## Giving objects attributes
---
#We modify our class Student so that our object has numerous attributes:
class Student():
courses = ["Biology", "Mathematics", "English"]
age = 5
sex = "Male"
#Let us now create Vince again:
vince = Student()
## Accessing attributes
---
#We can take a look at the values of each attribute:
print vince.courses
print vince.age
print vince.sex
## Manipulating attributes
---
#We can add a new course:
vince.courses.append("French")
print vince.courses
#We can change the value of the age:
vince.age = 28
print vince.age
#We can change the value of sex:
vince.sex = "M"
print vince.sex
## Defining a method
---
class Student():
courses = ["Biology", "Mathematics", "English"]
age = 5
sex = "Male"
#We can define methods within our class:
def have_a_birthday(self):
self.age+ = 1
#Let us see how this works:
vince = Student()
print vince.age
vince.have_a_birthday()
print vince.age
## The init method
---
#The init method is a special method that allows us to pass arguments when we generate an instance of a class.
class Student():
def __init__(self,courses,age,sex):
self.courses = courses
self.age = age
self.sex = sex
#We can define methods within our class:
def have_a_birthday(self):
self.age += 1
#Let us see how this works:
vince = Student(["Biology","Math"],28,"Male")
print vince.courses
print vince.age
print vince.sex
##New classes from old
---
#We can use a class to create new classes:
class Math_Student(Student):
favourite_class = "Mathematics"
#Let us create another instance
becky = Math_Student(["Mathematics", "Biology"], 29, "Female")
#This class has the attribute of the inherited class:
print becky.courses
print becky.age
print becky.sex
print becky.favourite_class
#This class has the methods of the inherited class:
becky.have_a_birthday()
print becky.age
## Summary
---
- Classes
- Attributes
- Methods
- Inheritance
## Advantages of OOP
---
- Simplicity
- Modularity
- Modifiability
- Extensibility
- Re-usability
## Another important thing
---
## Libraries (built in)
---
- [csv](http://docs.python.org/2/library/csv.html)
- [math](http://docs.python.org/2/library/math.html)
- [random](http://docs.python.org/2/library/random.html)
- [...](http://pypi.python.org/pypi)
## Libraries (not built in)
---
- [matplotlib](http://matplotlib.org/)
- [scipy](http://www.scipy.org/)
- [sage](http://www.sagemath.org)
- [easy to create your own](http://docs.python.org/2/tutorial/modules.html)
## Important programming ideas
---
- Version control (git and github)
- Test driven development