Wednesday, February 3, 2016

My #python reference

What is this? I read a book called 57 Exercises for Programmers and used the exercises to learn Python. I took notes as I went along. Here they are.



I tried a few different IDEs and a text editor. I liked PyCharm the best.
  1. Visual Studio has Python support. Need to install Python Tools for Visual Studio. I also installed IronPython. 
  2. NetBeans. Haven't tried this yet.   
  3. IDLE. It's installed when you install Python. Just open it and create a new file. I like it because it works quickly without hassle.
  4. Trying PyCharm: . I want a powerful Python w/ web development IDE. I really like this one!


In C# you have { } to indicate blocks. In Python, you have indents, which you must use for everything.

def MyFunction():
<indent>print "Hello World"


C# "using" equivalent = import. ex: import sys

  1. import decimal
  2. from decimal import Decimal
  3. Alias like this: from decimal import Decimal as D
    1. instead of Decimal("1.25") you can use D("1.25"). This is useful when there are very long names to type 

In this case "decimal" is a module (a .py file) that contains a class called Decimal. 

Exiting a script

import sys


single line = #this is a comment
multiple = """this
is a 
multiple line 


dogName = "Scruffy"
if dogName == "Scruffy":
    print "Woof woof"elif dogName == "Rex":
    print "Bark bark"else:
    print "I have no idea what sound that dog makes"

spoon = Noneif not spoon:
    print "There is no spoon"
catName = ""
if not catName:
    print "You didn't name the cat"

Woof woof
There is no spoon
You didn't name the cat

Notice how the "not" operator worked on both a null object (None) and an empty string? Yeah, that's pretty sweet

Switch/case: Python doesn't have these. Use a dictionary instead. See here: 


from decimal import Decimal
myString = "1.25"myDecimal = Decimal(myString)
myInt = int(myDecimal)

print "Decimal {0}  Integer {1}".format(myDecimal, myInt)

Decimal 1.25  Integer 1

A reusable function checking if a thing is a float
def isfloat(value):
    return True
    return False

Try ... catch

except (optional Exception type here):
     handle error


    first = float("haha")
except ValueError as ex:
    print ex.message

could not convert string to float: haha


def functionName(params):
     string for documentation -- this shows up when you're calling the function
     return something

optional parameters like: def function(name="")

def askName()
     "Prompts the user for their name, then returns the name"
     return raw_input("What's your name? ")

command line inout

print raw_input("Print this")


assert booleanStatement
assert name=="Mak"


1. while loop syntax

input = getInput()
while input.upper() != DONE:
    #parse input
    #do stuff with it
    input = getInput()

Note the colon + indenting of the body of the loop. 

2. For loop syntax

Items = []
Items.append(Item("Computer", 1, 1000.55))

for item in Items:
     print item; 

3. Counting to 10 with a for loop
for i in range(1, 11):
     print i


This is pretty strange if you're coming from a language that doesn't have slicing. After seeing the examples, I'm sure you'll understand how awesome this language feature is. Try writing code in another language and producing the exact the same output, and comparing it to this (including checking boundaries)

The format

a[start:end] # items start through end-1
a[start:]    # items start through the rest of the array
a[:end]      # items from the beginning through end-1
a[:]         # a copy of the whole array
There is also the step value, which can be used with any of the above:
a[start:end:step] # start through not past end, by step


hello = "Hello World"
print "hello[:] prints [{0}]".format(hello[:])

#This won't throw an 'index out of range' exception

print "hello[500:] prints [{0}]".format(hello[500:])

#Neither will this
print "hello[0:500] prints [{0}]".format(hello[0:500])

#from 0 to 5
print "hello[:5] prints [{0}]".format(hello[:5])

#every other character
print "hello[::2] prints [{0}]".format(hello[::2])

print "hello[::-1] prints [{0}]".format( hello[::-1])

This produces
hello[:] prints [Hello World]
hello[500:] prints []
hello[0:500] prints [Hello World]
hello[:5] prints [Hello]
hello[::2] prints [HloWrd]
hello[::-1] prints [dlroW olleH]



input = raw_input("What's the word? ")
length = len(input);
 #named arguments
print "{input} has {length} chars".format(input=input, length=length)
print "{0} has {1} chars".format(input, length)
 #using function pointer
output = "{0} has {1} chars".format
print output(input, length)

2. Uppercasing: stringObject.upper()


1. Split string 
input = "1.00:2.00"
QTY, Price = input.split(":", 1) # : is my delimiter in this particular example


1. Creating a class
Pretty much the same syntax as a function. Need the colon after the class name. Class variables and functions need be indented.

class MyClass:
    "I'm a doc string. Use print ClassName.__doc__"
  def __init__(self):
       self.InstanceVariable = "I'm a class variable"

     def ClassFunction(self):
          "I'm a class function"
           print self.InstanceVariable 

2. Static method

class MyClass
     def BuildMyClass():
         return MyClass()

You'd use it like MyClass.BuildMyClass()

3. Constructor = def __init__():

4. Inheritance
class Parent():
class Child(Parent):

class Parent():
def __init__(self, eyecolor, haircolor):
print "parent cstr called"
self.eyecolor = eyecolor
self.haircolor = haircolor

class Child(Parent):
def __init__(self, eyecolor, haircolor, numberoftoys):
print "child cstr called"
Parent.__init__(self, eyecolor, haircolor)
self.numberoftoys = numberoftoys

Method Overriding - just name the function in the child class


create directory
import os

create file + write to it
with open("folder1/dummy.txt", 'a+') as f:
    f.writelines("One should never utilize the word 'utilize' in writing. Use 'use' instead")

read file
with open(oldFileName, 'r') as f:
    for line in f.readlines():
              print line

Data Structures

Array / List

Arrays and lists are the same thing in python. 
Example: arr = ["Yasmin"]
1. CREATE: arr = ["Yasmin"]
2. READ: 
for a in arr:
    print a

5. Checking if a key exists
-key in arr

6. Operations on all elements in a list: use map()

Associative array

addresses = {
    'Mac':"Mac's house",
    "Bob Saget": 'Full House in SF'}

addresses["Obama"] = "The White House"

addresses["Mac"] = "Mac's new house"

#checking for a value
if addresses.has_key("Bob Saget"):
    print "Evicting Bob Saget"    #deleting    addresses.pop("Bob Saget")

for name in addresses:
    print "{0} lives at {1}".format(name, addresses[name])

Evicting Bob Saget
Mac lives at Mac's new house
Obama lives at The White House

Date & Time

Getting the current date + adding to it 
import datetime
now =
print "The year is {0}".format(now.year)
print "20 years from now is {0}".format(now.year + 20)   

The year is 2016
20 years from now is 2036

Specific tasks

Opening a URL

response = urllib2.urlopen("")

Getting and parsing JSON

import urllib2
import json
import pprint #this stands for Pretty Print

response = urllib2.urlopen("")
data = json.loads(

#pretty printer
pprint.pprint( data)

This outputs
{u'message': u'success',
 u'number': 6,
 u'people': [{u'craft': u'ISS', u'name': u'Mikhail Kornienko'},
             {u'craft': u'ISS', u'name': u'Scott Kelly'},
             {u'craft': u'ISS', u'name': u'Sergey Volkov'},
             {u'craft': u'ISS', u'name': u'Yuri Malenchenko'},
             {u'craft': u'ISS', u'name': u'Timothy Kopra'},
             {u'craft': u'ISS', u'name': u'Timothy Peake'}]}

#parsing into a nice table
def p(name, craft, filler=' '):
    formatString = "{0}|{1}"    print formatString.format(name.ljust(20, filler), craft.ljust(10,filler))

p("Name", "Craft")
p('','', '-')
for line in data["people"]:
    p(line["name"], line["craft"])

This outputs
Name |Craft
Mikhail Kornienko |ISS
Scott Kelly |ISS
Sergey Volkov |ISS
Yuri Malenchenko |ISS
Timothy Kopra |ISS
Timothy Peake |ISS 

Getting and parsing an RSS feed

to install feedparser just do "pip install feedparser".
see here:

This example pulls in the flickr feed, searching for public photos with the tag of "dog"
and then loops through the results and gets all the URLs to the photos
import feedparser

def getImages():
    feed = feedparser.parse("")
    images = []
    for entry in feed["entries"]:
        for link in entry["links"]:
            if (link["type"] == "image/jpeg"):
    return images

Encryption using bcrypt

  1. Install bcrypt using pip by executing the following in the command prompt C:\Program Files\Python2.7\Scripts> pip install bcrypt
  2. use bcrypt - see here 

Website directory
  2. Twilio - Phone voice and SMS API -  
  3. Learn Python the Hard way: 
  4. Hosting: 
  5. Google Python Style Guide 

No comments:

Post a Comment

There was an error in this gadget