Search notes:
Python code snippets
misc - copy_array.py
a = [ 'one', 'two', 'three', 'four' ]
# Make a copy of a. Note: not a deep copy because references within
# point to the same object.
# In order to make a deep copy, use copy.deepcopy
#
a_copy = a[:]
# Create a reference to the array pointed at by 'a'.
a_ref = a
a_copy.append('five')
a_ref .append('FIVE')
print(a_copy) # ['one', 'two', 'three', 'four', 'five']
print(a_ref ) # ['one', 'two', 'three', 'four', 'FIVE']
print(a ) # ['one', 'two', 'three', 'four', 'FIVE']
misc - pass_by_value_or_reference.py
#/usr/bin/python
#
# Does python pass by value or by reference?
#
# Output of program is
#
# B[two] = 2
# B[one] = 1
#
#
def f(X, k, v):
X[k] = str(v)
A=dict()
f(A, 'one', 1)
B=A
f(A, 'two', 2)
for k in B:
print " B["+k+"] = " + B[k]
misc - callback_functions_with_arguments.py
def math_op(func, operand_1, operand_2): return func(operand_1, operand_2)
def plus(a, b): return a+b
def mult(a, b): return a*b
print (math_op(plus, 4, 5)) # 9
print (math_op(mult, 4, 5)) # 20
filecmp - script.py
import filecmp
if filecmp.cmp('a.txt', 'b.txt'):
print "a.txt == b.txt"
else:
print "a.txt != b.txt"
if filecmp.cmp('a.txt', 'c.txt'):
print "a.txt == c.txt"
else:
print "a.txt != c.txt"
libraries - Python-Image-Library - pixels.py
import Image
im = Image.new('RGB', (256, 256), "black")
pixels = im.load()
for x in range(0, 256):
for y in range(0, 256):
pixels[x, y] = (x, y, 127)
im.show()
im.save('pixels.png')
statements - for_in.py
d = {'foo': 42,
'bar': "forty-two",
'baz': None}
print
for k in d:
print " ", k, " = ", d[k]
print
print "Using items()"
for k,v in d.items():
print " ", k, " = ", v
statements - continue.py
for a in range(1, 10):
# Don't print the numbers 5 and 7
if a == 5 or a == 7: continue
print a
statements - yield.py
def Y():
print ('yiedling foo')
yield 'foo'
print ('yielding bar')
yield 'bar'
print ('yielding baz')
yield 'baz'
for y in Y():
print ('y: ' + y)
# yiedling foo
# y: foo
# yielding bar
# y: bar
# yielding baz
# y: baz
def YY():
for i in ['FOO', 'BAR', 'BAZ']:
print ('yielding ' + i)
yield i
for yy in YY():
print ('yy: ' + yy)
# yielding FOO
# yy: FOO
# yielding BAR
# yy: BAR
# yielding BAZ
# yy: BAZ
def YYY():
for i in [1, 2, 3, 4, 5, 6]:
if i != 3:
print ('yielding ' + str(i))
yield i
else:
return
# Note:
# numbers 3 through 6 are not printed.
for yyy in YYY():
print 'yyy: ' + str(yyy)
# yielding 1
# yyy: 1
# yielding 2
# yyy: 2
statements - import - __import__.py
#!/usr/bin/python
FooBarBaz=__import__("FooModule")
print (FooBarBaz.module_func_sum(38,4)) # 42
statements - import - import_03.py
#!/usr/bin/python
import FooModule as f
print (f.BarModule.bar_func_4())
statements - import - from_X_import_ALL.py
#!/usr/bin/python
from FooModule import *
print module_func_sum (38,4) # 42
print module_func_mult(21,2) # 42
statements - import - import_02.py
#!/usr/bin/python
from FooModule import BarModule
print (BarModule.bar_func_4()) # 4
statements - import - BarModule.py
def bar_func_4():
return 4
statements - import - from_X_import.py
#!/usr/bin/python3
from FooModule import module_func_sum
print(module_func_sum (38,4)) # 42
# print FooModule.module_func_mult (38,4) # NameError: name 'FooModule' is not defined
# print module_func_mult(21,2) # NameError: name 'module_func_mult' is not define
statements - import - import_01.py
#!/usr/bin/python
import FooModule
print (FooModule.module_func_sum (38, 4)) # 42
print (FooModule.module_func_mult(21, 2)) # 42
print (FooModule.BarModule.bar_func_4())
# print module_func_sum(38,4) # NameError: name 'module_func_sum' is not defined
statements - import - import_04.py
#!/usr/bin/python
from FooModule import *
print (module_func_sum(8, 9)) # 17
statements - import - FooModule.py
import BarModule
def module_func_sum(a, b):
return a+b
def module_func_mult(a, b):
return a*b
statements - pass.py
def X():
pass
def Y():
global y
pass
y = 42
X()
Y()
print y # 42
standard-library - SimpleHTTPServer - script.py
import SimpleHTTPServer
import SocketServer
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("", 8888), Handler) # Listen at port 8888
httpd.serve_forever()
standard-library - Tkinter - draw_image.py
# Note, Python 3 has lowercase Tkinter.
import Tkinter
tk = Tkinter.Tk()
canvas = Tkinter.Canvas(tk, width = 200, height = 200)
canvas.pack()
canvas.create_rectangle( 20, 20, 180, 180, fill="orange")
canvas.create_line( 10, 10, 190, 190, fill="blue")
canvas.create_line( 10, 190, 190, 10)
Tkinter.mainloop()
standard-library - collections - script.py
#/usr/bin/python
import collections
cnt=collections.Counter()
for word in "foo bar baz more or less foo most foo even more foo or is it less".split():
cnt[word]+=1
print "for word in cnt"
for word in cnt:
print " %-10s: %d" % (word, cnt[word])
print "\nfor word in cnt.most_common(3)"
for word in cnt.most_common(3):
print " %-10s: %d" % word
print "\nsum(): "
print " There are " + str(sum(cnt.values())) + " words in the original string"
standard-library - site - script.py
#!/usr/bin/python
import distutils.sysconfig
import site
import sys
print "\nsite.getsitepackages():"
for dir in site.getsitepackages():
print " " + dir
print "\n Compare with distutils.sysconfig.get_python_lib():"
print " " + distutils.sysconfig.get_python_lib()
print "\n Compare alse with sys.prefix"
print " " + sys.prefix
classes - member_variables.py
#!/usr/bin/python
class A(object):
def __init__(self, ident):
self.ident = ident
foo ='local variable'
def go(self):
print ("go " + self.ident)
# print foo
a = A('aaa')
print a.ident # aaa
# print a.foo # AttributeError: 'A' object has no attribute 'foo'
# print foo # NameError: name 'foo' is not defined
a.go() # go aaa
builtin-functions - filter.py
def starts_with_b(t):
return t[0] == 'b'
a = ['foo', 'bar', 'baz']
print filter(starts_with_b, a)
# ['bar', 'baz']
print filter(lambda t: t[0] == 'b', a)
# ['bar', 'baz']
print filter(None, [0, 'foo', None, 'bar', 'baz']) # Note: 0 and None will be gone...
# ['foo', 'bar', 'baz']
builtin-functions - map.py
for i in map(lambda λ: λ**2, range(6)):
print(i)
# 0
# 1
# 4
# 9
# 16
# 25
builtin-functions - ord.py
# -*- coding: utf-8 -*-
ord_ = ord(u'־')
hex_ = format(ord_, '04x')
print str(ord_) + ' ' + str(hex_)
builtin-functions - len.py
a = ['one', 'two', 'three', 4, 5]
print len(a) # 5
d = {'foo': 'one', 'bar': 2, 'baz': None}
print len(d) # 3