Python Notes
default
dir()
# List names in current scope.
# Displays objects (variables, dictionaries, etc) and
# its funtionality (methods, etc) that are currently
# defined.
dir(some_dictionary_name)
# List information about an objects.
id(variableName)
# Displays memory location of variable.
hex(id(variableName))
# Display hex value of a variables memory location.
variableName.__repr__
# Display hex value of memory location and type of object.
# Some of pythons data types:
# ---------------------------
# Strings
# Numbers
# Lists
# Dictionaries
# Tuples
# Boolean
# Strings
# -------
dude = "sam the man"
dude = 'sam the man'
dude = 'sam\nthe\nman'
print dude
dude = r'sam\nthe\nman'
# print dude
# Sets variable as raw string, print will not
# interpret the escape sequences (no newline).
dude = """
sam the man from alabam
stuck in a block string
oh damn
"""
print dude
# Multiline string
dude = u'sam the man'
print dude
# Prints unicode variable
str(dude)
# Convert unicode variable to string.
unicode(dude)
# Convert variable to unicode string.
greeting = '안녕하세요'
print greeting
greeting = u'안녕하세요'
print greeting
# ----
# You can see the difference of the two greetings
# inside the python interpreter by using:
# gretting
#
# instead of:
# print greeting
# ----
# Strings are immutable objects:
dude = 'sam the man'
print dude[0]
# Prints first letter of dude.
# dude[0] = 'r'
# Errors as strings are immutable.
# Instead reassign it:
dude = 'ram the man'
# Another example of immutableness:
dude = 'sam the man'
otherDude = dude
print otherDude
otherDude = 'the rude dude'
print otherDude
print dude
guy = 'sam'
girl = 'sally'
couple = guy + ' ' + girl
print couple
# Concatenate strings.
print "Give me my candy!\n" * 8
# Repeat a string eight times.
str(23)
# Convert an integer to string.
int("54")
# Return string as integer.
print "Are you my mommy?" [8:16]
# Slicing a string.
print 'rpsyztwhqobn'[1:12:2]
# Slicing a string in steps of two.
print "Hey baby!".find("baby")
# Find the index where a string starts.
print "I am not your baby!".find('not', 10)
# Find a string and give it a starting point.
# If not found it will return: -1
animal = "Puppies are cuddly. Puppies are cool."
animal.find('Puppies', 10, 37)
# Find a string index given a start and end point.
###############################################
## Find the second occurence of a word by index
def find_second_occ(corpus, findme):
first_occ = corpus.find(findme)
second_occ = corpus.find(findme, first_occ + 1)
return second_occ
greeting = 'Um hello, are you here? Huh hello?'
print find_second_occ(greeting, 'hello')
####
## This could be shortened to something like this:
####
def find_second_occ(corpus, findme):
return corpus.find(findme, corpus.find(findme) + 1)
greetback = 'Who are you and what are you doing in here?'
print find_second_occ(greetback, 'you')
##End-second-occurence
######################
print "Yo dude!".replace('Yo', 'Later')
print "scary scary scary".replace('scary', 'merrily')
# Replace a string.
print 'scary is scary'.replace('scary', 'hairy', 1)
# Replace only the first instance of scary.
print "Split splits on spaces by default".split()
# Split a string by spaces.
# Split splits into a list.
print "Please stop it! Please stop it now!".split('Please')
# Split on string Please.
print "Please stop it! Please stop it now!".split('Please', 1)
# Split on the first Please only.
boyfriend = 'sammy'
bragging = 'My boyfriend is %s' % boyfriend
print bragging
# String formatting with %s.
print "I have a wife %s and a husband %s" % ('Sarah', 'Sammy')
# String formatting with more than one place holder.
orderList = ['cheeseburger', 'fries', 'shake']
len(orderList)
print orderList
print orderList[0]
print len(orderList[0])
# Create a list.
# Get the length of a list
# Print out the list as a list.
# Print the first item in the list.
# Print length of first item. (cheeseburger)
allOrders = [['taco', 'cola'], ['salad', 'water']]
print allOrders[0]
allOrders.append(['tacosalad', 'lemonade'])
allOrders.reverse()
allOrders.pop()
print allOrders
# Create nested list.
# Print the first nested list.
# Append a new order to the list.
# Reverse the order of the list.
# Pop off the last item in the list.
# Print list.
lovers = ['jerrel', 'mike', 'vlado']
lovers.insert(2, 'huong')
del lovers[0]
print lovers
# Create a list.
# Insert new lover in second position.
# Delete lover at 0th position.
# Print lovers list.
mixedList = [20, 'twenty', [7.5, 'plus', 12.5]]
print mixedList
# Create a heterogeneous list.
# List with interger, string, nested list, and float.
birthDates = tuple([1777, 1856, 1952])
print birthDates
Gauss, Tesla, Fravia = birthDates
print Gauss, Tesla, Fravia
# Create a tuple.
# Print the tuple.
# Assign the tuple data to variables with sequence unpacking.
# Print the variables.
animalSet = set(['hamster', 'snake', 'hamster', 'raccoon'])
print animalSet
pettedBefore = set(['snake', 'cat', 'goat'])
animalSet|pettedBefore
animalSet&pettedBefore
animalSet-pettedBefore
pettedBefore-animalSet
# Create a set.
# Print the set.
# Create another set.
# Union two sets with |.
# Intersect two sets with &.
# Difference animalSet with pettedBefore with '-'.
# Difference pettedBefore with animalSet with '-'.
martialArtists = { 'name' : 'Bruce Lee', 'style' : 'Wing Chun' }
print martialArtists['name']
martialArtists.has_key('name')
'name' in martialArtists
print martialArtists.keys()
print martialArtists.values()
print martialArtists.items()
print martialArtists.get('name')
martialArtists['country'] = 'China'
del martialArtists['country']
martialArtists.clear()
# Create a dictionary called martialArtists.
# Print the dictionary.
# Check to see if dictionary has a specific key.
# Another way to see if key is in a dictionary.
# Show keys in a dictionary.
# Display values of the dictionary.
# Print key value pairs of a dictionary as tuples.
# Return value of specific key.
# Add a key value pair to a dictionary.
# Delete an item from a dictionary.
# Clear all data in a dictionary
# Dictionaries:
# Dictionaries use: {}
# Key valued pairs (unordered).
# Their keys have to be unique immutable objects. (strings, numbers, etc)
# The values to keys can changed at anytime.
# if
# elif
# else
# While Loops:
# Break
# Continue
# Pass
# Else
bosses = [ 'Bison', 'Bowser', 'Dr. Wily']
for boss in bosses:
print boss
# Create a list
# Use for loop to print out each item in a list
range(16)
# Print out numbers 0 to 15 as a list.
range(10, 20)
# Print with start and end range.
range(2, 32, 2)
# Start, end, step. (count by two)
for item in range(2, 33, 2) :
print item
try:
a= 0/0
except:
print "Uh oh! Bad programmer"
# Example of a try exception block.
try:
print 'Praise the Lord'
except:
print 'Struck by lightning'
else:
print 'State your request'
finally:
print 'Wake up please!'
# Try block with except, else, and finally.
# Finally will run always.
try:
errorStarter = 0%0
except ZeroDivisionError:
print "Modded by zero... bad girl!"
except:
print "You messed up your code again"
# If you can find the exact error. It will return
# instead of a default exception.
try:
errorStarter = 0%0
except Exception as badCode:
print badCode
# Set results of the exception to be stored
# in a variable, for further exploration.
import sqlite3
conn = sqlite3.connect('/home/myUser/sample.db')
cursor = conn.cursor()
for person in cur.execute("select * from message") :
print person
# Sample connection to sqlite3 database.
fdesc = open("file_test.txt", "w")
for count in range(0, 100) :
fdesc.write(str(count) + "\n")
fdesc.close()
# Open a file for writing, and write to it.
for count in range(300, 400, 2) :
fdesc.write(str(count) + "\n")
fdesc.close()
# Append data to a file
fdesc = open("file_test.txt", "r")
for line in fdesc.readlines() :
print line.strip()
fdesc.close()
# Read a file, and print it.
import os
os.rename("file_test.txt", "test_data.txt")
# Rename a file.
import os
os.getcwd()
os.mkdir("pyepye")
os.listdir("./")
# Import operating system library
# Get current working directory.
# Create a new directory called: pyepye
# List the currenty directory contents "."
for item in os.listdir(".") :
if os.path.isfile(item) :
print item
elif os.path.isdir(item) :
print item + "/"
else:
print "Undefined filetype!"
# List out the files and directories, putting
# a / after directory names.
import os
import glob
for file in glob.glob(os.path.join(".", "*.py")) :
print file
# Print all files ending in .py
# If there are a lot files in a directory
# glob is not efficient.
# Clone a process by forking
# Returns 0 to child process.
# Returns pid of child to the parent process.
# Network Programming
# Client server programming usually depends on
# socket programming.
# TCP and UDP Sockets
# Are usually used for regular servers and clients.
# Raw Sockets
# Used for things like packet sniffing and injection.
# SocketServer
# Is a python framework for creating TCP and UDP servers
print 2**10
# Two to the power of ten.
# Bitwise Operators:
# x|y
# x^y
# x&y
# Logical Operators:
# x and y
# x or y
# not x
## Factorial
def factorial(n):
result = 1
while n>=1:
result = result * n
n = n -1
return result
print 'Factorial of 0:', factorial(0)
print 'Factorial(4):', factorial(4)
##end-factorial
# Immutable -
# Dictionaries - key valued pairs (unordered)
# Forking - cloning a process.
# Tuples - immutable lists with ( ) instead of [ ].
# Sets - unique objects in an unordered collection
# Union -
#
default