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?

Live Notes and Archives

Suppose every year I plan a birthday party for my good friend, Jean Petite.

I have separate notes containing lists of presents, guests, food and drink, entertainment and so on.  I also have one master note named Project: Jean Petite Birthday 2022.  All the notes are tagged jpbirthday so I can find them quickly.

The party is a success. Even so, I create a new note outlining what went wells and even better ifs that I can refer to when planning next year’s party.

What happens when next year comes around?  Do I create new notes or use old ones? 

Some notes such as guests will just need to be modified, but others like food and drink may have to be done from scratch. I’ll probably want to create a new note for presents, but retain the old note so I don’t buy the same gift twice.

How do I stop the current notes getting mixed up with the old ones?

One way is to tag the notes by year: 2020, 2021, 2022 and then just filter to this year’s party.

Here’s a better way.

Create the following notebooks (the numbers are there so they appear in the correct order in the sidebar)

Put this year’s party notes in the In Progress Notebook. Put previous years’ notes in the Done Notebook.  Put reference notes, notes that don’t really change from year to year, in the cabinet.

Notebook View

That way if you want to see this years notes, just filter to In Progress and jpbirthday.  To see only reference notes, filter to Cabinet and jpbirthday.  To see everything, just filter to jpbirthday

The system makes use of the fact that a note can only be in one notebook at a time. Notes can be Todo or In Progress, but never both at the same time. 

A lot of people recommend using tags to represent these states, I think they’re wrong.  I’ve written about that here: You’re Using Folders and Tags the Wrong Way Round

Two more things about this system.

The filtered notes widget works really well with this system.  You can use them to see this year’s party notes at a glance.

And lastly, I used to have a separate Archive Notebook for old notes.  This is no longer needed, they all just go in the Cabinet

Stop tagging your notes with todo and done. Use notebooks.

Java Course 4: Selection

if statement

Scanner scan = new Scanner(System.in); 
System.out.println("How old are you?"); 
int age = scan.nextInt(); 
if (age < 18) { 
            System.out.println("You're too young to vote"); 
} else { 
            System.out.println("You're old enough to vote"); 
}

Operators

  • <, >, <=, >=
  • .equals() (for Strings)
  • .equalsIgnoreCase()
  • ! not
  • | or
  • & and

Examples

  • if (age>10 & age<19)
  • if(surname.equals(“Ballantyne”))
  • if(surname.equalsIgnoreCase(“Ballantyne”))
  • if(!answer.equals(“quit”))

Questions

Don’t forget to paste your code beneath the questions!

  1. Write a program that asks a user to input their BMI (body mass index) and then outputs their BMI Category as follows: Underweight = <18.5, Normal weight = 18.5–24.9, Overweight = 25–29.9, Obesity = BMI of 30 or greater
  2. Ask the user to input the name and age of two people. e.g. George, 32, Jill, 35. Get it to print out who is the youngest/oldest e.g. George is younger than Jill
  3. Honorific Generator: Write a program that accepts as input a person’s sex and age, and outputs the honorific Mr, Ms, Miss or Master
  4. Days in the month: Input the name of the month and whether or not it’s a leap year, then output the number of days in that month
  5. Write a quiz with 2 questions. Print out the users score out of 2 at the end of the quiz
  6. Write a password checker. Give the user three chances to enter the correct password.

Extension

  1. Personality test: Look at the personality test here http://www.personalityquiz.net/profiles/typology/index.htm Write a program that replicates this test.
  2. Allow the user to input a number. Output if the number is odd or even
  3. Search for the java switch case statement. Rewrite the last question using switch case.

Python Course 1: Turtle Graphics

Useful Code

Moving the Turtle

turtle.forward(100)
turtle.back(50)
turtle.right(90)
turtle.left(45)
turtle.goto(10,10)
turtle.home()
turtle.setheading(0)

Changing the Pen

turtle.pencolor('red')
turtle.penup()
turtle.pendown()
turtle.pensize(4)

Changing the Board

turtle.reset()
turtle.bgcolor('blue')
turtle.showturtle()
turtle.hideturtle()

Exercise

Draw the following

  1. A square with sides of length 100
  2. An equilateral triangle with sides of length 80
  3. A noughts and crosses board
  4. Draw a star by turning an angle of 144 degrees.
  5. A red hexagon on a blue background.

Lesson 2

The following program draws a purple square with a black border. Note the use of begin_fill() and end_fill()

import turtle

turtle.fillcolor('purple')
turtle.pencolor('black')

turtle.begin_fill()
turtle.forward(100)
turtle.left(90)
turtle.forward(100)
turtle.left(90)
turtle.forward(100)
turtle.left(90)
turtle.forward(100)
turtle.left(90)
turtle.end_fill()

The above requires a lot of cut and paste code: always a sign that there is a better way of doing things. Here’s one way:

import turtle

turtle.fillcolor('purple')
turtle.pencolor('black')

turtle.begin_fill()

for times in range(4):
    turtle.forward(100)
    turtle.left(90)

turtle.end_fill()

We are going to be drawing lots of squares. We can define the  code to draw a square as a function, that way we can reuse it. (Learning  to use functions is the main reason we are using turtle graphics!)

import turtle

def square():
    for times in range(4):
	turtle.forward(100)
	turtle.left(90)

turtle.fillcolor('purple')
turtle.pencolor('black')

turtle.begin_fill()
square()
turtle.end_fill()

We can add a size parameter to the function. Now we can draw squares of different sizes.

import turtle

def square(size):
    for times in range(4):
	turtle.forward(size)
	turtle.left(90)

square(50)
square(100)
square(200)

Exercise

1) Enter the following code and run it. Make sure you understand what it’s doing.

import turtle

def square():
    for times in range(4):
	turtle.forward(100)
	turtle.left(90)

for n in range(8):
    square()
    turtle.right(45)

2) What do you think the following code will do? Enter it and run it.

import turtle

def square(size):
    for times in range(4):
	turtle.forward(size)
	turtle.left(90)

for n in range(8):
    square(20*n)

3) Define a function to draw a triangle.
4) Use your triangle function to draw the following shape

Extension

  1. Write a function to draw a pentagon
  2. Write a function to draw a hexagon
  3. Draw a function that accepts a parameter number_of_sides that draws a  polygon with that number of sides
  4. Write a function to draw a chessboard
  5. Write a function to draw a honeycomb

Todos and Agenda Views

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


On my original Emacs Writing Set Up I had this many states:

(setq org-todo-keywords
      (quote ((sequence "TODO(t!)"  "NEXT(n!)" "|" "DONE(d!)")
              (sequence "REPEAT(r)"  "WAIT(w!)"  "|"  "PAUSED(p@/!)" "CANCELLED(c@/!)" )
	      (sequence "IDEA(i!)" "MAYBE(y!)" "STAGED(s!)" "WORKING(k!)" "|" "USED(u!/@)"))))

Now I only have three: TODO, IN PROGRESS and DONE

This is in line with my philosophy that productivity systems are great procrastinators. Thinking of new tagging systems and states for tasks is very absorbing. You can spend hours moving notes around and not doing any work.

Now I capture all my notes as TODOs, I change their state to IN PROGRESS and DONE as projects advance.

Calling org-agenda gives me a bird’s eye view of everything I’m working on. I can then filter down as appropriate.

For convenience, I wrote the following function to restrict the agenda to the current project. ou can see an example in my config.el file

(defun tb/agenda-restrict-this-project ()
    "Restrict agenda to current project"
    (interactive)
    (let ((org-agenda-files (list (projectile-project-root))))
      (org-agenda)))

I rely a lot on this function. When writing I hit SPC j p p (my keybinding: see my config.el file) to see the TODOs and IN PROGRESSes for the current project only.

You can read more in My Doom Emacs Writing Set Up

Capturing and Refiling Notes

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

Capturing Notes

Like any writer I’m always capturing ideas. I used to carry a notebook everywhere, now I capture ideas on my phone using either orgzly or Evernote.

When working in Emacs I use org-capture.

GTD means capturing ideas quickly. I used to have templates to capture to different locations, I realised that this was an unnecessary step. Now I either capture everything as a TODO, either directly to my gtd file, or directly to the story file I’m currently working on.

As org-capture requires you to select a template I wrote the following two functions. The first calls org-capture with the ’t’ template preselected, the second does the same but uses let* to change org-capture-templates to the current buffer for the current capture only.

(defun tb/capture ()
    "Capture to do without options"
    (interactive)
    (org-capture nil "t"))

  (defun tb/capture-to-this-buffer ()
    "Capture note to this buffer"
    (interactive)
    (cond  ((not  (eq major-mode 'org-mode))
            (message "Can't capture to non org-mode buffer"))
           (t
            (let* ((this-file buffer-file-name)
                   (org-capture-templates
                    `(("t" "Todo" entry (file+headline ,this-file "Captured")
                       "** TODO %?"))))
              (org-capture)))))

2. Refiling Notes

org-refile makes it easy to refile notes, particularly with a completion system like Vertico. On Doom Emacs this means hitting SPC m r r

Why Doom Emacs?

Way back in September I posted about my new Emacs Writing Set Up: Productivity Overview

Things might have appeared to have gone a little quiet since then. Behind the scenes, however, I’ve been making changes. One of these is to begin the process of moving my Emacs Writing Setup across to GitHub: https://github.com/ballantony/emacs-writing.

I’ll continue to blog relevant content here. Here’s the first, explaining why I’ve adopted Doom Emacs.


Emacs is incredibly configurable. I can choose, for example, the shape and contents of my agenda, the completion engine I use and even such things as the colour of my Todos.

And that’s a problem. Emacs allows me to configure many things that, if I’m honest, I really don’t care about.

It’s very easy to fall into the Emacs trap of sending time configuring the system rather than doing any actual work. I don’t want to think about how many hours I’ve spent experimenting with new packages and thinking of the perfect key bindings when I could have been writing stories instead. GTD can be a powerful procrastinator.

That’s why I’m happy to let someone else do it for me.

Enter Doom Emacs. So what if the TODOs are a different colour to the ones I use, and the capture templates aren’t quite the ones I was using, they’re still good. The key bindings may be different, but they’re far more extensive than any I’ve ever set up and I could probably finish a short story in the time it would take me to replicate them (and I can always override the few I really care about: C-e for example).

Most of all, Henrik Lissner, the creator of Doom Emacs, knows so much more about Emacs than I. I’ve learned so much simply tracking through his code. I wasn’t aware of Vertico until it turned up in the Doom config. I don’t have the time or inclination to try out all new Emacs packages. It’s great that someone else is doing this, and if I don’t like their choices, well, Doom is flexible enough for me to change them.

One final observation. Doom Emacs is fast to load. This is important to me. I like to take notes or begin writing when inspiration strikes. I can open Doom Emacs (or Orgzly on my mobile phone) and take a note in the time it takes apps such as Evernote or Notion to load.