Python

So I did manage to teach myself Python this year!

Downloaded the binaries from python.org

I took the codecademy Python course and this is what I learned:

Comments
# This is a single line comment
“”” This is a multiline comment …..
…… “””
Variable assignment
var = 1
stringVar = “this is it”
String functions
len(stringVar)
stringVar.upper()
stringVar.lower()
string.isalpha()
Which type is it?
# returns the type
type(4)          # <type ‘int’>
type(4.23)     # <type ‘float’>
type(‘string’) # <type ‘str’>
# use it:
if type(num) == int or type(num) == float  . . .
Number functions
max(1,2,3)
min(1,2,3)
abs(-10)
# cast a number into a string
str(3.14)
Print a variable
print stringVar
print “This is a literal”
print “Concatenate ” + “strings ” + ” using the plus sign”
print “This is how you escape a sign\” “
print “Print this variable %s” % (stringVar)
Date and time
# import the library first
from datetime import datetime
# populate sysdate
now = datetime.now()
print now.day
print now.month
print now.year
print now.hour
print now.minute
print now.second
# print current date mm-dd-yyyy
print ‘%s-%s-%s’ % (now.month, now.day, now.year)
print ‘%s:%s:%s’ % (now.hour, now.minute, now.second)
Input
answer = raw_input(“Type your input here and hit ‘Enter’.”).upper()
Conditions
if answer == “LEFT” :
    print “This is left”
elif answer == “RIGHT” :
    print “This is right”
else:
    print “Neither left nor right”
Comparisons
==
!=
<
<=
>
>=
Booleans
True
False
not True
not False
Functions
def funcName ():
Libraries
#import library
import math
#use library
print math.sqrt(25)
#import only one function from the library
#from module import function
from math import sqrt
#use it; no need to use math. prefix
print sqrt(25)
#import all functions from a module
#from module import *
from math import *
# to see all functions imported from module
import math
print dir(math)
Lists
list1 = [“first”, “second”, “third”]
print list1[0]
list1.append(“fourth”)
print len(list1)
# get a slice to contain the second and third items
# will include the from : to but not including
slice = list1[1:3]
# grab the first two
list1[:2]
#grab the last two
list1[1:]
#find the index for item “third”
list1.index(“third”)
#insert a new item there
list1.insert(2, “new”)
# list comprehension syntax
# populate list with the even numbers between 0 and 60
list1 = [x for x in range(61) if x % 2 == 0]
# slice list
#start at 0 index, end at 5 index, stride (advance) in 2’s
list1[0:5:2]
# go backwards
list1[::-1]
# list functions
list1.append()
list1.remove(item)  #removes item when it finds it
list1.pop(index)     #removes item corresponding to location index
list1.index()
list1.sort()
len(list1)
Loops
# Loop through a list
# after the for, put a variable name to contain the list items
for string1 in list1:
    #print all the items inside list1
    print string1
# Loop through a dictionary
for key in dict1:
    #print all the values in a dictionary
    print dict[key]
# Range loop
for i in range(0, len(list1)):
    list1[i] = list1[i] + 2
or
for in in range(len(list1))
    print list1[i]
# Generate a range:
# range(starting at 0, stop at but not including)
range(3) # [0, 1, 2]
# range(start, stop at but not including)
range(1, 3) # [1, 2]
#range(start, stop at but not including, go in increments of this)
range(1, 10, 2) # [1, 3, 5, 7, 9]
# while loops
while x < 10:
    x += 1
    break # breaks out of the loop.
#while/else loop
# or
# for/else loop
while count < 10:
    ……..
else:
    ……
#The else block will execute when the while condition evaluates to False.
# This happens when count is 10: then else will be executed and the while will not be entered.
# This also happens when the while loop exits normally.
# if the loop exits because of a break then the else does not execute.
Dictionaries
#key:value pairs inside a list with curly brackets
# value can be a number, string, or a list
residents = {} #empty dictionary
residents = {‘Puffin’:104, ‘Sloth’:105, ‘Burmese Python’:106}
print residents[‘Puffin’] #returns 104
residents[‘Tiger’] = 107
#delete key-value pair
del residents[‘Puffin’]
#assign new value to key
residents[‘Tiger’] = 108
residents.items() # returns all the key:value pairs
residents.keys() # returns all the keys
residents.values() # returns all the values
Lambda: Anonymous functional programming
#Instead of function:
def by_three(x):
    return x % 3 == 0
#Do it anonymously
lambda x: x % 3 == 0
Bitwise operators
print 5 >> 4  # Right Shift
print 5 << 1  # Left Shift
print 8 & 5   # Bitwise AND
print 9 | 4   # Bitwise OR
print 12 ^ 42 # Bitwise XOR
print ~88     # Bitwise NOT
# write binary numbers
print 0b1   # 1
print 0b10 # 2
print 0b11 # 3
print 0b100 # 4
Classes
class Animal(object):
    def __init__(self, name):
        self.name = name
        pass
    def __repr(self):
        return self.name
zebra = Animal(“Stripey”)
class Customer(object)
# Inheritance: Returning Customer inherits from Customer
class ReturningCustomer(Customer)
File Input/output
my_file = open(“file_name.txt”, “w”)
mode:
r = readonly
w = write
r+ = read and write
my_file.read()
my_file.readline()
my_file.write(“dkaldjf”)
my_file.close()  # when done.
# check to see if the file is closed
my_file.closed == True
# use with and as to have Python automatically close the files
# with open(“file_name.txt”, “mode”) as variable:
with open(“text.txt”, “w”) as textfile:
    textfile.write(“Success!”)
Web pages
# Import the library below to access Web pages
from urllib2 import Request, urlopen, URLError
request = Request(‘https://datacarton.com/&#8217;)
try:
    response = urlopen(request)
    carton = response.read()
    print carton[559:1000]
except URLError, e:
    print ‘No data.  Got an error code:’, e
#Use the requests library
import requests
# GET  a request
carton = requests.get(‘https://datacarton.com/&#8217;)
print carton.text[559:1000]
# POST  a request
response = requests.post(“http://……&#8221;, data=”mydata”)
# Get the status code of the response
# 1xx: working on request
# 2xx: success
# 3xx: missing something, need something first
# 4xx: error
# 404: file not found
response.status_code
# Get the header information
response.headers
Handling XML
from xml.dom import minidom
Handling JSON
import json

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s