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. If you’d like to show your appreciation, please follow me on Twitter @TonyBallantyne
A big part of writing is putting the notes I’ve made into some sort of order. I spend a lot of time joining notes together to make scenes and then rearranging those scenes. Scrivener is good at the rearranging part (I’ve written about this here.) Where Scrivener falls down is the flexibility of search. Emacs allows me to home in on a scene, an idea or a sentence almost instantly.
I copied some of my writing process from Scrivener’s model, even going as far as writing a simple Emacs Scrivener mode. Doom Emacs has rendered that unnecessary. Tools like ripgrep and consult make it far quicker to find what I’m looking for. If you’re unfamliar with the following commands, try them out. You’ll be pleased that you did.
One last thing. Doom Emacs calls different commands depending on which completion engine you’re using. This means the search syntax may vary. I use the default (vertico at the time of writing) which means that searching for apples oranges will return lines containing apples and oranges. In other words: when searching, type one word for an initial selection, then a second to narrow it down.
10.0.1 Searching in Projects
SPC SPC find file in project
SPC s p search project for text
SPC s P search another project for text
SPC s d search files in directory for text
10.0.2 Searching in Buffers
SPC s s helper function search for text in current buffer. Matches are displayed in another window.
SPC s j helper function that goes to entry in evil’s jump list
SPC m . Jump to org heading (uses consult-org-heading)
And don’t forget
C-c C-j org-goto
10.0.3 Useful Tips
SPC s o Search online. t will search online dictionary, T thesaurus
Find an unmatched quote using this regex ^[^"]*"[^"]*$
10.0.4 M-x consult-ripgrep
For a more flexible search try consult-ripgrep. It’s worth reading the documentation, but here’s a taste:
#alpha beta Search for alpha and beta in any order.
#alpha.*beta Search for alpha before beta.
#\(alpha\|beta\) Search for alpha or beta (Note Emacs syntax!)
#word -- -C3 Search for word, include 3 lines as context
#first#second Search for first, quick filter for second.
Older programming languages distinguish between Functions and Procedures. Very simply, a function returns a value, a procedure does not.
Java rolls both of these into one concept: Methods. A method always has a return type. If the return type is void it is what an older language would call a procedure, otherwise it’s a function.
Here is an example method:
public void spoons (String s, int i)
Access Type
Return Type
Name
Parameters
public
void
spoons
(String s, int i)
Two example Classes
public class Main {
public static void main(String[] args)
{
Person p1 = new Person("Bloggs", "Joe");
p1.setSex("M");
Person p2 = new Person("Baker", "Jill");
p2.setGender("F");
p1.printPerson();
p2.printPerson();
}
}
public class Person {
private String surname;
private String forename;
private String gender;
Person(String surname, String forename)
{
this.surname = surname;
this.forename = forename;
}
public void setGender(String s)
{
if(!(s.equals("F")|s.equals("M")))
{
System.out.println("Validation error!");
} else
{
sex = s;
}
}
public void printPerson()
{
System.out.println(surname + " " + forename + " " + gender);
}
}
Method Exercise: Progress Tracker
Write a class Pupil that will track pupils’ progress through a year. The class will store pupils’ grades as percentages.
Add private member variables String forename, surname
Add private member variables int target, autumn, spring, summer
Add a constructor method that will accept the parameters forename, surname, target
Test the constructor by adding the following pupils: Joe, Bloggs, 70 and Jill, Cooper, 75
Add accessor methods to setAutumn(), setSpring(), setSummer()
Add accessor methods to getAutumn(), getSpring(), getSummer()
Add the following grades to Joe Bloggs: Autumn 55, Spring 65, Summer 75
Add the following grades to JIll Cooper: Autumn 50, Spring 60, Summer 70
Add a method average() to return a double showing the average percentage a pupil has. Print out Joe and Jill’s average scores
Add a method progress() that will return a String saying whether the pupil is above target, on target or below target on the summer test.
Check this method works on Joe and Jill
Add a print() method that will print out the pupil’s details in a suitable format
Extension Work
Add a validation() method to check that grades entered lie between 1 and 100
Modify your average() method so it will return a correct average if only one or two grades have been entered so far
Add a static int variable aBound to record the grade A boundary.
Add the appropriate setters and getters to aBound
Set up a Pupil [] array in your Main class to handle your pupils
Add a save() method to your Pupil class that will write the pupil data to file
String [] day = {"Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday", "Sunday"};
for(int i = 0; i<day.length;i++)
{
System.out.println(day[i]);
}
Random Element of Array
String [] day = {"Monday","Tuesday","Wednesday","Thursday",
"Friday","Saturday","Sunday"};
int d = (int)(Math.random()*7);
System.out.println(day[d]);
Splitting a String into Words
String s = "This is an example string";
String [] seperated = s.split("\\s+");
for (int i=0; i<seperated.length; i++)
{
System.out.println(seperated[i]);
}
int [] numbers = {3,5,3,4,7,8}; Print out the second element of the array
Make a String array of the months of the year. Print out all the months.
Print out a random month of the year
Create an int array recording the number of days in each month
Print out all the months and the days in each month.
int [] numbers = {3,5,5,4,8,8,10,2}; Print out the total of all the numbers in the array. Print out the average
Make a string array with the words “First”; “Second”; “Third”; … “Twelfth”. Write a for loop to print out “On the First Day of Christmas,” “On the Second Day of Christmas” etc.
Separate the following string using the “,” as a token. Print out all the elements. String s = “1,5,6,1,7,1,4,3,1,4,5,6,1,5,3,5,6,4,4,8”;
Extension
Paste the following code into your IDE, and then do the questions below.
String [] question = { "What is the capital of France?",
"What is the capital of Germany?",
"What is the capital of Spain?"};
String [] answer = {"Paris", "Berlin","Madrid"};
int score = 0;
Scanner scan = new Scanner(System.in);
String input;
for(int i= 0; i<3; i++)
{
System.out.println(question[i]);
input = scan.nextLine();
if(input.equals(answer[i]))
{
score++;
}
}
System.out.println("You scored "+ score + " out of "+ question.length);
Run the code to check it works
Add some extra questions and answers. Check the code still works
Add code to print out the correct answer if the user gets a question wrong
Alter your code so that questions and answers are read in from text files
food = ["Sausage", "eggs", "Bacon", "Beans"]
pupils = ["John", "Jill", "Emily", "Satpal"]
scores = [5,3,6,7,9,1,2]
days = ["Sunday","Monday","Tuesday","Wednesday","Thursday", "Friday","Saturday"]
# Print all the days
for day in days:
print(day)
#print eggs
print(food[1])
#print Emily, Satpal
print(pupils[2:])
#print Tuesday, Wednesday
print (days[2:4])
#print John, Jill
print(pupils[:2])
#print Friday
print(days[-2])
print(len(days))
print(max(scores))
print(min(scores))
if "John" in pupils:
print("Pupil is present")
else:
print ("Pupil absent")
pupils = pupils + ["Arthur"]
print(pupils)
Exercises
The following questions refer to the sample code. You can type the code into IDLE and run it to help you figure out the answer
Look at the print(food[ 1 ]) line. What does the [ 1] do?
How would you print the first item in the list?
If a python list has seven items, what would number would the seventh item be?
Look at the print(pupils[2:]) line. What does [2:] mean?
Look at the print(days[2:4])line. What does [2:4] mean?
Look at the print(days[-2]) line. What does [-2] mean?
What does len do?
What do max and min do?
Now write your own modules to do the following
Create a list called months, containing the months in the year.
Print out all the months, one after the other
Use slicing (e.g. days[2:4]) to print out the spring months: March, April, May
Print out the summer months: June, July, August
Print out the first and last months of the year
Print out the winter months: December, January and February
Extension: Research
Use a search engine and online manuals to find out how to get Python to do the following
Reverse the following list: [“Sunday”,”Monday”,”Tuesday”,”Wednesday”,”Thursday”, “Friday”,”Saturday”] i.e. print out “Saturday”,”Friday”,”Thursday”,… etc
Remove “eggs” from this list food = [“Sausage”, “eggs”, “Bacon”, “Beans”]
Sort the following list into ascending order scores = [5,3,6,7,9,1,2]
Insert “Mushrooms” into this list, just after “eggs”
Count how many times “blue” appears in this list [“red”,”blue”,”blue”,”blue”,”red”,”blue”]
For many people, going to College means freedom. Freedom to try new things, to do what you like, when you like.
Well, not quite.
You’re still going to have lectures and tutorials to attend (that’s why you’re going, remember?) You want to make sure that you know what you’re doing every day, so that you can really enjoy your free time without worrying that you’re behind on an assignment.
That’s where Evernote can help you.
Evernote Home gives you your day on a page. Front and center should be your calendar. Your calendar will tell you where you need to be and when. Lectures, tutorials, practicals…
Setting up a calendar with all those details can be tedious. The good news is that 99% of the time your college will have your timetable already prepared and will share it with you via Google Calendar or Outlook.
You can view that calendar on your home page on Evernote. Here’s how you can add a Google Calendar. Evernote doesn’t support Outlook Calendar integration yet, but you can subscribe to your Outlook Calendar from your Gmail account. Scroll to the bottom of the page to see how.
Add your college calendar and when you open up Evernote in the morning you’ll have your day on a page before you.
But there’s more.
Searching is easy on Evernote, but why search when you can have the right notes appear at the right time?
Here’s a tip: link your study notes to your individual events.
Just suppose you’ve created a note with the materials you need for tomorrow’s 9am tutorial. Link that note to the tutorial on the calendar on your Home Page. Here’s how to add link notes to calendar events. Now the note will be there, just when you need it.
You can even get Evernote to remind you to open the notes as the lecture begins. Just go to Calendar settings (click the dots on the top right of the calendar widget).
int count = 10;
while (count>0)
{
System.out.println(count);
count = count - 1;
}
System.out.println("Lift off!");
Counting Objects
String colours = "red blue red blue blue blue blue red blue red blue "
+ "red blue blue red blue blue blue red blue red red "
+ "blue blue red red red red blue red blue red blue blue";
Scanner scan = new Scanner(colours);
int redcount = 0;
while (scan.hasNext()) {
String s = scan.next();
if (s.equals("red")) {
redcount = redcount + 1;
}
}
System.out.println("Number of reds " + redcount);
A Basic Question Loop
Scanner scan = new Scanner(System.in);
String answer;
do
{
System.out.println("What's the capital of France?");
answer = scan.nextLine();
}while (!answer.equals("Paris"));
System.out.println("Correct!");
A Question Loop with a Count
Scanner scan = new Scanner(System.in);
String answer;
int count = 0;
do
{
System.out.println("What's the capital of France?");
answer = scan.nextLine();
count = count + 1;
}while (!answer.equals("Paris"));
System.out.println("Correct!");
System.out.println("It took you " + count + " guesses");
A Question Loop with a Flag
Scanner scan = new Scanner(System.in);
int answer;
boolean isNotDone = true;
do
{
System.out.println("Enter an Integer, 0 to end.");
answer = scan.nextInt();
System.out.println(answer + " squared = " + answer * answer);
if (answer == 0)
{
isNotDone = false;
}
}while (isNotDone);
System.out.println("Done!");
A Question Loop with a Count and a Flag
Scanner scan = new Scanner(System.in);
String answer;
boolean isCorrect = false;
int count = 0;
do
{
System.out.println("Enter the password");
answer = scan.nextLine();
if (answer.equals("Java"))
{
isCorrect = true;
}
count = count + 1;
}while(!isCorrect & count <3 );
if (isCorrect)
{
System.out.println("Correct password");
}
else
{
System.out.println("Incorrect password");
Exercise
while Questions
Use a while loop to print out the integers from 1 to 10
Use a while loop to print out the even numbers from 2 to 20
Use a while loop to print out the four times table
Use a while loop to print out the five times table in the form “n x 5 = 5n”
Use a while loop to print out the sequence 7,10,13,16,19,22,25
Use a while loop to print out the sequence -0.3, -0.2, -0.1, 0, 0.1, 0.2
Use a while loop to print out the sequence 64, 32, 16, 8, 4, 2, 1
Use a while loop and Scanner to count how many heads and tails there are in the String below. (nb. you should carefully copy and paste the String into your program)
String coins = “head head tail head tail head head head tail head tail head tail head head head tail “+ “head tail head tail head tail head tail head tail tail tail head head head tail “+ “tail head tail head tail tail head head head tail tail tail head tail head head head tail “+ “head tail tail head tail head head head tail head tail head tail head head head head “+ “head tail head tail head tail head head head tail tail head tail head tail head head head head”;
Write a code to find the number of times the word “never” appears in the following poem: I never saw a purple cow, I never hope to see one, but I can tell you anyhow, I’d rather see than be one.”
Now search the Internet for the text to the poem “McCavity the Mystery Cat” Write code to count the number of times the word McCavity appears.
do while Questions
Make the computer keep asking “Are we there yet?” until the answer yes is input.
Ask the user the to guess a number between one and ten. Hard code the number 4 as an answer. The computer will print out how many guesses the user takes before they get the correct answer.
Modify program 2 so that the computer chooses a random number as the answer.
Write a higher lower game. Modify program 3. The computer thinks of a number between 1 and 100. The user tries to guess the number, and the computer tells the user if their answer is higher or lower. Whe then user guesses correctly, the computer congratulates the user and tells them how many guesses it took them.
Wrtie a password checker. The user cannot proceed until they enter the correct password.
Modify your password checker so that the user sees the message “Locked Out” if they fail to guess the password in three guesses.
Extension
The skeleton code below is intended to guess the number the end user is thinking of. The end user can enter yes if the computer guesses the answer, higher if the number is higher and lower otherwise. Copy the code into the IDE and complete it.
Scanner scan = new Scanner(System.in);
double num = Math.random()*100;
int ran = (int)num+1;
int guess = 50;
int high =100;
int low= 0;
String input = "";
boolean isCorrect = false;
do
{
System.out.println("Is the number " + guess + "?");
input = scan.nextLine();
if(input.equals("yes"))
{
isCorrect = true;
}
else if(input.equals("higher") )
{
low = guess;
guess = low + (int)(high-low)/2;
}
}while(!isCorrect);
Which of the following is better programming practice? Why?
x = 35.51*1.17
print(x)
or
pounds = 35.51
euroRate = 1.17
euros = pounds * euroRate
print("£", pounds , " = " , euros , " euros")
print("at a rate of " , euroRate , " euros to the pound")
Formatting
Take a look at the output from the second piece of code
£ 35.51 = 41.546699999999994 euros
at a rate of 1.17 euros to the pound
This would be better if it read 41.55 euros, rather than 41.546699999999994
Also, take a look at this line
print("£", pounds , " = " , euros , " euros")
All those commas and speech marks are confusing. It’s easy to make a mistake when entering them.
There’s a better way to format your data.
pounds = 35.51
euroRate = 1.17
euros = pounds * euroRate
print("£ {} = {} euros".format(pounds, euros))
print("at an rate of {} euros to the pound".format(euroRate))
The above does the same as the original code. It has the advantage of being slightly easier to enter and read. As an added bonus, you can format the number of decimal places
pounds = 35.51
euroRate = 1.17
euros = pounds * euroRate
print("£ {} = {:.2f} euros".format(pounds, euros))
print("at an rate of {} euros to the pound".format(euroRate))
Notice the {:.2f}. This says “format the number as a float (a decimal) to 2 decimal places”
This produces the following output
£ 35.51 = 41.55 euros
at a rate of 1.17 euros to the pound
Much more user friendly!
Loop Question
Use a while loop to produce the sequence 0.1, 0.2, 0.3, …1.0
number = 0.1
while number <=1:
print(number)
number = number + 0.1
The numbers are printed in denary, binary and hexadecimal.
17
10001
11
Remember that the input command reads strings. You have to convert strings to integers (whole numbers) or floats (decimals) if you want to use them to perform calculations.
Examples
1) Write a program that prompts the user to enter the length and width of a rectangle. Output the area of the rectangle
length = int(input("Enter the length of the rectangle"))
width = int(input("Enter the width of the rectangle"))
area = length*width
print("The rectangle has an area of {}".format(area))
2) To convert miles to kilometers, you multiply the number of miles by 1.609. Write a program that prompts the user to enter the number of miles, and then output the answer converted to kilometers
Note the use of float as a user may input 12.5 miles, for example.
miles = float(input("Enter the number of miles"))
kilometers = miles * 1.609
print("{} miles = {:.2f} kilometers".format(miles,kilometers))
Exercise
Write a program with two variables, length and width, that outputs the perimeter of a rectangle. Test it with length = 5 and width = 4.
At the time of writing, the exchange rate for pounds to euros is 1 GBP = 1.19984 Euros. Write a program that will convert pounds to euros. Test it using the data GBP4.50 (Don’t forget to convert the input to a float!)
Now write a program to convert euros to pounds. Test it using the data Euro 7.40
Prompt the user to input a number. Output the square of that number.
Prompt the user to input two numbers. Output the average of those two numbers.
Prompt the user to input three numbers. Output the sum and the average of those three numbers.
Assume pi = 3.1415. Prompt the user to input the radius of a circle. Output the circumference and the diameter of that circle
Extension: Fahrenheit to Celsius
Here are the formulas to convert from Fahrenheit to Celsius and back again.
°F to °C Deduct 32, then multiply by 5, then divide by 9 °C to °F Multiply by 9, then divide by 5, then add 32
Now write a program to convert Celsius to Fahrenheit. Use the test data to check your program.
Write a program to convert Fahrenheit to Celsius. Again, use the test data below to check your program.
Prints the first ten squared numbers in the form “3 squared = 9”
for(int i =1; i<=10; i =i+1) {
System.out.println(i+ " squared = "+ i*i);
}
Nested for loops
The following nested for loops print out the pattern triangle pattern below. Note the j<i condition in the second for loop and the use of print() and println().
import turtle
SIDE = 50
def triangle():
turtle.begin_fill()
for n in range(3):
turtle.forward(SIDE)
turtle.right(120)
turtle.end_fill()
def black_triangle():
turtle.fillcolor("black")
triangle()
def white_triangle():
turtle.fillcolor("white")
triangle()
def snake():
black_triangle()
turtle.forward(SIDE)
turtle.right(60)
white_triangle()
turtle.left(60)
snake()
Exercise
Copy the code into your IDE and run it.
Draw a snake 6 segments long
Draw a red and green snake, 6 segments long.
Draw pink and yellow snake, 6 segments long, but half the size of the previous snake.
Use a for loop to simplify your code.
Now draw a snake 10 segments long
Extension
Modify your code to draw a bracelet, as shown below.
Functions and Turtle Graphics
The following code is the start of a solution to the problem of drawing a chessboard. It uses functions to help make the code understandable
import turtle
# Declare this at the top. Put it in capitals to show it shouldn't be changed
SIDE = 50
def square():
turtle.begin_fill()
for n in range(4):
turtle.forward(SIDE)
turtle.right(90)
turtle.end_fill()
def black_square():
turtle.fillcolor("black")
square()
def white_square():
turtle.fillcolor("white")
square()
def move_one_square_right():
turtle.penup()
turtle.forward(SIDE)
turtle.pendown()
def move_one_square_down():
turtle.penup()
turtle.right(90)
turtle.forward(SIDE)
turtle.left(90)
turtle.pendown()
def white_black_line():
for n in range(4):
white_square()
move_one_square_right()
black_square()
move_one_square_right()
# Speed up the turtle
turtle.speed(0)
# Draw two lines of the chessboard
white_black_line()
turtle.home()
move_one_square_down()
move_one_square_down()
white_black_line()
Exercise
Copy the code into your IDE. Watch out for indents!
Run the code and see what it does.
Add a function to draw a black_white() line
Draw a chessboard using the functions provided
Can you make you code more efficient, perhaps by using a for loop?
What happens if you change the value of SIDE?
Draw a 10×10 chessboard
Extension
The following function draws a hexagon:
def hexagon():
for n in range(6):
turtle.forward(50)
turtle.left(60)
Use the function to draw a honeycomb pattern
Can you make the honeycomb cover the whole screen?