Code is Poetry

Brian Bilston has written a History of Modern Art in Poetry.  I  wondered what it would be like to do something similar in various programming languages.

Here’s the original poem:

Roses are red
Violets are blue
Sugar is sweet
And so are you

Haskell

Here’s the poem constructed using a zip statement in Haskell

Prelude> zip ["roses","violets","sugar","you"]["red","blue","sweet","sweet"]
[("roses","red"),("violets","blue"),("sugar","sweet"),("you","sweet")]

The list produced holds the relationship that sugar is sweet and you are sweet. The comparison between “you” and sugar is not made clear.

Lisp

Here’s the poem stored as an alist in Lisp

(setq poem '(("roses" . "red") ("violets" . "blue") ("sugar" . "sweet")("you" . "sweet")))
(mapcar (lambda (x) (concat (car x) " are " (cdr x))) poem)

I’ve gone one stage further here, using a mapcar function to produce something that looks a little bit more like the original poem, however we’re still missing the connection between “you” and sugar.

("roses are red" "violets are blue" "sugar are sweet" "you are sweet")

Python

Of course, sugar are sweet isn’t right.   Let’s try some Python.

poem = {"roses":"red","violets":"blue","sugar":"sweet","you":"sweet"}

for key, value in poem.items():
    if key == "sugar":
        print(key, "is" ,value)
    else:
        print(key, "are", value)

This output is at least grammatically correct.

roses are red
violets are blue
sugar is sweet
you are sweet

Java

Java can do something similar using a HashMap

Map<String, String> poem = new HashMap<String, String>();

        poem.put("roses", "red");
        poem.put("violets", "blue");
        poem.put("sugar", "sweet");
        poem.put("you", "sweet");

        for (Map.Entry<String, String> entry : poem.entrySet()) {
            if(entry.getKey().equals("sugar")){
                System.out.println(entry.getKey() + " is " + entry.getValue());
            } else{
                System.out.println(entry.getKey() + " are " + entry.getValue());
            }
            
        }

But we’re still no closer to conveying the connection between “you” being sweet, just like sugar is sweet.

Fortunately, Java allows us to use some object oriented design to better convey the meaning of the poem.

In the example below I’ve used an interface to allow sweetness to be applied to both sugar and to the special one to whom the poem refers.  The comparison is at last made clear.  As there can only be one true love, it seemed reasonable to make a singleton class for TheOne, inherited from a regular person.

Run the code and the poem is printed out properly, just like the original.  More importantly though, the concepts to which the poem refers are properly encapsulated and related.

The original poem was only 4 lines long.  My implementation takes 80 lines, but I think you’ll agree I’ve done a rather better job, providing clarity and removing any ambiguity.

public class Love {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Flower [] rose = new Flower[12]; // 12 roses in a bunch
        Flower [] violet = new Flower[30]; // more violets in bunch
        Sugar sugar = new Sugar();
        TheOne myLove = TheOne.getInstance();  // Singleton class
        // There can only be one true love
        
        rose[0] = new Flower();
        rose[0].setColour("red");  // colour is static so only need
                                    // to instantiate one here
        
        violet[0] = new Flower();
        violet[0].setColour("blue");
        
        System.out.println("Roses are " + rose[0].getColour());
        System.out.println("Violets are " + violet[0].getColour());
        System.out.println(sugar.sweet());
        System.out.println(myLove.sweet());
    }
    
}

class Flower {
    private static String colour;
    
    public void setColour(String colour){
        this.colour = colour;
    }
    
    public String getColour (){
        return colour;
    }
}

class Sugar implements Sweetness {

    @Override
    public String sweet() {
        return "Sugar is sweet";
    }
    
}

class Person {
    public String sweet()
    {
        return "Not sweet";
    }
}

class TheOne extends Person implements Sweetness{
    private static TheOne instance = null;
    
    private TheOne()
    {
        
    }
    
    public static TheOne getInstance()
    {
        if(instance == null)
            instance = new TheOne();
        
        return instance;
    }

    @Override
    public String sweet() {
         return "And so are you";
    }
}

interface Sweetness {
    String sweet();
}

Functions and Parameters (Level 6)

Sample Code

def hello(name):
    answer = "Hello " + name
    return answer

print(hello("George"))
print(hello("Gill"))
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.

While Loops (Level 5)

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 Paris?")

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 Paris?")
    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!")

Exercise

  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)
  1. 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!”

Write a program to simulate the above.

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

Data Types: int and float (Level 3)

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 " + str(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(str(miles) + " miles = " + str(kilometers) + " 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

C F
0 32
12 54
100 212
-3 27
-18 0
-23 -10

4 – For Loops (Level 5)

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

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

Print the five times table

for k in range(1,11):
    print("5 x {0} = {1}".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.

Extension

  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

3 – Python Lists (Level 5)

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"]
for day in days:
    print(day)
print(food[1])
print(pupils[2:])
print (days[2:4])
print(pupils[:2])
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

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”]

2 – Selection (Level 4)

Sample Code

 Simple Selection

surname = input("Enter your surname\n")
gender = input("Are you M or F?\n")
if gender == "M":
    print("Hello Mr " + surname)
else:
    print("Hello Ms " + surname)

Operators

day = input("Name a day that starts with the letter S\n")
if day == "Saturday" or day == "Sunday":
    print("Correct")
else:
    print("Wrong")
year = int(input("Input your year\n"))
if year>=7 and year <=9:
    print("You are in KS3")
else:
    print("You are not in KS3")

Exercises

  1. Prompt the user as follows: “What’s the capital of France?” Output “Correct” if they enter “Paris”, output “Incorrect” otherwise
  2. Prompt the user as follows: “Name a month that starts with the letter A”: Output “Correct” if they enter “April” or “August”, output “Incorrect” otherwise
  3. Prompt the user as follows: “Name a Beatle”. Output “Correct” if they enter “John”, “Paul”, “George” or “Ringo”, output “Incorrect” otherwise
  4. Prompt the user to enter their age. If they are 18 or over output “You are old enough to vote.” Otherwise, output “You are too young to vote”
  5. Prompt the user to enter their age. If they are aged between 4 and 16 output “You should be at school”
  6. An online whisky shop charges for shipping as follows: One bottle, £5.99; two to five bottles, books £7; more than five bottles, free. Prompt the user to enter the number of bottles bought and output the shipping cost.
  7. An online bookshop charges shipping as follows: Orders less than £10, £2.99; orders £10 and over, free; add on £2.50 for all orders if next day delivery is selected. Prompt the user to enter the cost of the order, and then prompt for next day delivery. Output the shipping cost.

Extension

The modulo operator (%) is very useful. It works out the remainder when one number is divided by another. So
10 % 2 = 0 (Because 10/2 = 5 remainder 0)
10 % 3 = 1 (Because 10/3 = 3 remainder 1)
Use the modulo operator to solve the following problems.
  1. Prompt the user to enter a number. Output if the number is odd or even.
  2. Prompt the user to enter a humber. Output Fizz if the number is divisible by 3, otherwise just output the number
  3. Extend the above problem so that the computer will output Fizz if the number is divisible by 3, output Buzz if the number is divisible by 5 and otherwise just output the number.
  4. Now extend the above problem again so that the computer will output Fizz if the number is divisible by 3, output Buzz if the number is divisible by 5, output Fizz Buzz if the number is divisible by both 5 and 3 and otherwise just output the number.

1 – Input and Output (Level 3)

Sample Code

Escape Characters

Escape Sequence Character
\n newline
\t tab
\b backspace
\” double quote
\’ single quote
\\ backslash
\uDDDD Unicode character
print("\u0041")

Simple Input

name = input('Enter your name: ')
print('Hello', name)

Format Output

pounds = 2
exchange = 1.38
print("{0} Pounds = {1} Euros".format(pounds, exchange))

Exercise

  1. Use the \t escape character to print out a noughts and crosses grid, as shown below in fig. 1
  2. Prompt the user to enter their (name). Print out “Hello” (name) “I hope you’re well”
  3. Prompt the user to enter their (name) and their (age). Print out (name) ” is ” (age) “years old.”
  4. Prompt the user to enter two numbers. Print out the sum of those numbers.
  5. Prompt the user to enter two numbers. Print out the average of those numbers.
  6. Prompt the user to enter their name and their age. Print out “Hello” (name) “you are” age “years old.”
  7. Get the computer to tell a Knock Knock Joke. “Knock Knock” (wait for input) “Olivia” (wait for input) “No you don’t, I live here”
  8. Print the dandelion shown in fig. 2
Table 1: fig. 1
o x
x o
o x o

fig. 2

      .--.
    .'_\/_'.
    '. /\ .'
      "||"
       || /\
    /\ ||//\)
   (/\\||/
______\||/_______

Extension

  1. Look up the current pounds to dollars exchange rate. Write a program that prompts the user to input a number of pounds and then outputs how many dollars that is.
  2. To work out your BMI, divide your weight in kilograms by your height in metres squared. In other words BMI = w / h*h. Write a program that prompts the user to input their weight and height, and then outputs their BMI.

Python Levels

The Daily Python questions are levelled as follows. It’s my experience that nearly all students are capable of coding at level 3. Some students need help to progress to subsequent levels.

The following are based on my department’s experience in teaching coding. You may disagree with the levels, you may wish to use them as a starting point for further development, either way, I’d be very interested to hear your opinion.

The level numbers start at 3 to fit in with the old KS3 levelling system.

Level 3

  • Output Strings and numbers
  • Concatenate Strings and numbers
  • Use variables
  • Perform simple arithmetic operations
  • Prompt for user input

Level 4

  • Use if statements with Strings
  • Use if statements with numbers
  • Use if else statements
  • Understand difference between addition and concatenation.

Level 5

  • Elif
  • For loops
  • A list
  • Concise Comments

Level 6

  • Boolean operators AND OR NOT
  • Counts and iterations while loops
  • Nest if statements
  • Functions and parameters

Level 7

  • Nest for, while loops
  • 2D Arrays
  • Scope

Level 8

  • Recursion
  • Modular programming
  • Self-documenting code: high level commenting

– Loop Solutions

2 Loop Solutions

 1: def oneToTen():
 2:         for i in range(1,11):
 3:                 print(i)
 4: 
 5: def oneToTenAcross():
 6:       print("|", end="")
 7:         for i in range(1,11):
 8:                 print(i,"|",end="")
 9: 
10: def oddNumbers():
11:         for i in range(1,21,2):
12:                 print(i)
13: 
14: def squares():
15:         for i in range(1,11):
16:                 print(i*i)
17: 
18: def random4():
19:         for i in range(1,5):
20:                 print(random.randint(1,10))
21: 
22: def even(n):
23:         for i in range(1,n+1):
24: 
25: 
26: def powers(n):
27:         for i in range(1,n+1):
28:                 print(2**i)
29: 
30: def triangle():
31:         for i in range(1,6):
32:                 for j in range(1,i+1):
33:                         print("*", end = "")
34:                 print()
35: 
36: def areWeThereYet():
37:         s = "no"
38:         while (s != "yes"):
39:                 s = input("Are we there yet?")
40:         print ("Good!")
41: 
42: 
43: def tableSquare():
44:         for i in range(1,5):
45:                 for j in range (1, 5):
46:                         print("|",i*j, "\t", end = "")
47:                 print("|")
48: 
49: def tableSquares(n):
50:         for i in range(1,n+1):
51:                 for j in range (1, n+1):
52:                         print("|",i*j, "\t", end = "")
53:                 print("|")