Python Training Part 3 (of 4)

In my ongoing series on EVERY business person should learn a programming language… and that language should be Python…   this is part 3 of 4.   Like prior trainings, this should be done in order.  You should already have python 2.6 installed, and be able to create files and invoke idle from either the shell or the gui.

Today’s lesson is on “classes”… classes are a very important concept in Python (and almost any programming language).   They enable you to write much more readable and useful code…. most importantly they enable you to build complex systems that ‘build on top of each other’ using either member variables of classes or inheritance or both.

A class can be thought of as simply a “container” for one or more “variables” and one or more “methods”.
Those variables are called ‘member variables’ because they belong “in the class”.
Those methods are called ‘class methods’ or sometimes called ‘member functions’ because they (almost always) act on or use the member variables of that class.

An object is an instantiation of a class… e.g. while a class “describes” what are it’s member variables and member functions…   an object is one instance (e.g. one of potentially many) class objects.

Okay, enough mumbo-jumbo, let’s get some hands-on!

1. First, create a file called location_classes.py somewhere in your library include path (C:python26 works)

2. In that file, put the following very simple class:
class Location(object):
    #MemberVariables
    #x    #y    #z
    def __init__(self,x,y,z):
        self.x = x
        self.y = y
        self.z = z

# this is one of the most basic classes possible, it has 3member variables, x, y, z, and one member function called “__init__”.   “__init__” is a special member function that is called when an instance is created.
Now, let’s use it.

3. Next, from within idle, type the following commands

from location_classes import Location
l21 = Location()  #this fails!   In our __init__ we required x,y,z to be set!
l2 = Location(3,4,5)
l1 = Location(0,0,0)
print l2
print l1
print l1.x
print l2.z

#notice the “dot” notation to access your instance member variables (l2 is an instance of class Location)
#notice how l1 is seperate from l2, but both are the same class?
#cool right? 🙂
#you havn’t seen the least of it!

4. Now, change your class code to be as follows:
import math
from datetime import datetime

class Location(object):
    #MemberVariables
    #x    #y    #z
    def __init__(self,x=0,y=0,z=0):
        self.x = x
        self.y = y
        self.z = z
     
    def __str__(self):
        return “X: %f, Y: %f, Z: %f” % (self.x,self.y,self.z)

    def distance(self,destination):
        xDiff = destination.x – self.x
        yDiff = destination.y – self.y
        zDiff = destination.z – self.z
        return math.sqrt(math.pow((xDiff),2) + math.pow((yDiff),2) + math.pow((zDiff),2))

#notice we’ve done 3 things.. we’ve set some ‘default values’ to the __init__ function, we’ve added 2 new member functions __str__ and distance.  __str__ is a special one that defines that classes string representation.   let’s try it!
5. Close Idle, and restart it… (you have to do this, or your classes may not get reloaded correctly).  type the following into the new idle window
from location_classes import Location
l21 = Location()  #this succeeds now!!!
print l21
l2 = Location(3,4,5)
l1 = Location(0,0,0)
print l2
print l1
print l1.x
print l2.z

print l1.distance(l2)  #notice it did the distance math from l1 to l2!  cool right?

#play around with this…
l1.z=55
print l1.distance(l2)

#and try stuff like this
l21 = l2
print l21
print l2

6. Okay, now to learn about including a class into a class… this is NOT inheritance, it is instead, making a class a member variable of another class!   (We’ll learn inheritance later).   For now, update your location_classes.py file to be as follows:

import math
from datetime import datetime

class Location(object):
    #MemberVariables
    #x    #y    #z
    def __init__(self,x=0,y=0,z=0):
        self.x = x
        self.y = y
        self.z = z
     
    def __str__(self):
        return “X: %f, Y: %f, Z: %f” % (self.x,self.y,self.z)

    def distance(self,destination):
        xDiff = destination.x – self.x
        yDiff = destination.y – self.y
        zDiff = destination.z – self.z
        return math.sqrt(math.pow((xDiff),2) + math.pow((yDiff),2) + math.pow((zDiff),2))

def vectorTo(origin,destination,speed):
    if speed==0:
        return origin
    dist = origin.distance(destination)
 
    dx = (destination.x – origin.x) / dist
    dy = (destination.y – origin.y) / dist
    dz = (destination.z – origin.z) / dist

    x = origin.x + dx * speed
    y = origin.y + dy * speed
    z = origin.z + dz * speed
 
    return Location( x, y, z )

#a boat is defined by its length, width, height, type-code and position and heading (point boat is moving towards)
class Boat(object):
    #Member Variables
    #length = 0    #width = 0    #height = 0    #boat_type = 0    #position = Location(0,0,0)    #heading = Location(0,0,0)

    def __init__(self,boat_type):  #makes boat_type required
        self.length = 0
        self.width = 0
        self.height = 0
        self.position = Location(0,0,0)
        self.heading = Location(0,0,0)
        self.boat_type = boat_type

    def move_towards_heading(self, speed):
        if (self.position.distance(self.heading) <= speed):
            print “Will arrive”
            self.position = self.heading
            return True
        else:
            #move towards goal
            self.position = vectorTo(self.position, self.heading, speed)
        return False

## Notice We’ve made a function (vectorTo) which is used in a new member function of class Boat… (move_towards_heading)…
### Notice that the Boat class has 2 member variables that are a Location type!  And that the move_towards_heading updates the position vectors of the Boat class!  Cool right?

7. Let’s play with our new boat! 🙂  From python idle command line type:
from location_classes import Boat
ab = Boat(1)  #a boat of type 1
ab.heading = Location(5,5,5)
print ab.position
print ab.position.distance(ab.heading)
ab.move_towards_heading(1)
print ab.position
print ab.position.distance(ab.heading)

ab.move_towards_heading(speed = 1) #note that i said speed=1 here, but i didn’t have to, I could have just said 1, but I wanted to show you how in a function call you can specify which parameters are what…

print ab.position
print ab.position.distance(ab.heading)

ab.move_towards_heading(1)
print ab.position
print ab.position.distance(ab.heading)

#can you see our boat moving?  I can!   It’s moving!!!!

8. Okay, time to learn about inheritance!   We need TIME!  Time, I say, time! Make your location_classes.py file look like this:

import math
from datetime import datetime

class Location(object):
    def __init__(self,x=0,y=0,z=0):
        self.x = x
        self.y = y
        self.z = z
     
    def __str__(self):
        return “X: %f, Y: %f, Z: %f” % (self.x,self.y,self.z)

    def distance(self,destination):
        xDiff = destination.x – self.x
        yDiff = destination.y – self.y
        zDiff = destination.z – self.z
        return math.sqrt(math.pow((xDiff),2) + math.pow((yDiff),2) + math.pow((zDiff),2))

def vectorTo(origin,destination,speed):
    if speed==0:
        return origin
    dist = origin.distance(destination)
 
    dx = (destination.x – origin.x) / dist
    dy = (destination.y – origin.y) / dist
    dz = (destination.z – origin.z) / dist

    x = origin.x + dx * speed
    y = origin.y + dy * speed
    z = origin.z + dz * speed
 
    return Location( x, y, z )

#a boat is defined by its length, width, height, type-code and position and heading (point boat is moving towards)
class Boat(object):
    #Member Variables
    #length = 0    #width = 0    #height = 0    #boat_type = 0    #position = Location(0,0,0)    #heading = Location(0,0,0)

    def __init__(self,boat_type):  #makes boat_type required
        self.length = 0
        self.width = 0
        self.height = 0
        self.position = Location(0,0,0)
        self.heading = Location(0,0,0)
        self.boat_type = boat_type

    def move_towards_heading(self, speed):
        if (self.position.distance(self.heading) <= speed):
            print “will arrive”
            self.position = self.heading
        else:
            #move towards goal
            self.position = vectorTo(self.position, self.heading, speed)
        return self.position
 
class Location4d(Location):
    t = datetime.now()
    def __init__(self,x,y,z,t):
        super(Location4d, self).__init__(x,y,z)
        if t > 0:
            self.t = t

    def __str__(self):
        return “X: %f, Y: %f, Z: %f, T: %s” % (self.x,self.y,self.z,self.t)

## notice we added a new class Location4d, and it inherited Location!   up till now, we’ve been inheriting “object” which is actually a very base class that gives us ability to call super  ( we didn’t have to do this, we could have called  class Location()  but then we wouldn’t have had access to the super function, which can be really helpful. )

### Also notice that since we inherited from Location class, that we actually have an x, y, z already as member variables, and we added t  (time!).

### We’ve over-ridden the __str__ function (by having defined ou own) and added to the __init__ function (using super)

#### let’s play with it.

9. In your command shell  (idle) type the following:

from location_classes import Location4d
l4 = Location4d(0,0,0,0)
print l4
l3 = Location4d(4,5,6,0)
l4.distance(l3)
l3.distance(l4)
#  notice we called the distance function?   how you say?  simple, we inherited not only the member variables, but also the member functions!   Cool right?

10. What else can you do with classes?
Turns out you can do a lot just with these few things I’ve showed you… but there is so much more too!  Creating classes of classes of classes, you could model the universe!
Most libraries you use will start with a class as well!  So knowing how to ‘instantiate’ a class instance is key  * you did this many times when you said l4=Location4d(0,0,0,0) for example!

So, here’s your homework!!!

Create a new class called Rectangle…  make sure it inherits from Location or Location4d  (your choice… yes, deep inheritance is possible, as is multiple inheritance..e.g. a location and a location 4d… although that makes no sense here).

Now, write a member function to return the area of the rectangle.

Now, write a member function to ‘move’ the rectangle from one position to another position at a given speed.

Now, write a program that asks for length and width and prints the area of the rectangle.

That’ll do it!  Enjoy!

Python Part 2: Learn a Programming Language.. dang it!

Continuing in my series where I try to convince you to learn a programming language… let me just say that Python can be used for a large number of very useful analytical things… like analyzing sales data, analyzing survey data, and much, much more!  

Without further ado, here is Part 2, to the “Quick Python Training by Harlan” series.
Here’s the link to part 1… (prerequisite is required): http://fastai.com/blog/2013/10/18/why-everyone-should-learn-programming/

This week you will learn: Intermediate Python…   Libraries, Dictionaries, Lists, Time, and more.

You will also learn about files, paths, and such…  here we go!

  1. First, you will need to be able to run python from a command line… on a PC, click Start->run->CMD   then in a command shell, type cd c:python26  <enter>  (or the path to where you installed python), then type python.exe   (you should be at the shell).  type quit() to exit the shell.
    1. on MAC, just open the terminal, and type python, and it should work.
  2. Now, we need to learn how to make a file that python can run…   from command line type:
    1. notepad hi.py (PC)  or    on mac.. do vi hi.py  
    2. in notepad type: print “Hello!” then alt-file-save alt-file-exit.  
      1. on mac, type i  then type print “Hello!”, then press escape, then type :wq  <press enter>
    3. now, from your command line type python hi.py
      1. SEE THE OUTPUT! 🙂  you just made a python program !
  3. Okay, next let’s do some FILE INPUT OUTPUT to learn about libraries.
    1. make a file called  helloname.py  that looks like this:
import sys, os, glob

from optparse import OptionParser, make_option
import csv

def main():
    help = “Read the name of person and print hello persons name”
    args = “usage: %prog -n = name”
    parser = OptionParser(args)
    parser.add_option(‘–path’, ‘-n’, dest=’name’, help=’name of person’)
    (options, args) = parser.parse_args()
    name = options.name

    print “Hello”, name

main()

#run this with python helloname.py -n Harlan

    4.  Now, lets do some outputting to a file!   make a new file called helloname_to_out.py

import sys, os, glob

from optparse import OptionParser, make_option
import csv

def print_hello_name_to_file(name):
    afile=open(“namefile.txt”, ‘wb’)
    afile.write(“Hello %s!” % name)
    afile.close()
    return afile

def main():
    help = “Read the name of person and print hello persons name”
    args = “usage: %prog -n = name”
    parser = OptionParser(args)
    parser.add_option(‘–path’, ‘-n’, dest=’name’, help=’name of person’)
    (options, args) = parser.parse_args()
    name = options.name

    file = print_hello_name_to_file(name)
    print “done check the file”, file

main()

#run this with python helloname_to_out.py -n Harlan

   5. Time to play with time… try this file: hitime.py

import sys, os, glob
from datetime import datetime

from optparse import OptionParser, make_option
import csv

def print_hello_name_to_file(name):
    afile=open(“namefile.txt”, ‘wb’)
    afile.write(“Hello %s! ” % name)
    now=datetime.now()
    afile.write(“It is now: %s” % now)
    afile.close()
    return afile

def main():
    help = “Read the name of person and print hello persons name”
    args = “usage: %prog -n = name”
    parser = OptionParser(args)
    parser.add_option(‘–path’, ‘-n’, dest=’name’, help=’name of person’)
    (options, args) = parser.parse_args()
    name = options.name

    file = print_hello_name_to_file(name)
    print “done check the file”, file

main()

#run this with python hitime.py -n Harlan

   6. Okay now time for some lists!  Let’s learn these in idle!  start idle in windows start->run->idle   or mac: from terminal type: idle
      #okay, now you can type stuff into idle to go along… and learn about lists
      firstlist = [1,2,3,4]
      print firstlist
      print firstlist[0]
      print firstlist[2]
      print firstlist[4]

      #now try this
      list2=[1,2,”3″,”hi”,[“a”,”b”,”c”]]
      print list2
      print list2[3]
      print list2[4]
      print list2[4][2]

  7. now then, on to dictionaries
        dict1={1:’one’,2:’two’,3:’three’}  
        print dict1
        print dict1[2]
        print dict1[0]
   #and an advanced one
       dict2={‘numbers’:[1,2,3], ‘letters’:[‘a’,’b’,’c’], ‘name’:”Harlan”, 5:’Five!’}
       print dict2[5]
       print dict2[‘numbers’]
       print dict2[‘numbers’][0]

   8. finally, lets make our own library and import it!
   #in notepad make a file called: namefromfile.py
import os
 
import os
 
def getname(afilename):
    afile = open(afilename,’r’)
    namelist = afile.readline()
    names_in_list = namelist.split(‘ ‘)
    if len(names_in_list) > 1:
         name=names_in_list[1]
    else:
         name=names_in_list[0]
    return name          

   #save this, now make a new file called   hinamefromfile.py
import sys, os, glob

from optparse import OptionParser, make_option
from namefromfile import getname
import csv

def main():
    #help = “Read the name of person and print hello persons name”
    #args = “usage: %prog -n = name”
    #parser = OptionParser(args)
    #parser.add_option(‘–path’, ‘-n’, dest=’name’, help=’name of person’)
    #(options, args) = parser.parse_args()
    #name = options.name

    name = getname(‘namefile.txt’)

    print “Hello”, name

main()

  #run this with: python  hinamefromfile.py
 

9. OKAY HOMEWORK TIME!!!  This will require research… which is a MAJOR part of any programming language!!!  but you have the basics to do this!

first, create this file called “harlansdictionary.csv”, it should contain the following
Hungry,Honkin Hungry
Angry,Mad As Hell
Happy,Gleed Myself
Sad,Sobbin Myself

Now, write a program that takes any sentence, and replaces any word found in the first column, with Harlan’s version on the right.  For fun, feel free to add to the dictionary!

NOTE: you must load the dictionary fresh on each time the program runs!
HINT: you might use    import csv   (research it!)  will help a lot.
HINT2: you might use dictionaries
HINT3: you might use split() function as in today’s teaching.

YOU CAN DO IT!
   

Why everyone should learn a Programming Language & How to learn Python!

I think everyone should learn a programming language.  It teaches the importance of order, of ‘proper’ order.  It teaches good planning skills.  It teaches discipline.  It teaches self-learning… and IT IS PRACTICAL!    You would be surprised how often it could be helpful for you to know how to program something up real quick!

So, which language should you learn? My opinion: Python!   Specifically Python 2.6.    I will be posting here in my blog a mini-series of how to learn python.  This is part 1 of 4:  Basic Python

Python Basics  “Hello World”,  If I am Cool, “Hello World”,  Forever “Hello World”, 100 “Hello Worlds”.

This whole thing should take you no more than 30 minutes….

1.  Download and install python for your MAC or PC:  (just use the installer!)
http://www.python.org/download/releases/2.6/

2. NEVER BE AFRAID TO SEARCH THE DOCUMENTATION!!!!
http://docs.python.org/2.6/index.html

3. Breeze through a few of these Python Training Slides.. (just go through quickly….  you only learn programming by doing… so go do #4 ASAP!)
http://www.slideshare.net/ahmetbulut/programming-with-python-week-1
http://www.slideshare.net/ahmetbulut/programming-with-python-week-2
http://www.slideshare.net/ahmetbulut/programming-with-python-week-3
http://www.slideshare.net/amiable_indian/introduction-to-python
http://www.slideshare.net/amiable_indian/introduction-to-python-part-two

4. Do the following code in a file for practice… and do the homework below.

print “hello world”

a=1

print a

a=”b”

print a

b=5

print b

a=b

print a

message=”harlan is cool”

cool=True

if cool:

    print message

cool=not cool

if cool:

    print message

cool=not cool

if cool:

    print message

dancer=True

if cool and dancer:

    print message

    

if cool or dancer:

    print message

#while True:

#    print “hello world”

#for i in range(1,101):

    #print i, “hello world”

name=raw_input(“what is your name?”)

print “hello %s” % name

number=raw_input(“how old are you?”)

if int(number) < 5:

    print “you are younger than 5”

elif int(number) < 25:

    print “you are younger than 25”

else:

    print “you are older than 25”

    

”’Homework

Due by next week… write a program that prints    ___ is an even number…

   for every number from 1 to 1000.. then asks user to put in any number

      checks if it is even, and if so.. prints  __ is an even number

       if not prints ___ is NOT an even number.

       * bonus points if you handle 0 correctly!

”’