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

Java Course 9: Test Yourself

Write programs to do the following

  1. Prompt the user to enter the length and width of a square. Output the area of the square.
  2. Prompt the user to enter a test score. Output their grade: Under 100 – Fail, Under 120 Pass, Under 130 Merit, 130+ Distinction
  3. Use a for loop to print out the following sequence: 12, 15, 18, 21, 24, 27
  4. Use a for loop to print out the first 8 square numbers: 1,4,9,16,25,36,49,64
  5. Make a counting program. Use a do while loop to keep asking “Another?” until the user enters “n”. Output the number of times the loop repeated
  6. Create a file called names.txt containing the names John, Paul, George and Ringo. Write a program the reads in the text file and prints out the data
  7. Create a string array containing the four seasons: spring, summer, autumn and winter. Print out a random season

Extension

Write a program that prints out the verses of the song the Twelve Days of Christmas. You will get bonus marks for elegant coding.

On the first day of Christmas
my true love sent to me:
A Partridge in a Pear Tree

On the second day of Christmas
my true love sent to me:
2 Turtle Doves
and a Partridge in a Pear Tree

On the third day of Christmas
my true love sent to me:
3 French Hens
2 Turtle Doves
and a Partridge in a Pear Tree

.
.
.

On the first day of Christmas
my true love sent to me:
12 Drummers Drumming
11 Pipers Piping
10 Lords a Leaping
9 Ladies Dancing
8 Maids a Milking
7 Swans a Swimming
6 Geese a Laying
5 Golden Rings
4 Calling Birds
3 French Hens
2 Turtle Doves
and a Partridge in a Pear Tree

Python Course 6: String Handling

Sample Code

s = "This is a sample string"
print(s)
print("It contains this many characters: ", len(s))
print("Here it is in upper case...")
print(s.upper())
print("Here it is split into a list:")
words = s.split()
for word in words:
    print(word)
print("Here it is split by the letter \'a\'")
words = s.split("a")
for word in words:
    print(word)
print("Here's the characters from index 1 to 3")
print(s[1:3])
print("Here's the sample string with the letter s changed to z")
print(s.replace("s","z"))
print("And now with the letter s changed to sausage...")
print(s.replace("s","sausage"))
print("And now with the spaces removed...")
print(s.replace(" ",""))
print("Notice the original string is unchanged... ")
print(s)

Exercise

  1. Output the length of the String “I never saw a purple cow”
  2. Convert the String “I never saw a purple cow” to uppercase and output the resulting string.
  3. Use \n to create a string that prints out the words to Happy Birthday. Make it yourself (Happy Birthday dear Kevin). Print out the string
  4. Use the replace method to print out the words to Happy Birthday, this time for Mr Lightfoot
  5. Output the String “I never saw a purple cow” as a list of separate words.
  6. Output the initial letters of the String “I never saw a purple cow”
  7. Prompt the user to enter a String. Output a list of the initial letters of the words input. Example: input “British Broadcasting Corporation” output “B”,”B”,”C”.

Extension

  1. Prompt the user to enter a String. Output a String with the vowels replaced with *’s. Example: input “I never saw a purple cow” output “* n*v*r s*w * p*rpl* c*w”
  2. Prompt the user to enter a string. Output the string as separate words in alternate upper and lower case: SO it LOOKS like THIS example
  3. Output the following list as one String: words = [“Calling”, “occupants”, “of”, “interplanetary”, “craft”]
  4. Prompt the user to enter a string. Output the number of vowels in the String.
  5. A palindrome is a string that reads the same forwards and backwards. Examples are “radar” and “rotavator”. Write a program that accepts a String as input and outputs “Palindrome” if the String is a palindrome, and “Not Palindrome” otherwise.

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