Scratchpad – Learning Python

Here are some reference notes I made for myself while learning Python –
hope it is useful for you 🙂

1) General

1.1) Getting User Input

nickname = raw_input("what is your nickname? ")

1.2) Comments

#Single line comment
""" multiline
comment 
example"""

1.3) Exponential

sixty_four = 8 ** 2

1.4) Useful Utility Functions

len(variable) #returns the length of variable, usually used for Lists
str(variable) #return string version of variable, usually for integers, float, etc

Works on all data types

1.5) Pass Placeholder Statement

A placeholder statement for areas when a statement/code block is required, but not ready. Nothing happens when it is executed, which is also useful for stubs/work in progress.

class MyClass():
    pass
# Refer to section below for details on classes

1.6) Printing on Same Line

print "one",
print "two"
#output: one two

2) Strings

2.1) String Indexing

secondLetter = "luppeng"[1]
print(secondLetter) 
#output: u

2.2) String Functions

name = "luppeng.wordpress.com"
print name.isalpha() # test if string consists of letters only
print name.upper()   # returns the string with all upper case characters
print name.lower()   # returns the string with all lower case characters

Works only on Strings

2.3) Variable Substitution in Strings

print "Variable value is %s" % variable
print "Variable values are %s and %s" % (variable1,variable2)

Just like printf in C

3) Date/Time

from datetime import datetime
now = datetime.now()
print now.year,now.month,now.day,now.hour,now.minute,now.second

4) Operators Precedence

Descending order: (), not, and, or

5) Conditional Statements

if [elif] else

6) Modules

6.1) Print all functions in module

import moduleName
allFunctions = dir(moduleName)
print allFunctions

6.2) Importing Modules

Less Desirable

from math import *
print str(floor(4.2)) 
#output: 4.0

Cons:
– Lots of unnecessary variables and functions within application now
– conflict of functions (when two modules have same function name)
– No idea which module a function comes from (accidental dependency removal)

Preferred Methods

import math
print str(math.floor(4.2)) 
#output: 4.0
from math import floor
print str(floor(4.2)) 
#output: 4.0

7) Lists

7.1) List Creation

myList = [...]
multiplesOfThree= [ x for x in range (1,100) if x % 3 == 0]
                 (value)      (range)         (condition)

7.2) List Utility Functions

itemIndex = myList.index("item")
list.sort()

7.3) List Traversal

for item in list:
    #do stuff (not possible to modify the list this way)
for i in range(0, len(myList)):
    #do stuff (can modify the list because we have the index)
#Reverse List Traversal
myList = [...]
print myList[::-1]

7.4) List Manipulation

myList.insert(someIndex, newItem) # the item occupies the index provided. Everything else pushed down by 1 index
myList.remove("item")
myList.append()
myList.pop(index)
myList.remove(item)
del(myList[index]) # like pop() but does not return anything

7.5) Lists Joining

a = ["a1","a2"]
b = ["b1","b2","b3"]
print a + b 
#Output: ["a1","a2","b1","b2","b3"]
b = ["b1","b2","b3"]
print "-".join(b)
#Output: b1-b2-b3

7.6) List slicing

list[start:end:stride]
default values: [0:len(list):1]

8) Dictionary (key-value pairs)

8.1) Dictionary Creation

menu = {"key1":"value1","key2":"value2",...}

8.2) Dictionary Utility Functions

menu["key1"] = "newValue1" #Updating new value for key
del menu[key_name]

8.3) Traversing Dictionary

for key in myDictionary:
    print myDictionary[key] #print all values as it iterates through the key

8.4) Accessing Dictionary

print my_dict.items() --> returns array of tuples, with each tuple being a k/v pair
my_dict.keys() --> returns all keys
my_dict.values() --> returns all values

9) RANGE()

A useful shortcut to generate a list
Synatx: range([start],stop,[step])
Default values:
– start = 0
– step = 1

range(10)     #[0,1,2,3,4,5,6,7,8,9]
range(4,10)   #[4,5,6,7,8,9]
range(4,10,2) #[4,6,8]

10) Loops

10.1) while/else

Similar to if/else, but the else code block will execute when the loop condition is false. Else block will not execute if the loop exits via a break

10.2) for/else

Same as while/else

10.3) Looping List with Enumerate

Pass the enumerate function a list, and it will return an index (starting from 0) and the corresponding list item at the given index.

theList=["c1","c2","c3","c4"]
for element in enumerate(theList):
    print element

#output:
#(0, 'c1')
#(1, 'c2')
#(2, 'c3')
#(3, 'c4')
theList=["c1","c2","c3","c4"]
for index,element in enumerate(theList):
    print str(index) + " -- " + element

#output:
#0 -- c1
#1 -- c2
#2 -- c3
#3 -- c4

10.4) Looping Multiple Lists

“zip”, an built-in Python function, creates tuples of elements at the same index across the lists it was passed as parameters. The zip function is constrained by the shortest list length

listA = [1,2,3,4,5]
listB = [6,7,8,9]
for tuple in zip(listA, listB):
    print tuple

#Output: 
#(1, 6)
#(2, 7)
#(3, 8)
#(4, 9)
listA = [1,2,3,4,5]
listB = [6,7,8,9]
for a,b in zip(listA, listB):
    print max(a,b)

#Output: 
#6
#7
#8
#9

11) FILE I/O

11.1) Open a File in RW mode

The below two code snippets are two different methods to achieve the same thing

my_file = open("filename","r+")  # Open for reading and writing. The stream is positioned at the beginning of the file.
print my_file.read() 
my_file.readline()
my_file.close()
with open("text.txt", "w") as textfile:  # Truncate file to zero length or create text file for writing. The stream is positioned at the beginning of the file.
    textfile.write("success!")

Using with/as will invoke file object’s built in __enter__() and __exit__() methods, which calls the open() and close() functions

11.2) Looping Through a File

 with open("myfile.html", "r") as textfile:  #Open text file for reading. The stream is positioned at the beginning of the file.
    for line in textfile:
        if (line.startswith("Title:")):
            print line 
        elif line and line[0].isalpha():  #check if the first line is a character
            print "Line starts with a character"

11.3) File Modes

The following is a snippet from BSD’s fopen() man page. Credits to https://stackoverflow.com/questions/1466000/python-open-built-in-function-difference-between-modes-a-a-w-w-and-r

r   Open text file for reading.  The stream is positioned at the
    beginning of the file.

r+  Open for reading and writing.  The stream is positioned at the
    beginning of the file.

w   Truncate to zero length or create text file for writing.  The
    stream is positioned at the beginning of the file.

w+  Open for reading and writing.  The file is created if it does not
    exist, otherwise it is truncated.  The stream is positioned at
    the beginning of the file.

a   Open for writing.  The file is created if it does not exist.  The
    stream is positioned at the end of the file.  Subsequent writes
    to the file will always end up at the then current end of file,
    irrespective of any intervening fseek(3) or similar.

a+  Open for reading and writing.  The file is created if it does not
    exist.  The stream is positioned at the end of the file.  Subse-
    quent writes to the file will always end up at the then current
    end of file, irrespective of any intervening fseek(3) or similar

12) Functional Programming

12.1) Anonymous Functions

The following two code samples are similar:

lambda x: x%3 == 0
def by_three(x):
    return x%3==0
#return x if condition is true

Examples – return x if the value is == “PythonLanguage”

lambda x : x == "PythonLanguage"

12.2) filter function

filter (condition to return the value, input list)

13) Bitwise Operators

13.1) Operators

>> right shift
<< left shift
& bitwise AND
| bitwise OR
^ bitwise XOR (bit flipper)
~ NOT

#Left Shift 5 times 
newShiftVariable = shiftVariable << 5

13.2) Binary Number Representation

0b1010 –> decimal 9

13.3) Utility Functions for Bitwise Operations

bin(string) – returns binary representation of the string input
oct(string) – Octal representation
hex(string) – Hexadecimal representation
int(string,[base]) – integer representation, optional second parameter as input’s base

int("0b1010", 2)

14) Classes

14.1) Class Definition Syntax

class ClassName(InheritedClass):
    def __init__(self, a, b, ..): #first keyword is used to reference itself. python convention uses the word "self"
        self.a = a
        self.b = b
        ...

    def otherMethods(self, ...):
        ...

14.2) Superclass

class SportsUtilityVehicle(Vehicle):
    def turboAccelerate(self, param):
        return super(DerivedClass, self).accelerate(param)

14.3) Good Method to Override

__repr__()

Similar to java’s toString() method

End of scratchpad (or is it scratchpost?)

Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s