python-tutorial



python-tutorial

0 0


python-tutorial

Reveal.js presentation about Python basics

On Github tayden / python-tutorial

Python Functions Tutorial

Basics

# String
person = "Douglas Adams"

#Integer
a = 3

#Float
b = 6.0

Basics

Array types

# LIST
a = [1, 2, 3, "dog"]

# these are mutable
a[0] = 9 #[9, 2, 3, "dog"]


# TUPLE
b = (1, "fish", 9.1)

# these are immutable
b[1] = "pony" # Error!

Dicts (key-value lookups)

person = {name: "Rob", profession: "Delivery guy"}

Accessed by key

print person.name
print person['name']

output>> "Rob"
output>> "Rob"

Nested types

Types can be combined to help represent more complex data structures

Lists of lists

Common for representing matrices

matrix_keanu = [
    [0,0,0],
    [0,0,1],
    [0,1,0],
    [0,1,1]
]

... can also be written

matrix_keanu = [[0,0,0], [0,0,1], [0,1,0], [0,1,1]]

Dict arrays

Common for representing tabular data

powerrangers = [
    {color: "Red", zord_rating: 7 },
    {color: "Black", zord_rating: 8 },
    {color: "Pink", zord_rating: 9 },
    {color: "Blue", zord_rating: 2 }
]

For loops

for n in [1, 2, 3, 4, 5, 6]:
    print n

output>> 1
output>> 2
...
output>> 6

syntax:

for [var-name] in [iterable]:
    [Do something with var-name]

iterables are typically lists or tuples.

Nested loops

You can do anthing you want in the [Do something] part of the loop, including call more loops

quads = [
  [1,2,3,4],
  [5,6,7,8]
]

for item in quads:
    # item is [1,2,4,8], then [1,3,9,27].
    for n in item:
        print n*2, # trailing comma makes print not add a newline
        print ", ",

    print # print a newline


output>> 2, 4, 6, 8,
output>> 10, 12, 14, 16,

While loops

i = 3

while(i > 0)
    print i
    i -= 2

output>> 3
output>> 1

List comprehension

A compact for loop for working with lists/tuples

numbers = [1,2,3,4,5,6,7,8,9,10]

odds = [n for n in numbers if n%2 == 1]
print odds

output>> [1,3,5,7,9]

Conditionals

Used to execute code if a condition is met

a = 2

if a > 2:
    print "a is greater than 2"

elif a == 4:
    print "a is 4"

# can add more elif statements here if desired

else: # All tests failed
    print "there is no 'truth' in the world"


output>> "there is no 'truth' in the world"

Nesting conditionals

powerrangers = [
    {color: "Red", zord_rating: 7 },
    {color: "Black", zord_rating: 8 },
    {color: "Pink", zord_rating: 9 },
    {color: "Blue", zord_rating: 2 }
]

for ranger in powerrangers:
    if ranger.zord_rating > 7:
        print ranger.color


outputs>> "Black"
outputs>> "Pint"

Functions

Functions abstract away complex operations and prevent rewriting code you've already written.

Function definitions

# add two numbers and print the result
def add(a, b):
    print a+b

# call function
add(1, 2)


output>> 3

Functions that return

Reusable functions typically return a value so it can then be used as the input to another function

# add two numbers and print the result
def add(a, b):
    return a+b

# call function
result = add(1, 1)
result = add(1, result)
print result

output>> 3

Function with default parameters

A function may have a default value like This

# add two numbers and print the result
def add(a, b=10):
    return a+b

# call function
print add(1)

print add(1, 2)

output>> 11
output>> 3

Classes

A definition of an object - something that contains attributes and functions to abstract away complexity

class Person:
    def __init__(self, name)
        # A special function that creates new objects
        self.name = name

    def nameStartsWithT(self):
        return upper(self.name[0]) == "T"

# Create object from class definition
me = Person("Taylor")

# Call Class function on object
me.nameStartsWithT() # Returns True

Classes - another example

class Restaurant:
    def __init__(self, name, capacity):
        self.name = name
        self.capacity = capacity
        self.currentDiners = 0

    def addTable(self, patrons):
        self.currentDiners += patrons

    def atCapacity(self):
        self.currentDiners >= self.capacity

Everything is an object

  • In Python, everything is an object

  • This means that pretty much everything has some inherent functions attached

# String functions
print "fish, dog, pony".split(",")

output>> ["fish", "dog", "pony"]

# Dict functions
some_dict = {person:"Guido", profession:"Programmer"}

print some_dict.keys()
output>> ["person", "profession"]

print some_dict.values()
output>> ["Guido", "programmer"]

and many more!

API calls

"Application programming interface"

  • Functions and classes that have been defined by someone else
  • You just worry about the inputs and outputs

Shapely API example

class Polygon(exterior[, interiors=None])

from shapely.geometry import Polygon
polygon = Polygon([(0, 0), (1, 1), (1, 0)])
polygon.area

output>> 0.5
  • interiors parameter is optional.
  • Documentation describes format for exterior and the methods a Polygon has

Useful GIS APIs/libraries

From Carson Farmer's website:

  • pandas - For data handling and munging
  • shapely - For geometry handling
  • cartopy - For plotting spatial data
  • geopy - For geolocating and things like that
  • ogr/gdal - For reading, writing, and transforming geospatial * data formats
  • pyqgis - For anything and everything GIS
  • fiona - For making it easy to read/write geospatial * data formats
  • matplotlib - For all my plotting needs
  • networkx - For working with networks (duh!)
Python Functions Tutorial