Featured

Welcome

This blog’s tagline is adapted from the Emacs Org-Mode motto. It seemed appropriate, as I seem to have spent most of my life writing novels and short stories (of which you can find out more at tonyballantyne.com) or teaching computer coding.

I’ve amassed a lot of material over the years, and I wanted to share it with people who may not have had the same access to education as people living in my country are lucky enough to have. If you want to change the world, become a teacher.

As the the teaching of coding seems to be coming back into fashion, I’ve also included my thoughts on the pedagogy of this subject.

All comments are gratefully received.

No Charge, No Adverts – however be aware that as an Amazon Associate I earn from qualifying purchases. If you’d like to show your appreciation, please follow me on Twitter @TonyBallantyne

All Materials Copyright (c) Tony Ballantyne 2022

A New Way to Evernote

Many people in the Personal Knowledge Management field are getting excited by Maps of Content: a new way of organizing your notes.

A Map of Content is simply a note containing links to other notes. Now that Evernote has upped its linking capabilities, Maps of Content are now an option for Evernote users.

This post will help you get started


Begin by making a new note called the Home Note. You can star this or pin it to your dashboard.

In your home note start writing about yourself. Here’s an example

My name is Tony.  The main things in my life are my family, my job as teacher and playing the piano.

Now look at that sentence. There are three areas in my life, family, teaching and piano, so I now create three new notes: Family, Teaching and Piano

Go back to the Home note and add links to those notes.  It’s easy to do this on Evernote by hitting Ctrl + Alt + K on Windows or Cmd + Opt + K on Apple then using the Select a Note dialogue. Here I am selecting my newly created Teaching note.

Now my Home note is done I go to one of the linked notes and start filling it in. Here’s an example:

I already have notes for the classes I teach so it’s straightforward to add links to them.

Now I can go to each class and start adding links or thoughts directly there.

My Maps of Content are building into a web of notes. I can navigate forwards using my links and backwards using the new backlinks feature.

The beauty of making Maps of Content is that I’m planning what I’m doing at the same time as I’m structuring my notes.

Using Maps of Content is a great way to grow your notes organically.  Folders are no longer used for navigation, they’re there for housekeeping only.

The great thing about this system is that you can run Maps of Content alongside your existing system for organisation. You’re just adding a new way to find the right note at the right time

Here are screen shots of the process so far:

Why not give Maps of Content a try? They might just change your life…

Whitespace Mode

I copy and paste text between lots of different applications. Whitespace mode makes it easy to see all the non printing characters that different apps use to format their notes: Evernote, for example, has a habit of insert non breaking spaces in its notes.

Unfortunately, Doom Emacs uses whitespace mode for tab indents only. In order to restore functionality, I had to read up on whitespace mode. Here are my notes, so you don’t have to do the same.

Whitespace

Whitespace uses two ways to visualize blanks: Faces and Display Tables.

  • Faces are used to highlight the background with a color. Whitespace uses font-lock to highlight blank characters. (FontLockMode, rather confusingly, is used for syntax highlighting.)
  • Display table changes the way a character is displayed. For example whitespace-mode uses $ by default to show end of lines.

The whitespace-style variable selects which way blanks are visualized.

whitespace-style

List containing various values. The first is face which enables visualisation using faces

The following will highlight any part of lines > 80 characters

(setq whitespace-line-column 80) ;; limit line length
(setq whitespace-style '(face lines-tail))

whitespace-display-mappings

Specify an alist of mappings for displaying characters.
Each element has the following form:

(KIND CHAR VECTOR…)

Where:

KIND is the kind of character.
It can be one of the following symbols:

    tab-mark        for TAB character
    space-mark      for SPACE or HARD SPACE character
    newline-mark    for NEWLINE character

CHAR is the character to be mapped.

VECTOR is a vector of characters to be displayed in place of CHAR.
The first display vector that can be displayed is used;
if no display vector for a mapping can be displayed, then
that character is displayed unmodified.

The NEWLINE character is displayed using the face given by
whitespace-newline variable.

(newline-mark ?\n    [?\$ ?\n]) ;; Standard emacs $ for EOL
(newline-mark ?\n    [182 ?\n]) ;; Unicode for Pilcrow sign

Doom Emacs Config

Doom Emacs uses Whitespace mode for tab indents only. The following restores functionality. (Solution adopted from this post)

(use-package! whitespace
  :config
  (setq
    whitespace-style '(face tabs tab-mark spaces space-mark trailing newline newline-mark)
    whitespace-display-mappings '(
      (space-mark   ?\     [?\u00B7]     [?.])
      (space-mark   ?\xA0  [?\u00A4]     [?_])
      (newline-mark ?\n    [182 ?\n])
      (tab-mark     ?\t    [?\u00BB ?\t] [?\\ ?\t])))
  (global-whitespace-mode +1))

Whitespace commands

M-x whitespace-mode
M-x global-whitespace-mode
M-x whitespace-newline-mode
M-x whitespace-toggle-options
M-x whitespace-report  Very handy

Related Posts

Buying Time

Making a big purchase? Here’s a good Evernote habit to get into…

  1. Use Webclipper to capture the details of the item you’re buying. Save it in a note with the name of the item.
  2. Use webclipper to take a screenshot of the receipt or drag and drop the receipt into the note.
  3. If appropriate, download the manual and add it to the note.
  4. Finally, tag the note so you can find similar purchases later if necessary

And there you have it, everything you need all in one place

The above takes two minutes, it saves so much time in the future.

Go and capture that information!

Python Course 13: Tests and Questions

Revision Questions

There will be test next week on the work we’ve done so far.  Here are some questions for you to practice:

  1. Prompt the user to enter their (name). Print out “Hello” (name) “I hope you’re well”
  2. Prompt the user to input two numbers.  Output the average of those two numbers.
  3. Prompt the user to enter their age.  If they are aged between 4 and 16 output “You should be at school”
  4. Create a list called months, containing the months in the year.  Now print out all the months, one after the other
  5. Use a for loop to print out the following numbers: 7,14,21, … 63,70,77
  6. Convert the String “I never saw a purple cow” to uppercase and output the resulting string.

Autumn 1 Test

Write programs to solve the following. Submit your answers as a word document here.

  1. Prompt the user “What’s the capital of France?” If they enter “Paris” print out “Correct!” otherwise print “Wrong!”
  2. Create a list containing the following houses “Rowntree”, “Wrigley”, “Lord”, “Mothersill”, “Birley”, “Hall”.  Print out the list, one after the other.
  3. The area of a triangle is half x base x height.  Prompt the user to enter the base and height of a triangle and then print out the area.
  4. Use a for loop to print out the 6 times table up to 12 x 6. Print it in the format “4 x 6 = 24” 
  5. Create a list containing the days of the week. Use string handling functions to print out the list in uppercase and then in lowercase.

Extension

Draw a house using turtle graphics. You get 1 point for each of the following features

  • Roof
  • Door
  • 1 Window
  • 2 Windows
  • Chimney
  • Garden Path

Code Golf: Songs

In code golf, the aim is to write a program with the lowest number of characters.

How short can you make the program to print out one of  the following songs?

Autumn 2 Test

Do the following questions.  Submit your code and output as screenshots on a Word Document here.

  1. Prompt the user to enter the number of bits in a byte.  If they answer 8 print correct, otherwise print “try again.”  The program should loop until the user gets the correct answer.
  2. Use a for loop to print out the 5 times table.
  3. Create a list containing the following names:  Ann, Sue, Andy, Steve, Charlotte, Craig, Mark, Raza.  Now print out all the names using a for loop.
  4. An online sweet shop charges for shipping as follows:  One box, £5.99; two to five boxes £7; more than five boxes, free.   Prompt the user to enter the number of boxes bought and output the shipping cost.
  5. In Python, open a file object with write access to a file called “cheese.txt”.
    1. Write the following three names to the file: Cheddar, Lancashire, Mozzarella
    2. Close the file object

Revision Questions 2

The Problems

Write programs to do the following. Take screenshots of your code and upload them as a word document.

  1. Prompt the user to enter the number of bits in a byte. If they answer 8 print correct, otherwise print “try again.” The program should loop until the user gets the correct answer.
  2. Use a for loop to print out the 5 times table.
  3. Create a list containing the following names: Ann, Sue, Andy, Steve, Charlotte, Craig, Mark, Raza. Now print out all the names, one after the other
  4. Create a dictionary called french containing the following data: chien – dog, chat – cat, vache – cow, cheval – horse, mouton – sheep. Loop through the keys printing out the associated values.

Extension

  1. Follow the link to find the text of the poem THE RIME OF THE ANCIENT MARINER: http://www.textfiles.com/etext/FICTION/coleridge-rime-371.txt
  2. Copy the text into a file called rime.txt
  3. Write a python program that reads rime.txt into a list.
  4. Modify your program so that it counts how many lines there are in the list.
  5. Modify the program further so that it counts how many words there are in the list.
  6. Modify the program so that it counts how many times the word “the” appears.
  7. Can you count the frequency of letters in the poem? In other words, how many times does ‘a’ appear, ‘b’ appear, ‘c’ appear and so on…

Time in Words

Given a time in numbers we can convert it into words. For example:

  • 5:00 Five o’clock
  • 5:10 Ten minutes past five
  • 5:15 Quarter past five
  • 5:30 Half past five
  • 5:45 Quarter to six
  • 5:47 Thirteen minutes to six

Write a program which inputs two numbers (the first between 1 and 12, the second between 0 and 59 inclusive) and then prints out the time they represent, in words. You should follow the format of the examples above. Your program should then terminate.

Sample run
Hours: 4
Minutes: 12
Twelve minutes past four

Partial Solution

The following code should start you off. It will answer some times correctly but not all. You will have test the code and then add extra lines to fix it.

times = ["o'clock","One","two","three","four", "five", "six",
	 "seven","eight","nine","ten","eleven","twelve","thirteen","fourteen",
	 "quarter","sixteen","seventeen","eighteen","nineteen","twenty",
	 "twenty one","twenty two","twenty three","twenty four",
	 "twenty five","twenty six","twenty seven","twenty eight",
	 "twenty nine","Half past"]

hours = 4
minutes = 12

if minutes>30:
    print(times[60-minutes]+ " to " + times[hours])
else: 
    print(times[minutes] + " past " + times[hours])

Test the code with examples given at the top of the screen.

The test data at the top of the screen is not exhaustive. Think of some other times that are not covered. Adjust your code accordingly.

Have you considered all the options? There is some test data at the bottom of this page…

Paste your completed code to a word document

Extension

  1. Which times, when written in words, have the longest length?
  2. Write a program that outputs times in 24 hour clock format, eg 13 hours 0 minutes outputs 13:00 and 9 hours 15 mins prints out 09:15.  You must include the leading 0s! 

Time in Words Test Data

  1. 3 o’clock
  2. 6:25
  3. 7:45
  4. 12:00 (noon)
  5. 0:00 (midnight)
  6. 12:55
  7. 0:05
  8. 0:30

Python Course 12: Robust and Secure Programming

  • Robust programming means writing programs that can cope with errors. One example would be to use data validation to avoid incorrect input.
  • Secure programming means writing programs that use security features such as passwords

You must check your validation with normal, boundary and erroneous data.

Examples

NOTE: All the following use while loops, not ifs! Why?

The following code checks that a value is entered

ans = input("Enter your choice")

while ans == "":
    ans = input("You must enter a value")

Test data: Erroneous: “” Normal: “Pizza”

The following code checks that the username is at least 6 characters long

ans = input("Choose your username")

while len(ans) <6:
    ans = input("Username must be at least 6 characters")

Test data: Erroneous: “Pizza” Normal: “Hamburger”

The following checks that someone is aged between 11 and 18

age = int(input("Enter your age: "))

while age < 11 or age > 18:
    age = int(input("Age must be between 11 and 18 "))

Test data: Erroneous: 8 Boundary: 11 Normal: 15

The following checks that someone is in a year 9 form

forms = ["9b","9h","9bh","9l","9m","9lm","9r","9w","9rw"]

f = input("Enter your form group: ").lower()

while f not in forms:
    f = input("Not a valid form group: ").lower()

Test data: Erroneous: “8qt” Normal: “9l”

Exercise

Write code to perform the following validation checks.

  1. Jockey club names cannot be more than 18 characters long. Write a validation check for these names. Test with the normal data “Ariel” and the erroneous data “supercalifragilisticexpialidocious”
  2. Modify your answer to question 1 so that blank names are also rejected
  3. Police officers in the UK are aged between 18 and 60. Write a validation check for this. Test your code with the following data: 25, 60 and 81
  4. A cafe sells the following drinks: tea, black coffee, white coffee, hot chocolate, lemonade. Write a validation check for the above drinks.

Extension

The following code demonstrate the instartswith and endswith functions

>>> s ="I never saw a purple cow"
>>> s.endswith("cow")
True
>>> s.startswith("I")
True
>>> "never" in s
True

Use them to write validation checks for the following:

This is an example of a URL: http://blue-coat.org

  1. URL check: does it end in .com or .org?
  2. Does it start with http:// or https://
  3. Simple check for email: does the string contain an ‘@’?
  4. More complex email check: does a string contain ‘@’ and end with .com or .org?

Python Course 11: Dictionaries and REPLs

Copy the following code into your IDE

terms = {"bit":"binary digit", "byte":"8 Bits", "kilobyte":"1000 Bytes"}

def Main():
    # The input output loop
    ans = ""
    while ans != "end":
	print("L to Look up a Word")
	print("E to Enter new Word")
	print("end to exit the program")

	ans = input("What do you want to do?")

	if ans == "L":
	    lookup()

	elif ans == "E":
	    enter()

	else:
	    print("I don't understand that command")


def lookup():
    word = input("Enter the word you wish to look up")
    if word in terms:
	print(terms.get(word))
    else:
	print("Word not in dictionary")


def enter():
    word = input("Enter new word")
    definition = input("Enter the definition")
    terms[word] = definition


Main()

Revision Helper Exercise

  1. Run the above code. Make sure you understand how it works
  2. Follow the link to see Computing Key Terms. Add some of these to your dictionary.
  3. Add an option to the Main() loop to print out all the key values in the terms dictionary. Implement that option

Python Course 10: Dictionaries

Sample Code

# Create a dictionary
graphics = {"pixel": "Picture Element", "resolution": "Number of pixels on screen", "bitmap":"Image composed of pixels"}

# Print a value
print(graphics["pixel"])

# Loop through the keys
for key in graphics:
    print(key)

# Loop through keys and values (note the .items()!)
for key, value in graphics.items():
    print(key, " is ", value)

# Add an entry to the dictionary
graphics["colour depth"] = "Number of bits used to represent each pixel"

# Check to see entry
print(graphics)

Exercise

  1. Create a python file called dict.py
  2. Create a dictionary called sound containing the following terms: analogue – continuously variable data, digital – data stored as bits, sample – measure of amplitude at a point in time
  3. Print out the value of sample
  4. Add the following two definitions to the dictionary: sampling rate – number of samples taken in a second, Sample resolution – number of bits per sample.
  5. Loop through all the keys in the dictionary and print them out.

Extension

Choose a different subject. Create a key terms dictionary with at least 5 items for that subject. Print out all the keys and values

Python Course 9: File Objects

Write to Disk

my_file = open("sample.txt","w")
my_file.write("Sausage\n")
my_file.write("Egg\n")
my_file.write("Chips\n")

my_file.close()
my_file = open("hello.txt","w") 
lines_of_text = ["Sausage\n","Egg\n","Chips\n"] 
my_file.writelines(lines_of_text) 
my_file.close() 

Read from Disk

Read One Line from Disk

my_file = open("sample.txt","r")
print(my_file.readline())
my_file.close()

Read all Lines and Strip Line Breaks

file = open("sample.txt", "r") 
for line in file: 
    print(line.rstrip('\n'))

or

file = open("sample.txt", "r") 
for line in file: 
    print(line, end = "")

Read Lines into a List

my_file = open("sample.txt","r")
print(my_file.readlines())

my_file.close()

Exercise

  1. In Python, open a file object with write access to a file called “people.txt”.
    1. Write the following three names to the file: George, Alison, Jasprit.
    2. Close the file object
    3. Open the file in Notepad and check the names were written correctly.
  2. Use Notepad to create a text file called “shopping.txt”. Add the following items, one item per line: milk, sugar, flour, 6 eggs, butter, raisins, raspberry jam
    1. In Python, open a file object with read access to shopping.txt
    2. Use a for loop to print out the items in your shopping list
  3. In Python, open a file object with write access to a file called “todo list.txt”
    • Write a question loop that will prompt the user “Add another item”
    • If the user enters “N” the loop will terminate and the file object will be closed.
    • Otherwise, the item entered will be written to the file object
    • Run your program and check that the todo list is created.

Python Course 8: Question Loop Examples

A Basic Question Loop

Keep asking the question until the correct answer is entered

answer = ""
while (answer != "Paris"):
    answer = input("What is the capital of France?")
print("Correct!")

A Question Loop with a Count

Keep a count of how many attempts were made

answer = ""
count = 0

while (answer != "Paris"):
    answer = input("What is the capital of France?")
    count = count + 1

print("Correct!")
print("You took ", count , "goes")

A Question Loop with a Flag

finished = False
number = 0
print("Denary to Binary Converter")
print("Enter -1 to finish")

while (finished == False):
    number = int(input("Enter a number in Denary"))
    if (number == -1):
	finished = True
    else:
	print("{:b}".format(number))

A Question Loop with a Count and a Flag

finished = False
correct = False
answer = ""
tries = 3

while (finished == False):
    password = input("Enter the password: ")
    if (password == "p455w0rd"):
	finished = True
	correct = True
    elif (tries == 1):
	finished = True
	correct = False
    else:
	tries = tries - 1
	print("Wrong.  You have", tries, "tries remaining")


if(correct == True):
    print("You're in!")
else:
    print("Locked out!")

Exercises

1) Write a program that asks “Are we there yet?” and prompts the user to enter an answer. The program loops until the user enters “Yes”. The program then outputs “Hooray!”

2) Write a program that asks the user to guess a number between 1 and 10. The program loops until the user enters the correct answer [7]. The program then outputs then the number of guesses made.

3) Modify the program from question 2 so that the user now has to guess a number between 1 and 100. The program outputs “Too low” if the guess is lower the number, “Too high” if the guess is highter than the number and “Correct” if the guess is correct. The program then terminates

4) The following code converts pounds to kilograms. Write a program that prompts the user to enter a weight in pounds or -1 to terminate. The program will output the weight in kilograms. If -1 is entered the program will print “Goodbye”

pounds = 4
kilograms = pounds * 0.453592
print(kilograms)

5) A house alarm system is triggered when the front door is open. The user has three attempts to enter a four digit code. If the user enters the correct code the system outputs “Deactivated!”. If the user enters the incorrect code the system outputs the number of attempts remaining. If the user does not enter the correct code within three attempts the system outputs “Alarm!”

Extension

Write a quiz program that asks the user 5 questions.  The user is allowed 2 attempts at each question.  At the end the program prints out the users score out of 5

Python Course 7: Functions

Sample Code

def hello(name):
    answer = "Hello " + name
    return answer

print(hello("George"))
print(hello("Gill"))
def isChild(age):
    if age < 18:
        return "Child"
    else:
        return "Adult"

print(isChild(35))
def AreaRect(length, width):
    return length*width

l = int(input("Enter the length"))
w = int(input ("Enter the width"))
print(AreaRect(l, w))
PI = 3.1415

def main():
    radius = 4
    print("The area of a circle radius ", radius, " is ", Area(radius))     


def Area(r):
    return PI*r*r

main()

Exercises

  1. Write a function that accepts a string and returns “Pleased to meet you, ” + string
  2. Write a function that accepts a number and returns “Child” if the number is <18 and “Adult” otherwise
  3. Write a function that accepts a number and returns “Grade A” if the number is >20, “Grade B” if the number is >15, “Grade C” if the number is >10 and “Fail” otherwise.
  4. Write a function that accepts two numbers and returns the average of the numbers
  5. Write a function that accepts three integers and returns the average of the numbers.
  6. Write a function that accepts the length and width of a rectangle and returns the perimeter of the rectangle
  7. Write a function that accepts the base and height of a triangle and returns the area of the triangle
  8. Write a function that accepts a list and returns the sum of the list

Extension

  1. Write a function that returns the hypotenuse of a triangle when the other two sides are int a and int b. (Remember: hypotenuse squared equals a squared plus b squared)
  2. The scalar product of u=(u1,u2,u3) and v=(v1,v2,v3) is defined to be u1v1+u2v2+u3v3. Write a function that accepts two int tuples as parameters and returns an int representing the scalar product of those two tuples
  3. If A = (a1,a2, …an) and B = (b1,b2, …bn) then the vector sum of the two tuples A + B = (a1+b1, a2+b2, … , an+bn). Write a function that accepts two tuples as parameters and returns an array representing the vector sum of those two tuples
  4. The Euclidean distance between two points A = (a1,a2, …an) and B = (b1,b2, …bn) is defined as sqrt((a1-b1)2 + (a2-b2)2 +… + (an-bn)2). Write a function that accepts two int tuples representing A and B as parameters and returns a double representing the Euclidean distance between them.