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

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.

Enjoy Your Sunday Evening

You’re a teacher: it’s Sunday evening and you can’t relax as you have work tomorrow. Why is that?

Partly it’s stage fright. Those outside the profession don’t understand the necessary performance that every teacher undertakes in the classroom.  Take a tip from professional musicians: they  know the best cure for performance anxiety is to be thoroughly prepared.

Lack of preparation is a big cause of stress: that nagging feeling that there’s something really important that you should be working on while you’re busy tackling day to day tasks.

Trust the System

Productivity Systems like GTD can help you tackle this stress: I talk about GTD here

GTD boils down to writing down every job, no matter how small. Once you’ve done that you just need to make sure the jobs turn up in the right order.  That way you can focus on the task in hand.

If you believe your system is working then you’ll trust that the right task will be presented to you when it needs to be done. Nothing will be forgotten.

Use the Calendar

Evernote offers a number of ways to ensure that you see the right task at the right time.  Every teacher should Connect Evernote to Google Calendar.  You may be lucky, your lessons may already be available on just such a calendar. If not, it’s worth the time spent inputting the lessons yourself.

Once you can see your lessons in the calendar, you can begin to add notes to the individual events. 

Each lesson can have its own note containing reminders on things such as students to chase and homework to set. Pro top: tag your notes with the name of the class. That way you can quickly filter to all notes relating to that class. 

One thing, don’t repeat yourself. If your teaching materials and marks are already in the school’s learning platform or MIS, leave them there. If you duplicate materials you won’t know which ones you last updated.

But teaching isn’t just about lessons. What about the other jobs that need to be done tomorrow?

That’s where tasks come in…

Five Tasks a Day

Tasks are your todo list. Add due dates to your tasks but be realistic: you can’t do everything tomorrow. The question you should ask yourself isn’t what COULD I do tomorrow but what HAS to be done tomorrow? Adding a due date to your tasks means you know that you won’t miss the tasks that HAVE to be done that day.

I aim to complete five tasks a day. Why five? Because five works for me. I look for a balance of bigger tasks such as marking a set of books and smaller tasks such as phoning a parent. Choosing a set number of tasks helps you to manage your expectations: you’re never going to complete everything that you want to do. Trying to do so leads to stress.

Your Day on a Page

Lastly, have your home page set up. Tasks and Calendar. Your day on a page. You can see tomorrow’s jobs at a glance.

Enjoy your Sunday Evening

Now that you know that tomorrow is sorted you can forget it. It’s time to unwind and enjoy your Sunday evening…

Hands off that Mouse!

Four keyboard shortcuts you shouldn’t be without (and one Evernote really should implement…)

Want to know the easiest way to improve your productivity?

Stop using the mouse.

Watch an IT professional and you’ll see that their hands never leave the keyboard. They know that it takes a couple of seconds to move your hand from the keyboard to the mouse, and then to move the mouse to the right position on the screen and click. They know that the bigger the screen, the further the you have to move the mouse and the longer it takes to click. 

Learning just a few simple keyboard shortcuts can really speed things up. Here are three shortcuts you can use with Evernote and one that works everywhere.

1: Tab Switch between Applications

The first shortcut is nothing to do with Evernote; it’s something built into Macs, Windows and most Linux desktops 

Just suppose you’re surfing the web with your favourite browser (Safari, Chrome, Firefox, Edge) and you want to switch to Evernote to check something. 

Don’t reach for the mouse. Hold the Alt key on Windows or the Command (⌘)   key on Apple and then press the tab key. 

As you press tab you’ll see your current open apps appear on the screen.

Repeatedly press tab until you have selected the app you want to switch to, and then let go.

Tab switching is clever. The apps rearrange themselves every time you tab switch so that the app you last used is only ever one tab away. Try it.

Once you’ve got the hang of this you’ll wonder why you ever used the mouse.

2: Finding a Note in Evernote

You have two choices here:

Either jump to the search bar using Ctrl Command (⌃⌘)  E on Mac or Win Shift F on Windows

Or press Command (⌘) J on Mac or Ctrl Q on Windows to open the switcher.

The search bar remembers things like which notebook you’re in, the switcher does a fresh Evernote wide search with suggestions

Which is better? Why not try them both out and see which one you like?

If you want a new note: hit Command (⌘) N on Mac or Ctrl N on Windows

3: Finding something within a Note

Now that you’ve found your note, try and find a particular word within it.

First you have to jump to the note editor.   Hit tab repeatedly to get to it and then press enter.  (It has to be said, Evernote, you could come up with a better way)

After that it’s just Command (⌘) F on a Mac or Ctrl F on Windows to bring up the Find in Note dialog

4: A Bonus Shortcut

The previous shortcuts help you work in Evernote. But if all you want to do is jot down a quick note there is an even faster way: the helper.

The helper is one of the most underutilised features of the Evernote desktop

Ctrl Cmd (⌃⌘)  N on a Mac or Ctrl Alt H on Windows to bring it up. You can add a quick note here. You can even screenshot straight into Evernote

Test Yourself

Practicing the above shortcuts will help to get them into your muscle memory

Follow this link to see a copy of this page as a note. Save it Evernote.

Now, starting in another application see if you can find this elephant without using  the mouse

  1. Tab switch to Evernote (Cmd Tab or Alt Tab)
  2. Search for or switch to this note
  3. Search within the note for the word elephant