# Programming Examples - Python

These are example Python programs that I've written as demonstrations of particular programming techniques or types of solution for both KS3 Computing and GCSE Computer Science. They are organised and categorised by technique/concept. There are further examples in the Python course and Microtips playlist on the Computing and ICT in a Nutshell YouTube channel. The idea is that students can see how the various methods can be used as part of a larger program after learning the basics of programming.

The sections are:

- repetition with for
- repetition with while
- nested loops
- lists and tuples
- multi-dimensional lists
- dictionaries
- character/string manipulation
- casting
- Boolean logic
- random numbers
- modular arithmetic (and other mathematical techniques)
- sorting and searching
- number bases
- compression techniques
- drawing with the turtle
- reading and writing files
- recursion
- object-oriented methods
- larger programs/projects

NB. Some examples appear twice (possibly with different descriptions) because they use multiple techniques, and some examples with similar names might approach the same problem in different ways.

## Repetition with For

- Ten Green Bottles
- Prime Numbers - using modular arithmetic to determine whether a number is prime

## Repetition with While

- Range Validation - repeatedly ask for a value until it's in the correct range
- Lottery Numbers - pick your lottery numbers
- Calculating Change - what is the minimum number of coins required?
- Roman Numerals - converting from denary to Roman Numerals

## Nested Loops

- Binary Counter - binary counter with no calculations
- Squares and Triangles - using nested loops to plot shapes
- Thief!* - you know the digits in a PIN but not their order; list the possible PINs
- Twelve Days of Christmas - display the lyrics and count the presents
- Stopclock - uses nested loops to count the time and Boolean logic to display it
- Change - show the minimum number of coins required to give a certain amount of change
- Triangle Numbers - demonstration of Gauss' assertion that any natural number is the sum of at most three triangle numbers
- Towers of Hanoi - play the classic mathematical game
- Vedic Square - Indian multiplication table
- Palindromic Products - uses nested loops to generate combinations

## Lists and Tuples

- Magic 8 Ball - without using
*if*s! - Lottery Numbers - pick your lottery numbers
- Pep Talk Generator - generates random phrases
- Classification* - a binary search tree stored in a list and used to identify an animal
- Sieve of Eratosthenes - generate lists of prime numbers
- 100 Doors - generate a list of square numbers
- Sudoku Solver - solves sudoku puzzles stored in lists
- Merge Sort - on numbers of your choice
- Rotation - rotates people a given number of places around a circular table
- Roman Numerals - uses a list to contain the values of the letters
- Hexadecimal - uses a list to match the letters A-F with their corresponding values
- Number Names* - describe numerical values in words, e.g. describe 23 as twenty-three.
- Phonetic Alphabet - asks the user for a string and spells it out using the phonetic alphabet
- Morse Code* - convert a string to Morse code
- Fruit Machine* - a simulation of a classic arcade machine
- No Duplicates - removing duplicate items from a list
- Sequences - identify and describe linear and quadratic sequences (like Babbage's Difference Engine)
- Die Model - with lists and unicode characters
- Memory Game - based on an OCR past-paper question
- Image Manipulation - experiment with manipulating images (similar to this page
- Flood Fill Game - a grid-based game with a very simple use of recursion

## Multi-Dimensional Lists

- Rock, Paper, Scissors - using a table to look up the winner
- Card Game (OCR Programming Task) - using a table to see which card wins
- Noughts and Crosses - play the classic game against the computer
- Multiple-Choice Quiz - asks questions and checks answers
- Quiz Generator - stores the questions in a list, with the choices as sub-lists
- Towers of Hanoi - play the classic mathematical game

## Dictionaries

- Scrabble Score - take and word and see how many points it would score in Scrabble
- OCR Town Election - answer to a question from a GCSE past paper
- Dictionary Compression - input a sentence and turn it into a list of unique words and a list of indexes that refer to the words
- Calculating Change - what is the minimum number of coins required?
- Interpreter - reads instructions from a file and interprets them (solution to one of the 2019 CyberGirl challenges)
- Dice Game - uses a dictionary to match usernames with passwords and real names
- Huffman Coding - uses a dictionary to count the frequency of each letter

## Character/String Manipulation

- Phonetic Alphabet - asks the user for a string and spells it out using the phonetic alphabet
- Morse Code* - convert a string to Morse code
- Anagrams - create an anagram from a given string
- Anagrams (Real Words) - create an anagram that's a real word from a given string
- Word Jumble - take a sentence and jumble the letters apart from the first and last letter of each word
- Caesar Shift Cipher* - simple encryption technique using ASCII codes
- Encryption with EOR - uses ASCII codes and bitwise EOR
- Worderama - Wordle-style word game
- Thousands Separator - formatting digits into groups of three
- Hangman - a simplified version of the classic game
- Die Model - with lists and unicode characters
- Towers of Hanoi - play the classic mathematical game
- Arboreal Symmetry - draw (and possibly decorate) a tree
- Tables - aligning text in tables
- Look-and-Say Sequences - generate an unusual type of mathematical sequence

## Casting

- Kaprekar's Contant - calculating the value by sorting the digits
- Palindromic Products - finding products that are palindromes

## Boolean Logic

- Plurals - add an 's' to plurals and choose the verb (e.g. is/are) without using if
- Converting Denary to Binary - using bitwise logic
- Coin Flip - game that tries to avoid the use of if
- Boolean Logic - a program that takes a Boolean operator and two inputs and outputs the result
- Encryption with EOR - similar to the WWII Lorenz cipher cracked by Colossus at Bletchley Park
- Seven Segments - simulate a seven-segment display for a given number
- Stopclock - uses nested loops to count the time and Boolean logic to display it
- Four Numbers, One Variable - uses shifting and bitwise logic to store four 8-bit numbers in a single variable
- Dice Game - uses Boolean logic to display the dice faces
- Connect 4 - uses a simple algorithm to play the classic game (and bitwise logic to manipulate the board)

## Random Numbers

- Lottery Numbers - pick your lottery numbers
- Distribution of Random Numbers - generate a set of random numbers, write the frequencies to a .csv file
- Estimating Pi - using the Monte Carlo method to estimate the value of pi
- Shuffle - create a pack of cards and deal them out between a given number of players

## Modular Arithmetic (and other Mathematical Techniques)

- Teams - put people into teams like a PE teacher!
- Shuffle - create a pack of cards and deal them out between a given number of players
- Caesar Shift Cipher* - simple encryption technique
- Prime Numbers - using modular arithmetic to determine whether a number is prime
- Fizz Buzz* - identify multiples and prime numbers
- Sieve of Eratosthenes - generate lists of prime numbers
- 100 Doors - generate a list of square numbers
- Perfect Numbers - a function to check whether a number is "perfect" (i.e. it's the sum of its factors)
- Solving Quadratics - including those with complex roots
- Monte Carlo method for estimating the value of pi
- Countdown - uses RPN to solve the numbers round in Countdown (I don't think it finds all solutions, though!)
- Spider Webs - draws spider webs and uses Pythagoras to check that they don't overlap
- Triangulate* - enter the three sides of a triangle and determine whether it's equilateral, isosceles, right-angled, etc.
- Denary to Hexadecimal Converter (uses integer division and modular arithmetic)
- Converting Binary to Denary (uses powers of two)
- Connect 4 - uses a simple algorithm to play the classic game; the board is stored using a binary representation
- 21 Game - a generalised version of the Nim variant in which the winner is the first player to count to 21.
- Light Bulb Energy Rating - a good exercise in scaling and using arrays/lists for reference
- Vedic Square - Indian multiplication table
- Arboreal Symmetry - draw (and possibly decorate) a tree

## Sorting and Searching

- Bubble Sort - gives GCSE-style explanation of Bubble Sort
- Selection Sort - gives GCSE-style explanation of Selection Sort
- Merge Sort - gives GCSE-style explanation of Merge Sort
- Insertion Sort - gives GCSE-style explanation of Insertion Sort
- Binary Search - gives GCSE-style explanation of the steps in a binary sort
- Card Trick - AQA specimen task that "guesses" a card by sorting it into the middle of the pile

## Number Bases

- Converting Denary to Binary - using bitwise logic
- Converting Denary to Hexadecimal (based on OCR past paper question)
- Denary to Hexadecimal Converter (simpler version)
- Converting Binary to Denary
- Roman Numerals - converting denary to Roman numerals
- Hexadecimal - functions to convert to and from, and also to add and multiply hexadecimal
- Binary Addition - adding two binary numbers
- Normalised Floating-Point Binary - calculating mantissa and exponent
- Standard Form - represent a denary number in standard form

## Compression Techniques

- Dictionary Compression - input a sentence and turn it into a list of unique words and a list of indexes that refer to the words
- Huffman Coding - required for the AQA GCSE
- Run-Length Encoding - once appeared on an Edexcel paper

## Drawing with Turtle

- Snowflakes - draw random snowflakes using a similar method to making them out of paper
- Spider Webs - draws spider webs and uses Pythagoras to check that they don't overlap
- Fireworks - using Newton's laws of motion and a dab of trigonometry to simulate a firework.

## Reading and Writing Files

- Distribution of Random Numbers - generate a set of random numbers, write the frequencies to a .csv file
- Hashing - hashing usernames and passwords stored in a text file
- Quiz Generator - writes its output to a file as HTML to create a webpage
- Dice Game - reads valid usernames from a file and keeps the high scores in another file
- Music Quiz - hangman-style game based on song titles
- Worderama - Wordle-style word game

## Recursion

- Palindrome - determine whether a string is palindromic
- Anagrams - use a recursive method to create an anagram
- Factorial* - calculator a factorial
- Prime Factorisation* - find the prime factors of a number
- Flood Fill Game - a grid-based game with a very simple use of recursion
- Sudoku Solver - solves Sudoku puzzles stored in lists
- Word Ladder - enter the first and last words to generate a word ladder

## Object-oriented Methods

- Rectangles - demonstration of properties, methods and operator overloading
- Card Game - version of the OCR 2019/20 programming task (game part only) done using OOP principles

## Larger Programs/Projects

- Rock, Paper Scissors - with multiple rounds
- Dice Game - look in the Files section for a list of valid usernames and passwords
- Quiz Generator - the user inputs questions and answers and the program creates a self-marking quiz as a web-page

You'll notice that I tend to use lists or tuples in my code to avoid the need for multiple IFs - I explain the technique in this article, and also demonstrate how it can be used to improve a common Magic 8 Ball program here. You can also make use of True and False to avoid the need for a lot of IFs in your code. Finally, there is a video on recursion, in which I explain how the factorial, palindrome and prime factorisation programs work.

If you prefer to use a local IDE, you can download programming examples in BASIC, JavaScript and Python.

* These programs are also solutions to * OCR Coding Challenges*.