More results...

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

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

Class Register

class-register

Learning Objectives


In this challenge we are going to focus on accessing a text file in Python to:

  • Read the content of the file line by line,
  • Write data to a new file.

Before completing this challenge, you should read about the main file handling operations using Python.

Your Challenge


Your challenge consists of writing a Python script that could be used by a teacher to take the register at the beginning of the lesson.

Your program will need to:

  1. Read the text file called classList.txt, line by line.
  2. For each student (line of the text file) the program should ask the teacher if the pupil is pesent (“/” code), absent for medical reasons or illness (“M” code), on a school trip (“T” code), or absent with no reason provided yet (“X” code).
  3. The program should store the teacher’s input alongside with the name of each pupil into a new text file called “register.txt”.

To complete this challenge you will need to use the class list text file:


TextFile
ClassList.txt

Python Code

Complete the Python code below…

unlock-access

Solution...

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

Times Table Challenge

x-times-table-challenge

Learning Objectives


By completing this challenge you are going to perform arithmetic operations in Python. You will also learn how to manipulate counted loops (for loops) and how to combine loops together using nested loops.

Times Table


Look at the code below. It’s asking the user to type a number and then it displays the times table for that number using a for loop.

Nested Loops


When you insert a loop within a loop, you are using “nested loops”.
Check the code below that uses a nested loop.

Challenge #1


Tweak the code above to display a full times table:
times-table

Challenge #2


Tweak your code to display a number grid as follows:
number-grid
unlock-access

Solution...

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

Higher or Lower Game

Higher-Or-LowerFor this challenge you will design and write a program to play against the computer.
The computer will display a random number between 1 and 1000. It will then ask the end-user whether they believe the next number will be higher or lower. The program will then generate the next number. If the user guessed right (e.g. the next number is higher or lower than the previous one) then the user scores one point. The game stops when the user guesses it wrong.

Learning Objectives


By completing this challenge you are going to use selection (IF statements) and iteration (While loop). You will use comparison operators such as > , < and == to compare numbers. You will use variables to store the value of random numbers, retrieve user input and keep and increment a score as the game progresses.

Complete the Python Code


Molecular Mass Calculator

molecule

Learning Objectives


In this challenge you will improve your string manipulation techniques as well as use Python to perform some basic mathematical calculations.

Did you know?


The molecular weight (mass) may be calculated from the molecular formula of the substance; it is the sum of the atomic weights of the atoms making up the molecule. The molecular mass is expressed in atomic mass unit (amu).

For example, water has the molecular formula H2O, indicating that there are two atoms of hydrogen and one atom of oxygen in a molecule of water.

Atom Atomic Mass Quantity Total Mass
H 1.008 2 2.016
O 15.999 1 15.999
H20 18.015

In the following script we use a Python dictionary called atomicMass to store the atomic mass of some of the main atoms (C, H, O…)

We then work out the molecular mass of water: H20.

Your Challenge


Adapt this script to get the program ask the end-user to enter a molecular formula of their choice.
Using string manipulation techniques your Python script will break down the formula entered by the end-user and calculate the total mass of the molecule.

Test your script with the following molecules:

Molecule Formula
Water H2O
Carbon Dioxide CO2
Methane CH4
Butane C4H10
Carbonic Acid H2CO3
Acetone CH3COCH3
Lactose C12H22O11

Challenge #2


Add more atoms to the atomMass dictionary as follows:

Atom Atomic Mass
Fe 53.939
Ag 106.905
Cu 62.929
Na 22.989
Cl 34.968

Adapt your script so that it recognises when these atoms are used by the end-user when entering their molecular formula. This will be based on the use of uppercase & lowercase letters.

Test your script with the following molecules:

Molecule Formula
Sodium Chloride NaCl
Iron Oxide Fe2O3
Copper Chloride Hydroxide HOCuCl
unlock-access

Solution...

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

My Conversion Library

conversion

Learning Objectives


In this challenge you will learn how to create your own library and how to use it in your programs.

A library is a collection of functions and procedures. A library can then be reused in all your programs using the import instruction.

You have most likely used some libraries in the past, for instance the random library or the maths library.

We are going to create our own library focusing on conversion formulas. It will be useful when we need to convert for example distances from one unit to another (e.g. miles to km, cm to inches).

We have started the library for you by defining two functions: kmToMiles() and milesToKm().

Your Challenge


Complete the library to add the following conversion functions (Roll-over the frames below to reveal the conversion formula):

conversion-distanceConverting Distances

conversion-miles-to-km-1
conversion-inches-to-cm-1
conversion-temperatureConverting Temperatures

conversion-celsius-to-fahrenheit-1
conversion-weightConverting Weights

conversion-kg-to-lb-1
conversion-timeTime Conversion

conversion-seconds-1
unlock-access

Solution...

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

Lightning Distance Calculator

lightning-pictureHave you ever seen a lightning flash or heard the thunder of lightning and wondered how close you were from the ligthning strike? Have you noticed that there is always a delay between the flash of light and the clap of thunder when a lightning occurs?

It is possible to calculate the distance to a ligthning strike by counting the seconds between the lightning flash and the sound of thunder.

When lightning strikes, the first thing you see is the flash of light which you can see instantly. This is because light travels at a very high speed (Speed of light = 300,000 km/s). At the same time a clap of thunder is created. However, in the air a sound wave does not travel as fast as light, so it may take a few seconds for this clap of thunder to reach you. This depends on how far you are from the lightning.

Look at the following diagram and check the formula of speed. Bear in mind that the speed of a sound wave in the air is 340 m/s.
lightning-distance
speed-distance-formula

Your Challenge


Write a Python program that asks the end-user to enter a number of seconds. The program should output the distance (in meters or kilometres) from the lightning strike.

Note that 1 mile = 1.609 km, you may want to convert this distance in miles.

unlock-access

Solution...

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