# colourHexSpiral.py
import turtle
colours = ['red', 'purple', 'blue', 'green', 'yellow', 'orange']
t = turtle.Pen()
t.reset()
t.speed(0)
turtle.bgcolor('black')
for x in range(360):
t.pencolor(colours[x%6])
t.width(x/100+1)
t.forward(x)
t.left(59)
# Keep screen displayed
turtle.mainloop()
# textFileIO.py
filename = 'mytextfile.txt'
f1 = open(filename, 'wt') # open text file for writing
f1.write('The quick brown fox jumps over the lazy dog.' + '\n')
f1.write('Now is the time for citizens to come the the aid of their party.' + '\n')
f1.close()
f2 = open(filename, 'at') # open same file to append data
f2.write('A stitch in time saves nine.' + '\n')
f2.close()
f3 = open(filename, 'rt') # open same file for reading
data = f3.read()
f3.close()
lines = data.split('\n')
for line in lines: # print all lines in file
print(line)
# saveLoadSettings.py
import configparser
def updateConfig(filespec, cfObject):
with open(filespec, 'w') as configfile:
cfObject.write(configfile)
#--- First write a new config file ---------------------------------------------
config = configparser.ConfigParser()
config['Paths'] = {}
config['Paths']['Input'] = '/home/pi/Documents/Input'
config['Paths']['Output'] = '/home/pi/Documents/Output'
config['General'] = {}
config['General']['Updated'] = '25/12/2020'
filespec = 'settings.ini'
updateConfig(filespec, config)
print('Config file written: ' + filespec)
#--- Now read whats in config file ---------------------------------------------
config = configparser.ConfigParser()
config.read(filespec)
print(config.sections())
print(config['Paths']['Input'])
print(config['Paths']['Output'])
print(config['General']['Updated'])
# --- Change config value and update config file -------------------------------
config['General']['Updated'] = '26/12/2020'
updateConfig(filespec, config)
print('Updated config file: ' + filespec)
#--- Now read whats in updated config file--------------------------------------
config = configparser.ConfigParser()
config.read(filespec)
print(config['General']['Updated'])
''' Sample settings file - settings.ini
[Paths]
input = /home/pi/Documents/Input
output = /home/pi/Documents/Output
[General]
updated = 26/12/2020
'''
# sorting.py
# sorting Lists using the sort() method
fruits = []
fruits.append('lemon')
fruits.append('apple')
fruits.append('banana')
fruits.append('orange')
fruits.sort()
for fruit in fruits:
print(fruit)
# sorting different data types using the sorted() function
# List
x = ['q', 'w', 'r', 'e', 't', 'y']
print(sorted(x))
# Tuple
x = ('q', 'w', 'e', 'r', 't', 'y')
print(sorted(x))
# String-sorted based on ASCII translations
x = "python"
print(sorted(x))
# Dictionary
x = {'q':1, 'w':2, 'e':3, 'r':4, 't':5, 'y':6}
print(sorted(x))
# Set
x = {'q', 'w', 'e', 'r', 't', 'y'}
print(sorted(x))
# Frozen Set
x = frozenset(('q', 'w', 'e', 'r', 't', 'y'))
print(sorted(x))
# dictionaries.py
def showStaff():
print('Staff List')
print('-----------------------------')
for member in staff:
print(member, '\t', staff[member])
print()
staff = {} # create new dictionary
staff['Mike'] = 'accounts supervisor' # add staff
staff['Sally'] = 'managing director'
staff['Peter'] = 'buyer'
staff['Alice'] = 'distribution manager'
showStaff()
staff['Peter'] = 'chief buyer' # promote Peter
staff['David'] = 'buyer' # add new staff member
staff.pop('Alice') # remove staff member
showStaff()
# parseXML.py
import xml.etree.ElementTree as ET
''' Sample library.xml file
<?xml version="1.0" encoding="UTF-8"?>
<library>
<book>
<title>The War of the Worlds</title>
<author>H. G. Wells</author>
<genre>Science Fiction</genre>
</book>
...
'''
def parseXML(xmlfile):
tree = ET.parse(xmlfile)
root = tree.getroot()
items = [] # make an empty list
for item in root.findall('./book'):
detail = {} # make a dictionary for each item
for child in item:
# use xml tag as key to dictionary
detail[child.tag] = child.text
items.append(detail) # add dictionary to item list
return items # return item list
# parse xml file
filename = 'library.xml'
library = parseXML(filename)
for book in library:
for key in book:
text = book[key]
print(f'{key:10} {text}')
print()
# sinCosTan.py
import math
def getSinCosTan(angle):
radians = math.radians(angle)
print('Angle:', angle, 'is:', f'{radians:.3f}', 'Radians')
sine = math.sin(radians)
cosine = math.cos(radians)
tangent = math.tan(radians)
print('Sine of Angle:', angle, 'is:', f'{sine:.3f}')
print('Cosine of Angle:', angle, 'is:', f'{cosine:.3f}')
print('Tangent of Angle:', angle, 'is:', f'{tangent:.3f}')
asine = round(math.degrees(math.asin(sine)))
acosine = round(math.degrees(math.acos(cosine)))
atangent = round(math.degrees(math.atan(tangent)))
print('Inverse Sine of:', f'{sine:.3f}', 'is:', asine)
print('Inverse Cosine of:', f'{cosine:.3f}', 'is:', acosine)
print('Inverse Tangent of:', f'{tangent:.3f}','is:', atangent)
print()
angle = 45
getSinCosTan(angle)
# getPermutations.py
from itertools import permutations
letters = 'ABCDEFGHIJK'
for n in range(2,5):
combos = list(permutations(letters[:n]))
print(f'Letters: {letters[:n]}')
print('Permutations')
for tuple in combos:
print(tuple)
print()
print('Number of letters Number of permutations')
print('----------------- ----------------------')
for n in range(1,11):
combos = list(permutations(letters[:n]))
print(f'{len(letters[:n]):17} {len(combos):23}')
# timeCode.py
import time
def doSomething(limit):
for n in range(limit):
j = 3**n
print('Timing, please wait ...')
tic = time.perf_counter()
doSomething(30000)
toc = time.perf_counter()
print(f'Seconds elapsed: {toc-tic:0.2f}')
import timeit
lines_of_code = """
def doSomething(limit):
for n in range(limit):
j = 3**n
doSomething(30000)
"""
times = 10 # number of times to test
average = timeit.timeit(lines_of_code, number = times)/times
print(f'Average seconds elapsed: {average:0.2f}')
# formattingDateTime.py
from datetime import datetime
import time
now = datetime.now()
print(f'now: {now}')
print(type(now))
print()
# breaking down datetime.now into components
print(f'formatted datetime: {now.day}/{now.month}/{now.year}' + \
f' {now.hour}:{now.minute}:{now.second}')
print()
# show time as a number
timeAsANumber = time.time()
print(f'timeAsANumber: {timeAsANumber}')
print(type(timeAsANumber))
print()
# formatting date and time using strftime()
print(datetime.fromtimestamp(timeAsANumber).strftime('%Y/%m/%d %H:%M:%S.%f'))
print(datetime.fromtimestamp(timeAsANumber).strftime('%Y/%m/%d %H:%M:%S'))
print(type(datetime.fromtimestamp(timeAsANumber)))
print()
for n in range(10):
now = time.time()
print(datetime.fromtimestamp(now).strftime('%S.%f'))
time.sleep(0.1)
print()
# get future or past dates
import datetime
newYearsEve = datetime.datetime.strptime('31/12/2020', "%d/%m/%Y")
newYearsDay = newYearsEve + datetime.timedelta(days=1)
print(newYearsDay)
# can also use: microseconds, milliseconds, seconds, minutes, hours, days or weeks
# for a complete list of strftime formatting characters see: https://strftime.org
# usingOSmodule.py
import os
import time
# show current directory
curDir = os.getcwd()
print('Current Directory =', curDir)
# make a new directory
os.mkdir('newFolder')
# make a new file
f1 = open('newFile.txt', 'wt')
f1.close()
# rename file
os.rename('newFile.txt','oldFile.txt')
# list files and folders in current directory
fileList = os.listdir(curDir)
for entry in fileList:
if os.path.isfile(entry):
print('File:\t', entry)
elif os.path.isdir(entry):
print('Folder:\t', entry)
# get last modification date and time of file
secs = os.path.getmtime('oldFile.txt')
print('oldFile.txt last modified:', \
time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(secs)))
# remove a file
os.remove('oldFile.txt')
# remove directory
os.rmdir('newFolder')
Issue OS command
# issueOScommand.py
import subprocess
def issueOScommand(cmd):
response = subprocess.check_output(cmd)
response = response.decode("ascii") # needed in python 3
return response
# construct command to be issued, together with its arguments / parameters
cmd = ['cmd.exe', '/C', 'dir']
# issue command and collect any output
output = issueOScommand(cmd)
# print lines from output
lines = output.split('\r\n')
for line in lines:
print(line)
# show_command_line_arguments.py
import sys
# total arguments
n = len(sys.argv)
print("Total arguments passed:", n)
# Arguments passed
print("\nName of Python script:", sys.argv[0])
print("\nArguments passed:", end = " ")
for i in range(1, n):
print(sys.argv[i], end = " ")
# listEnvironmentValues.py
import os
for var in os.environ:
print(var + '=' + os.path.expandvars('$' + var))
# fileExplorer.py
import os
def walkDirectory(path):
for directory, subdirectory, filenames in os.walk(path):
if directory == path:
print('Files\n-----')
for filename in filenames:
print(filename)
print()
print('Sub-Folders\n-----------')
print(directory)
print()
path = '.' # = current directory (or replace with full path)
walkDirectory(path)
# readWindowsRegistry.py
# Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion
from winreg import *
from datetime import datetime
registry = ConnectRegistry(None, HKEY_LOCAL_MACHINE)
def getRegistryEntry(strKey, strItem):
rawKey = OpenKey(registry, strKey)
found = False
try:
i = 0
while 1:
name, value, type = EnumValue(rawKey, i)
if name == strItem:
found = True
break
i += 1
except WindowsError:
pass
CloseKey(rawKey)
if found:
return value
else:
return 'Not Found'
key = r'SOFTWARE\Microsoft\Windows NT\CurrentVersion'
productName = getRegistryEntry(key, 'ProductName')
releaseId = getRegistryEntry(key, 'ReleaseId')
installDate = getRegistryEntry(key, 'InstallDate')
currentBuild = getRegistryEntry(key, 'CurrentBuild')
ubr = getRegistryEntry(key, 'UBR')
installedOn = datetime.fromtimestamp(installDate).strftime('%d/%m/%Y')
print(f'Edition {productName}')
print(f'Release {releaseId}')
print(f'Installed on {installedOn}')
print(f'OS build {currentBuild}.{ubr}')
# plot2barCharts.py
from matplotlib import pyplot as plt
import numpy as np
x = [1,2,3,4,5,6,7,8,9]
y = [7,5,4,6,8,4,3,2,8]
y2 = [3,7,5,4,6,8,4,3,2]
ytype=['Pigs','Cows']
width = 0.35
pos = np.arange(len(x))
print('pos =', pos)
plt.bar(pos, y, width, color='b')
plt.bar(pos+width, y2, width, color='g')
plt.ylabel('Cattle', fontsize=16)
plt.title('Farmyard animals sold',fontsize=18)
plt.legend(ytype,loc=2)
plt.show()
# minimal_pygame.py
# imports
import pygame
# functions
def update_screen():
pygame.draw.rect(screen, RED, pygame.Rect(100, 200, 300, 400))
# variables
BLACK = (0,0,0)
RED = (255,0,0)
# main
pygame.init()
DISPLAY_WIDTH = 600
DISPLAY_HEIGHT = 700
displaySize = (DISPLAY_WIDTH, DISPLAY_HEIGHT)
pygame.display.set_caption("Minimal Pygame")
screen = pygame.display.set_mode(displaySize)
screen.fill(BLACK)
clock = pygame.time.Clock()
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT: # window close button clicked
done = True
if event.type == pygame.KEYUP:
if event.key == pygame.K_q: # 'q' key pressed
done = True
screen.fill(BLACK)
update_screen()
pygame.display.flip()
clock.tick(60)
print('Quitting')
pygame.quit()
# minimal_tkinter.py
from tkinter import *
root = Tk()
root.title("Minimal Tkinter Example")
root.geometry("300x100")
def button_clicked(event):
entry_text = my_entry.get()
my_label.config(text = entry_text)
my_entry = Entry(root)
my_entry.pack()
my_entry.insert(0, "Enter any Text")
my_button = Button(root, text="Click this button to see what happens")
my_button.bind("<Button-1>", button_clicked)
my_button.pack()
my_label = Label(root, text='watch this label')
my_label.pack()
root.mainloop()
# drawGrid.py - Draws a grid of cells
import pygame
# Define dimensions of grid
DISPLAY_WIDTH = 640
DISPLAY_HEIGHT = 480
displaySize = (DISPLAY_WIDTH, DISPLAY_HEIGHT)
# Define size and number of cells
SIZE = 16
XCELLS = int(DISPLAY_WIDTH/SIZE)
YCELLS = int(DISPLAY_HEIGHT/SIZE)
# Constants for Left and Right Mouse button events
LEFT = 1
RIGHT = 3
# Create a list of colours
colours = []
colours.append((255, 255, 255))
colours.append(( 0, 0, 0))
WHITE = 0
BLACK = 1
# Create a list for cells in the grid
grid = [[WHITE for y in range(YCELLS)] for x in range(XCELLS)]
# Define a function to initialise all the cells
def initGrid(grid, c):
for y in range(YCELLS):
for x in range(XCELLS):
grid[x][y] = c
# Define a function to draw a square of colour(c) at coordinates, x and y
def drawCell(x, y, c):
pygame.draw.rect(screen, colours[c], \
pygame.Rect(x * SIZE, y * SIZE, SIZE-1, SIZE-1))
# Define a function to update cells on screen from grid
def update():
for y in range(YCELLS):
for x in range(XCELLS):
c = grid[x][y]
drawCell(x, y, c)
# Initialise pygame
pygame.init()
# Set the window title
pygame.display.set_caption("Draw a grid of cells")
# Create the window
screen = pygame.display.set_mode(displaySize)
# Blank screen
screen.fill(BLACK)
# Initialise the generations
initGrid(grid, WHITE)
# Update the full display surface to the screen
pygame.display.flip()
# Create a clock to manage time
clock = pygame.time.Clock()
# Initialise variables
done = False
drawingON = False
drawColour = WHITE
# Runs the game loop
while not done:
# The code here runs when every frame is drawn
# Get any events that have occurred, like close button(X) clicked
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# handle Mouse
if event.type == pygame.MOUSEBUTTONDOWN:
drawingON = True
if event.button == LEFT:
drawColour = BLACK
elif event.button == RIGHT:
drawColour = WHITE
if event.type == pygame.MOUSEBUTTONUP:
drawingON = False
# Check for q key
if event.type == pygame.KEYUP:
if event.key == pygame.K_q:
done = True
# Check for drawingON
if drawingON:
pos = pygame.mouse.get_pos()
x = int(pos[0] / SIZE)
y = int(pos[1] / SIZE)
grid[x][y] = drawColour
# Update and draw
update()
# Update the full display surface to the screen
pygame.display.flip()
# Limit the game to 30 frames per second
clock.tick(60)
print('Quitting')
pygame.quit()
# getWebPage.py
import requests
def getWebPage(url):
headers = {'User-Agent': user_agent}
response = requests.get(url,headers=headers)
html = response.content
return html.decode()
url = 'https://sites.google.com/site/getthecodingbug/courses/pythonsnippets'
user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36'
html = getWebPage(url) # this page
tags = html.replace('<', '>') # split html into tags
tags = tags.split('>')
# Find Table Of Contents (TOC) tags
n = 0
for tag in tags:
if 'getWebPage.py' in tag:
break
if 'a name="TOC-' in tag:
print(f'{tag:60} {tags[n+5]:40}')
n += 1