More results...

Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors
post
page
Python IDE Dashboard

Python Basics

Python Cheat Sheet

Check the following Python instructions. These are all you need to know to start creating your first Python scripts!

You can also check our more advanced Python Helpsheet:
Python Cheat Sheet


Tagged with: , ,

Blackjack Challenge

blackjackIn this challenge you are going to create a blackjack game for one player. The computer will be the dealer.

Rules of the game


Source: wikipedia.

“Blackjack, also known as twenty-one, is the most widely played casino banking game in the world. Blackjack is a comparing card game between a player and dealer, meaning that players compete against the dealer but not against any other players. It is played with one or more decks of 52 cards. The object of the game is to beat the dealer, which can be done in a number of ways:

  • Get 21 points on the player’s first two cards (called a blackjack), without a dealer blackjack;
  • Reach a final score higher than the dealer without exceeding 21; or
  • Let the dealer draw additional cards until his or her hand exceeds 21.

The player or players are dealt an initial two-card hand and add together the value of their cards. Face cards (kings, queens, and jacks) are counted as ten points. A player and the dealer can count his or her own ace as 1 point or 11 points. All other cards are counted as the numeric value shown on the card. After receiving their initial two cards, players have the option of getting a “hit”, or taking an additional card. In a given round, the player or the dealer wins by having a score of 21 or by having the highest score that is less than 21. Scoring higher than 21 (called “busting” or “going bust”) results in a loss. A player may win by having any final score equal to or less than 21 if the dealer busts. If a player holds an ace valued as 11, the hand is called “soft”, meaning that the player cannot go bust by taking an additional card; 11 plus the value of any other card will always be less than or equal to 21. Otherwise, the hand is “hard”.

The dealer has to take hits until his or her cards total 17 or more points. (In some casinos the dealer also hits on a “soft” 17, e.g. an initial ace and six.) Players win if they do not bust and have a total that is higher than the dealer’s. The dealer loses if he or she busts or has a lesser hand than the player who has not busted. If the player and dealer have the same total, this is called a “push” and the player typically does not win or lose money on that hand.”

Final Product


You can check this game online.

Your Challenge


Your challenge is to recreate this game for one player only using your chosen programming language (e.g. Python, JavaScript…). The end-user will play against the computer (the dealer).

To start with you may want to create this game using a text-based interface. Cards could be displayed as follows:

  • ♠ As (Ace of spade), 2s, 3s, … 9s, 10s, Js, Qs, Ks
  • ♥ Ah (Ace of heart), 2h, 3h, … 9h, 10h, Jh, Qh, Kh
  • ♣ Ac (Ace of club), 2c, 3c, … 9c, 10c, Jc, Qc, Kc
  • ♦ Ad (Ace of diamond), 2d, 3d, … 9d, 10d, Jd, Qd, Kd

You may also want to investigate unicode characters to display the selected cards in a more visual way.

Tips / Questions to get you started


Before getting started you may want to ask yourself the following questions?

  • What data structure could I use to create the deck of 52 cards?
  • Once I have stored all 52 cards in my data structure, how can I shuffle the cards?
  • What variables will I need to store the initial amount ($) the player has, the value of the bet ($), the total number of points of the dealer, the total number of points for the player?
  • Input: What information do I need to ask/retrieve from the end-user and when does the program need to ask for that information?
  • Output: What information do I need to display to the end-user during the game? (and when in the game?)
  • When or how does the game end?
  • How can I break up this project into smaller achievable steps? What would be the first few steps that I would then focus on?

Complete the Code…


Graphical User interface


Should you decide to create a full graphical user interface (e.g. as a webpage using HTML & JavaScript or as a Python program using graphical library such as PyGame) then you can download the graphics for each of the playing cards from wikimedia.
playingcards
unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area
Tagged with: , ,

Number Sequences

Learning Objectives


In this challenge we are going to apply our programming skills to perform some arithmetic operations. We will use arithmetic operators such as +, – and * as well as for loops to repeat instructions.

Context / Starter activity


A primary teacher likes to start her maths lesson by displaying a number sequence maths challenge on the board. Here are the last three challenges she has used with her class. Can you solve these?

Number Sequence #1:number-sequence-2
Number Sequence #2:number-sequence-3
Number Sequence #3:number-sequence-1

Number Sequences


There are different types of number sequences. Let’s investigate the most widely used types of number sequences.
You may want to read this page first: https://www.mathsisfun.com/numberpatterns.html

Arithmetic Sequences

An Arithmetic Sequence is made by adding the same value each time. When creating an arithmetic number sequence you have to decide of a starting number (e.g. “2”) and an increment (e.g. “3”)

number-sequence-diagram-1

Geometric Sequences

A Geometric Sequence is made by multiplying by the same value each time.
When creating a geometric number sequence you have to decide of a starting number (e.g. “2”) and a multiplier (e.g. “3”)

number-sequence-diagram-2

Square Numbers

1,4,9,16,25,36…

This sequence consists of calculating the squares of whole numbers.

number-sequence-diagram-3

Incremental Sequence

1, 2, 4, 7, 11, 16, 22, 29, 37, …

This sequence is generated by adding an “increasing” number, that is a number that each time is incremented by 1 as we progress through the number sequence. Not clear? Check the diagram below.

number-sequence-diagram-4

Fibonacci Numbers

1, 2, 3, 5, 8, 13, 21, 34, …

The Fibonacci Sequence is found by adding the two numbers before it together.

  • The 3 is found by adding the two numbers before it (1+2)
  • The 5 is found by adding the two numbers before it (2+3)
  • The 8 is found by adding the two numbers before it (3+5)

number-sequence-diagram-5

Python Code


Arithmetic Sequence


Triangular Numbers


Fibonacci Numbers

Challenge #1


Edit some of the above scripts to create other number sequences such as:

  • Arithmetic sequences using a different starting number and increment,
  • Geometric sequences,
  • Square numbers sequence.

You can also adapt or even mix these techniques to create your own number sequences!

Challenge #2


Adapt your scripts so that the program asks the end-user the question: “What number comes next in the sequence?” The user has to type their answer. The program should check if they have got the right answer or not.

The bear hunt

repetitive-storyThis challenge is inspired from Michael Rosen and Helen Oxenbury’s children book “We are going on a bear hunt”. In this story, a family skids down a grassy slope, swishes across a river, sludges through mud and finally sees a bear who chases them all the way back to their home.

This story is based on a repetitive verse where the same verse is repeated several times and each time only a few words are changed.

So let’s see how we could apply our programming skills to print the words or lyrics of a repetitive story or song.

Learning Objectives


In this post we will investigate how to use a subroutine do write code more efficiently. We will also pass parameters to our subroutine.

You will also use string concatenation techniques to join two strings together.

Investigate the code below. See how we have defined a subroutine called printVerse() and used two parameters for this subroutine: obstacle and onomatopoeia (a word that represents a sound: e.g. splosh).

Challenge #1


Using a similar approach write a piece of code to print the lyrics of the following song:

    Five little speckled frogs
    Sat on a speckled log
    Eating some most delicious bugs – yum, yum
    One jumped into the pool
    Where it was nice and cool
    Now there are four green speckled frogs – glub, glub.

    Four little speckled frogs
    Sat on a speckled log
    Eating some most delicious bugs – yum, yum
    One jumped into the pool
    Where it was nice and cool
    Now there are three green speckled frogs – glub, glub.

    Three little speckled frogs
    Sat on a speckled log
    Eating some most delicious bugs – yum, yum
    One jumped into the pool
    Where it was nice and cool
    Now there are two green speckled frogs – glub, glub.

    Two little speckled frogs
    Sat on a speckled log
    Eating some most delicious bugs – yum, yum
    One jumped into the pool
    Where it was nice and cool
    Now there are one green speckled frogs- glub, glub.

    One little speckled frogs
    Sat on a speckled log
    Eating some most delicious bugs – yum, yum
    One jumped into the pool
    Where it was nice and cool
    Now there are no green speckled frogs – glub, glub.

Challenge #2


Using a similar approach write a piece of code to print the words of the “10 ladybugs” story by Melanie Gerth and Laura Huliska-Beith:

    Ten little ladybugs sitting on a vine,
    along came a butterfly – then there were…

    Nine little ladybugs skipping on a gate,
    along came a caterpillar – then there were…

    Eight little ladybugs looking up at heaven,
    along came a bird – then there were…

    Seven little ladybugs resting on sticks,
    along came a grasshopper – then there were…

    Six little ladybugs flying near a hive,
    along came a bumble bee – then there were…

    Five little ladybugs sleeping by the shore,
    along came a fish – then there were…

    Four little ladybugs climbing up a tree,
    along came a turtle – then there were…

    Three little ladybugs drinking up dew,
    along came a duck – then there were…

    Two little ladybugs basking in the sun,
    along came a frog – then there was…

    One little ladybug sitting all alone,
    along came a breeze – then she was HOME!

Tagged with: , ,

Logic Gates Diagrams

Learning Objectives


In this post you will practise drawing logic gates diagrams using the following logic gates:

  • AND Gate
  • OR Gate
  • XOR Gate
  • NOT Gate

First you will need to learn the shapes/symbols used to draw the four main logic gates:

Symbol Logic Gate
AND-Gate AND

OR-Gate OR

XOR-Gate XOR

NOT-Gate NOT

Logic Gate Diagrams


diagram-1

diagram-2

diagram-3

diagram-4

Your Task


Use our logic gates diagram tool to create the diagrams as follow: (Click on the following equations to draw their logic gates diagrams)

logic-gates-title-1

logic-gates-title-2

logic-gates-title-3

Logic Gates Diagram CreatorCreate your own logic gates diagram

Dry Run Testing & Trace Tables

Learning Objectives


You have just completed a piece of code but when you run it, it does not behave as expected.

One way to check and troubleshoot your code is to perform a dry run using a trace table.

Trace tables are used by programmers to track the values of variables as they change throughout the program. This is useful when a program is not producing the desired result.

Context / Starter activity


A primary teacher likes to start her maths lesson by displaying a number sequence maths challenge on the board. Here are the last three challenges she has used with her class. Can you solve these?

Number Sequence #1:number-sequence-2
Number Sequence #2:number-sequence-3Number Sequence #3:number-sequence-1

The primary teacher decided to create some Python script to help them create similar number sequences.

Here is the pseudo-code for her first script:

number = 3
PRINT number
FOR  i  from 1 to 3:
      number = number + 5
      PRINT number
PRINT "?"

To make sure her script is working she decided to complete a dry run test using a trace table. See animation below:
trace-table-s

View the complete trace table.

Challenge #1


Step 1: Complete the trace table for the following script:

number = 5
PRINT number
FOR  i  from 1 to 3:
      number = number + i
      PRINT number
PRINT "?"

Step 2: Implement this code using a high level programming language (e.g. Python) and compare your trace table with your actual output of your program.

Challenge #2


Step 1: Complete the trace table for the following script:

number1 = 2
number2 = 5
PRINT number1
PRINT number2
FOR  i  from 1 to 4:
      number1 = number1 + number2
      PRINT number1
      number2 = number1
PRINT "?"

Step 2: Implement this code using a high level programming language (e.g. Python) and compare your trace table with your actual output of your program.

Challenge #3


Think of your own number sequences. Write the pseudo-code, the trace table and implement them using a high level programming language (e.g. Python).

Modular Design

lego-bricks

Learning Objectives


When working on larger projects, you will need to carefully plan ahead the structure of your applications/programs. You will have to break down your application into smaller modules and will most likely want to give your end-users the option to navigate through all these sub-modules.

This top-down/modular approach to designing and structuring your applications will enable you to break down what may seem like a very complex project into smaller, achievable modules that you will complete progressively one at a time.

In order for your end-user to access to all the modules available you may be willing to offer a menu structure. This could use drop down menu bars, touch screen icons/menus or a text-based menu system used with a command prompt to interact with the end-user.

In this challenge we will focus on this latest approach: a text-based menu system with a command prompt to retrieve user inputs/choices. Note that the logic behind this would be similar with other types of menus based on a Graphical User Interface or touchscreen or even with a voice activated interface.

Context


We are about to create our first video game and have produced the following top/down modular design for it.
Main-Menu

Let’s look at how this would look like once implemented using Python:

Option #1:


Option #2:


This option is a bit more complex and enables the end-user to navigate between menus and sub-menus.

Option #3:


This code is exactly the same as the code used for option #2. However by splitting the code into mutilple .py files it looks neater and easier to maintain.

When using a modular approach to breaking down a large project we often spread the code accross multiple files. It makes troubleshooting a lot easier.

Improvements


There are many ways we could improve this menu system such as:

  • Add validation methods to make sure the user only enters the right type of menu options,
  • Add a Graphical User Interface to make this menu more visual. To do so we could use a Python library such as PyGame or TkInter.

US Population

Your challenge isUS-map to write a Python program that will read through the data from the US States.txt text file provided below in order to find out:

  • The total population in the USA (by adding the population of each of the 51 states,
  • The average population per state,
  • The state which has the highest population,
  • The state which has the lowest population,
  • A list of all 51 states with their population as a percentage of the total US population.

The given text file is a CSV file (Comma Separated Values) with the following fields:

State , State Code , Population (in year 2000)


TextFile
US States.txt

Learning Objectives


By completing this challenge you will learn how to read through and extract data from a CSV file. You may want to read this blog post about handling text files using Python first.

Complete the code


The code below read through the text file line by line using a for loop. For each line it extracts the data using the split() method.

Challenge #2: Compare State Population Game


Use this text file to create a Python game where the computer randomly displays two states on the screen (with their full name and their 2-letter code) and asks the user to guess which of the two states has the largest population. If the user guesses it right, they score one point otherwise they lose one point.

US-map

unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area
Tagged with: ,

UK Postcodes – Distance Calculator

haversine

Challenge


Your challenge is to write a Python program that asks the end-user to enter two valid UK postcodes and in return displays the distance in miles or km between those two postcodes.

To complete this challenge you will first find the exact longitude and latitude of both the postcodes entered by the end user. The following text file contains a list of all the UK outer codes (first part of a postcode) with their exact longitude and latitude.


TextFile
UK Postcodes.csv

Once your program will have retrieved the longitude and latitude of both locations (postcodes) it will use the Haversine formula to calculate the exact distance between these two locations.

Haversine Formula


The Haversine formula is an equation important in navigation, giving great-circle distances between two points on a sphere from their longitudes and latitudes.

This formula will enable us to calculate the shortest distance over the earth’s surface – giving an ‘as-the-crow-flies’ distance between the two locations (ignoring any hills they fly over, of course!).

You can read more about the haversine formula on this wikipedia page.

To complete this challenge you will also need to investigate the use of trigonometric functions from the math library.

haversine-formula-1

haversine-formula-2

haversine-formula-3

Note that when completing this challenge, longitudes and latitudes are given in degrees, not radians.


Once completed you can check your distances online.

unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area
Tagged with: , ,

Team Generator

team-1

Context


A primary school teacher has a class of 30 pupils. (See attached file called class.txt).
They would like you to create a Python script that will help them make teams for group activities.

Your program should ask the number of teams the teacher needs (between 2 and 6), read the names of the pupils from the text file and assign pupil randomly to teams. However there should be roughly (or exactly when possible) the same number of pupils in each team.


TextFile
class.txt


team-2

Learning Objectives


In this challenge you will learn how to read data from a text file. The file given is a CSV file. CSV stands for Comma Separated Values. Which means each record (pupil) is stored on a line of the file. On each line the two fields (firstname and lastname) are separated using a comma.

Before attemtping to complete this challenge, make sure you read about file handling operations using Python.

Complete the code

team-3

Challenge #2: Random Name Picker


The primary teacher sometimes asks questions to the whole class. They would like to have a program that helps them randomly pick a name from their class list. They would like to make sure that once a name has been picked up once, they cannot be picked up a second time.

Using the class.txt file, write a Python program to meet the teacher’s requirements.

unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area