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.


Basics

IDE

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. http://ironpython.codeplex.com/ 
  2. NetBeans. Haven't tried this yet. http://plugins.netbeans.org/plugin/56795/python4netbeans802   
  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: https://www.jetbrains.com/pycharm/download/download-thanks.html?platform=windows . I want a powerful Python w/ web development IDE. I really like this one!

Indenting

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

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


Importing

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
sys.exit()

Comments

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

Conditionals

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"

Output:
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: http://www.pydanny.com/why-doesnt-python-have-switch-case.html 

Conversions

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

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

Output:
Decimal 1.25  Integer 1

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

Try ... catch


try:
     statements
except (optional Exception type here):
     handle error

example

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

output:
could not convert string to float: haha

functions

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

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

ex
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")

Assertions

assert booleanStatement
example
assert name=="Mak"

Loops


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

Slicing


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


Examples

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])

#reversed
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]



Strings


Formatting

1.
input = raw_input("What's the word? ")
length = len(input);
 #named arguments
print "{input} has {length} chars".format(input=input, length=length)
 #positions
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()

Parsing

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




Classes


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
    @staticmethod
     def BuildMyClass():
         return MyClass()

You'd use it like MyClass.BuildMyClass()

3. Constructor = def __init__():

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

EXAMPLE
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

IO

create directory
import os
os.makedirs("folder1/subfolder1")

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
3. UPDATE:
arr.append("Mac")
4.DELETE:
arr.remove(key)
arr.pop()

5. Checking if a key exists
-arr.__contains__(key)
-key in arr

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


Associative array

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

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

#updating
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")

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



Output
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 = datetime.datetime.now()
print "The year is {0}".format(now.year)
print "20 years from now is {0}".format(now.year + 20)   

output
The year is 2016
20 years from now is 2036


Specific tasks

Opening a URL

response = urllib2.urlopen("http://api.open-notify.org/astros.json")

Getting and parsing JSON

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

response = urllib2.urlopen("http://api.open-notify.org/astros.json")
data = json.loads(response.read())

#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: http://stackoverflow.com/a/8959399/1538717

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("https://api.flickr.com/services/feeds/photos_public.gne?tags=dogs")
    images = []
    for entry in feed["entries"]:
        for link in entry["links"]:
            if (link["type"] == "image/jpeg"):
                images.append(link["href"])
    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 https://pypi.python.org/pypi/bcrypt/2.0.0#downloads 

Website directory
  1. https://docs.python.org/2/library/ 
  2. Twilio - Phone voice and SMS API - https://www.twilio.com/docs/python/install  
  3. Learn Python the Hard way: http://learnpythonthehardway.org/book/index.html 
  4. Hosting: PythonAnywhere.com 
  5. Google Python Style Guide https://google.github.io/styleguide/pyguide.html 

No comments:

Post a Comment

There was an error in this gadget