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. If you’d like to show your appreciation, please follow me on Twitter @TonyBallantyne

All Materials Copyright (c) Tony Ballantyne 2022

Getting Around in Doom Emacs

The following post is part of my new Emacs Writing Setup. You can find the complete setup here on GitHub: https://github.com/ballantony/emacs-writing


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.

Java Course 8: Methods

Before you do this section, watch the videos here: https://www.dropbox.com/sh/v0xcqgjkia6brmm/AABRKcrZjwhkR1j14NsMcd4za?dl=0

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 TypeReturn TypeNameParameters
publicvoidspoons(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.

  1. Add private member variables String forename, surname
  2. Add private member variables int target, autumn, spring, summer
  3. Add a constructor method that will accept the parameters forename, surname, target
  4. Test the constructor by adding the following pupils: Joe, Bloggs, 70 and Jill, Cooper, 75
  5. Add accessor methods to setAutumn(), setSpring(), setSummer()
  6. Add accessor methods to getAutumn(), getSpring(), getSummer()
  7. Add the following grades to Joe Bloggs:  Autumn 55, Spring 65, Summer 75
  8. Add the following grades to JIll Cooper:  Autumn 50, Spring 60, Summer 70
  9. Add a method average() to return a double showing the average percentage a pupil has. Print out Joe and Jill’s average scores
  10. 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.
  11. Check this method works on Joe and Jill
  12. 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

Python Course 5: For Loops and Lists

For Loop Examples

Print the numbers 1 to 9

for k in range(1,10):
    print(k)

Countdown from 10 to 1

for k in range(10,0,-1):
    print(k)

Print the days of the week

days = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]
for day in days:
    print(day)

Print the five times table

for k in range(1,11):
    print("5 x {} = {}".format(k, 5*k))

For Loop Exercises

Write for loops to output the following sequences of numbers

  1. 0,1,2,3,4,5,6,7,8,9,10
  2. 0,2,4,6,8,10,12,14,16
  3. 1,2,3,4,5, … 97,98,99,100
  4. 7,14,21, … 63,70,77
  5. 20,18,16, … 4,2,0,-2
  6. 2,5,8,11,14,17,20,23,26,29
  7. 99,88,77,66,55,44,33,22,11,0
  8. Numbers 1 to 1000.
  9. Even numbers from 0 to 100.
  10. Odd numbers from -50 to 50
  11. All multiples of 3 up to 500.

Look at the days of the week example above. Use lists and for loops to do the following

  1. Print out the seasons of the year (Spring, Summer, Autumn, Winter)
  2. Create a list of the names of the four people closest to you. Use a for loop to print that list.

Extension

Look at the examples above.

  1. Use a for loop to print the 5 times table up to 12 x 5
  2. Use a for loop to print the 7 times table up to 12 x 7 in the form “3 x 7 = 21”
  3. Use a for loop to print the following sequence: 0.5, 0.4, 0.3, 0.2, 0.1, 0
  4. Use a for loop to print the following sequence: 0.03, 0.02, 0.01, 0, -0.01, -0.02, -0,03
  5. Use a for loop to print five random numbers between 1 and 10
  6. Use a for loop to print the first ten square numbers: 1, 4, 9, 16, 25, 36, 49, 64, 81, 100
  7. Use a for loop to print the first ten triangle numbers: 1, 3, 6, 10, 15, 21, 28, 36,45, 55

Java Course 7: Arrays

Iterate Through an Array

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]);
}

for each loops

String [] day =    {"Monday", "Tuesday", "Wednesday", 
		    "Thursday", "Friday", "Saturday", "Sunday"}; 

for(String s: day)
{
    System.out.println(s);
}

Exercise

  1. int [] numbers = {3,5,3,4,7,8}; Print out the second element of the array
  2. Make a String array of the months of the year. Print out all the months.
  3. Print out a random month of the year
  4. Create an int array recording the number of days in each month
  5. Print out all the months and the days in each month.
  6. 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
  7. 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.
  8. 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);
  1. Run the code to check it works
  2. Add some extra questions and answers. Check the code still works
  3. Add code to print out the correct answer if the user gets a question wrong
  4. Alter your code so that questions and answers are read in from text files

Python Course 4: Lists

Sample Code

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

  1. Look at the print(food[ 1 ]) line. What does the [ 1] do?
  2. How would you print the first item in the list?
  3. If a python list has seven items, what would number would the seventh item be?
  4. Look at the print(pupils[2:]) line. What does [2:] mean?
  5. Look at the print(days[2:4])line. What does [2:4] mean?
  6. Look at the print(days[-2]) line. What does [-2] mean?
  7. What does len do?
  8. What do max and min do?

Now write your own modules to do the following

  1. Create a list called months, containing the months in the year.
  2. Print out all the months, one after the other
  3. Use slicing (e.g. days[2:4]) to print out the spring months: March, April, May
  4. Print out the summer months: June, July, August
  5. Print out the first and last months of the year
  6. 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

  1. Reverse the following list: [“Sunday”,”Monday”,”Tuesday”,”Wednesday”,”Thursday”, “Friday”,”Saturday”] i.e. print out “Saturday”,”Friday”,”Thursday”,… etc
  2. Remove “eggs” from this list food = [“Sausage”, “eggs”, “Bacon”, “Beans”]
  3. Sort the following list into ascending order scores = [5,3,6,7,9,1,2]
  4. Insert “Mushrooms” into this list, just after “eggs”
  5. Count how many times “blue” appears in this list [“red”,”blue”,”blue”,”blue”,”red”,”blue”]

Your Day on a Page

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).

If I only had two pieces of advice for people heading of to college, the above would be one of them. Follow this link to see the other…

Using Outlook

Using Outlook?  You can subscribe to your Outlook Calendar from your Gmail account, if your college allows you to share calendars.

  1. Go to Outlook and click on Settings (the cogwheel in the top right hand corner)
  2. Click on View all Outlook settings at the bottom
  3. Choose Calendar
  4. Choose Shared Calendars, just below Events from email. If Shared Calendars doesn’t appear then bad news, you’re college won’t allow this.
  5. Go to Publish a calendar and choose the calendar you want to share. Hit publish and copy the ICS link.  You
  6. Now open your Google Calendar
  7. Click on Cogwheel and Settings in the top right
  8. Choose Add Calendar and then From URL
  9. Enter the ICS link you copied earlier

Java Course 6: while and do While Loops

Counting Down

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

  1. Use a while loop to print out the integers from 1 to 10
  2. Use a while loop to print out the even numbers from 2 to 20
  3. Use a while loop to print out the four times table
  4. Use a while loop to print out the five times table in the form “n x 5 = 5n”
  5. Use a while loop to print out the sequence 7,10,13,16,19,22,25
  6. Use a while loop to print out the sequence -0.3, -0.2, -0.1, 0, 0.1, 0.2
  7. Use a while loop to print out the sequence 64, 32, 16, 8, 4, 2, 1
  8. 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”;

  1. 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.”
  2. 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

  1. Make the computer keep asking “Are we there yet?” until the answer yes is input.
  2. 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.
  3. Modify program 2 so that the computer chooses a random number as the answer.
  4. 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.
  5. Wrtie a password checker. The user cannot proceed until they enter the correct password.
  6. 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);

Python Course 3: Data Types and Integers

Good Practice

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

Produces

0.1
0.2
0.30000000000000004
0.4
0.5
0.6
0.7
0.7999999999999999
0.8999999999999999
0.9999999999999999

Format the number for a neater answer

number = 0.1
while number <=1:
    print("{:.1f}".format(number))
    number = number + 0.1

0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
1.0

Number bases

You can format numbers into different bases as follows

print("{:d}".format(17))
print("{:b}".format(17))
print("{:X}".format(17))

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

  1. Write a program with two variables, length and width, that outputs the perimeter of a rectangle. Test it with length = 5 and width = 4.
  2. 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!)
  3. Now write a program to convert euros to pounds. Test it using the data Euro 7.40
  4. Prompt the user to input a number. Output the square of that number.
  5. Prompt the user to input two numbers. Output the average of those two numbers.
  6. Prompt the user to input three numbers. Output the sum and the average of those three numbers.
  7. 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

  1. Now write a program to convert Celsius to Fahrenheit. Use the test data to check your program.
  2. Write a program to convert Fahrenheit to Celsius. Again, use the test data below to check your program.

Test data

CF
032
1254
100212
-327
-180
-23-10

Java Course 5: for Loops

Print the numbers 1 to 9

(look very carefully at the semi colons below!)

for(int i= 1; i<10; i=i+1) {
    System.out.println(i);
}

Print the numbers 1 to 10

for(int i= 1; i<=10; i=i+1) {
    System.out.println(i);
}

Print the numbers 10 to 1

for(int i= 10 ; i>0; i=i-1) {
    System.out.println(i);
}

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().

for(int i = 0; i < 6; i++) {
	   for(int j = 0; j < i; j++) {
	       System.out.print("*");
	   }
	   System.out.println("");
}
*
**
***
****
*****

Exercise

Use for loops to print out the following:

  1. Numbers from 1 to 70 inclusive
  2. Numbers from 10 to -10 inclusive
  3. Odd numbers from 1 to 19 inclusive
  4. Even numbers from 10 to -20 inclusive
  5. The sequence 0.3, 0.4, 0.5, 0.6, 0.7
  6. The sequence 0.1, 0, -0.1, -0.2, -0.3
  7. The square numbers 1, 4, 9, 16, … 81, 100
  8. Five random integers between 1 and 10 inclusive
  9. All multiples of 3 up to 99
  10. The powers of 2 up to 28 (2, 4, 8, … 128, 256)

Nesting Loops

Use nested for loops to print out the following patterns

*
**
***
****
*****
******
*******
********
*********
*****
****
***
**
*
**
****
******
********
  1. 6!, pronounced 6 factorial, means 6x5x4x3x2x1. Write a program to print out the first 10 factorial numbers.
  2. Print out the times tables for 1 to 10. Print them out in the format “2 x 3 = 6”
  3. Print out a chess board grid using 1s and 0s e.g. 0 1 0 1 0 1 0 1, then 1 0 1 0 1 etc to make an 8×8 grid.

Extension

Print out the following patterns, either using nested for loops or some other way…

     *
    **
   ***
  ****
 *****
******
   *
  ***
 *****
*******
   *
  ***
 *****
*******
 *****
  ***
   *

Python Course 2: Bracelets and Snakes

The following code draws a snake

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

  1. Copy the code into your IDE and run it.
  2. Draw a snake 6 segments long
  3. Draw a red and green snake, 6 segments long.
  4. Draw pink and yellow snake, 6 segments long, but half the size of the previous snake.
  5. Use a for loop to simplify your code.
  6. 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

  1. Copy the code into your IDE. Watch out for indents!
  2. Run the code and see what it does.
  3. Add a function to draw a black_white() line
  4. Draw a chessboard using the functions provided
  5. Can you make you code more efficient, perhaps by using a for loop?
  6. What happens if you change the value of SIDE?
  7. 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)
  1. Use the function to draw a honeycomb pattern
  2. Can you make the honeycomb cover the whole screen?