More results...

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

Space Mission

Rosetta: Rendez-vous with a comet


Rosetta is a robotic space probe built and launched by the European Space Agency. Along with Philae, its lander module, Rosetta is performing a detailed study of comet 67P/Churyumov–Gerasimenko.
Rosetta_spacecraft
Rosetta
Philae_lander
Philae
Comet_67P
Comet 67P

Rosetta: © (CC) ESA/ATG medialab – https://www.flickr.com/photos/europeanspaceagency/11206647984/
Philae: © (CC) ESA/ATG medialab – https://www.flickr.com/photos/europeanspaceagency/10796307373/
Comet 67P: © (CC) SA/Rosetta/NAVCAM – http://blogs.esa.int/rosetta/2014/09/19/cometwatch-19-september/

Your Challenge


At the time this blog post was created, the European Space Agency just received new photographs of comet 67P taken by Rosetta. The spaceship was 500 million km away from Earth.

Write a Python script to answer the following question:

Considering that electro-magnetic signals used to communicate with Rosetta travel at the speed of light (300,000 km/s), how long did these pictures take to travel from Rosetta to planet Earth?

To help you solve this problem you may need to investigate the following formulas:
speed-formula
You will need to make sure your script gives the answer using in the correct format: hh:mm:ss.

Challenge #2: Time travelling?


Did you know that when you look at the stars in the night sky you are time travelling. You are in fact looking at what the stars did look like years and years ago! This is because the stars are extremely far away from planet Earth, and the light they create takes several years to reach us.

When astronomers measure the distance of stars (from planet Earth) they do not use the kilometer (km) unit but instead they use the light-year unit. One light-year represents the distance that light travels in one year, at the speed of light (300,000 km/s).

Your challenge consists of writing a Python script to calculate the distance in km of one light-year.

Then you will use your script to calculate the distance in km for the following stars:

Star Distance from Earth (in light-years)
Alpha Centauri 4.24 light-years
Barnard’s Star 5.96 light-years
Luhman 16 6.59 light-years
WISE 0855-0714 7.2 light-years
Wolf 359 7.78 light-years

Source:
http://en.wikipedia.org/wiki/List_of_nearest_stars_and_brown_dwarfs

Discount Price Calculator

discountShopping during the sales can sometimes be very confusing. With discounted prices at 10%, 20%, 50% or even 70%!

For this challenge you are going to write a Python script that prompts the user to enter a price in pounds (or in your own currency) (e.g. £90) and a discount rate to apply (e.g. 20%).

Your program will then calculate and display the discounted price.

Video Tutorial


Python Code


Complete the code provided below:

Testing


Once your code is done, complete the following tests to check that your code is working as expected:

Test # Input Values Expected Output Actual Output
#1 Price: £100
Discount Rate: 25%
Discount: £25
Discounted Price: £75
#2 Price: £160
Discount Rate: 40%
Discount: £64
Discounted Price: £96
#3 Price: £180
Discount Rate: 10%
Discount: £18
Discounted Price: £162
unlock-access

Solution...

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

Fahrenheit to Celsius Converter

Fahrenheit-CelsiusDegree Fahrenheit (°F) and Degree Celsius (°C) are the main two units to measure temperature.

The Fahrenheit scale is used mainly in the USA whereas other countries tend to use the Celsius scale.

It is possible to convert a temperature from Celsius degrees to Fahrenheit and vice-versa using the following conversion formulas:
fahrenheit_to_celsius_formulas

Your Challenge


Write a Python script to:

  • Ask the end-user whether they want to convert from Fahrenheit to Celsius or from Celsius to Fahrenheit,
  • Ask the user to enter a temperature in the correct unit,
  • Apply the conversion formula and display the temperature in the new unit.

Testing


You can now use your code to complete the following test plan to test your code:

Celsius degrees to Fahrenheit conversions:

Test # Input Values (°C) Expected Output (°F) Actual Output
#1 20 68
#2 -10 14
#3 0 32

Fahrenheit to Celsius degrees conversions:

Test # Input Values (°F) Expected Output (°C) Actual Output
#1 68 20
#2 14 -10
#3 32 0

Challenge #2


On the temperature scale, the 0°C (=32°F is called Freezing Point which is when water starts freezing and becomes ice. At 100°C (=212°F) water starts to boil. This is called Boiling Point.

Adapt your script to write a message to the end user as follows:

  • You are above boiling point for all temperatures above 100°C
  • You have reached boiling point if the temperature is exactly 100°C
  • You are between freezing point and boiling point for all temperatures between 0°C and 100°C
  • You have reached freezing point if the temperature is exactly 0°C
  • You are below freezing point for all temperatures below 0°C
unlock-access

Solution...

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

The legend of the chessboard

chessboardThe story tells us that long long ago the great Sultan of India loved to play games. As he started to get bored of the games that were present at the time he asked a wise man who lived in his kingdom to come up with a new game.

This, according to the legend, is how the game of chess was invented. The Sultan was very pleased with the wise man who had invented the game and in return he offered the wise man a reward of his own choosing.

riceTo the Sultan’s surprise, the wise man did not ask for any gold. Instead he only had one request: He asked just for a few grains of rice in the following manner: the sultan was to put a single grain of rice on the first chess square, two grains on the second square, four on the third square and carry on doubling this number on every consequent square to fill up all 64 squares of the chessboard.

This seemed to the ruler to be a modest request, so he called for his servants to bring the rice. Did the Sultan manage to fulfil the wise man’s request?

Python Code


Your task consists of writing a python script to calculate the total number of grains of rice required to cover the chessboard following’s the wise man’s request.

unlock-access

Solution...

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

Fraction Simplifier

This challenge consists of writing a program that asks the end-user to enter a fraction (numerator and denominator) and output the matching reduced fraction when the fraction can be reduced.

To see what this program should do in action you may want to try fractionsimplifier.com.

fraction_numerator_denominator

To simplify a fraction your program will need to find the greatest common divisor (aka greatest common factor) of the numerator and denominator that will have been entered by the end user. Then, your program will divide the numerator and denominator of the fraction by this number.

fraction

To find out if a number is a factor of the numerator you will need to check that the remainder of the numerator divided by this number is null (=0):

  • For instance 3 is a factor of 24 because 24 mod 3 = 0.
  • remainder_24

  • Whereas 5 is NOT a factor of 32 because 32 mod 5 = 2 != 0.
  • remainder32

Extra tip: A factor of a number is always lower or equal to this number.

Your Challenge:


Complete the code below to find the greatest common factor of both the numerator and denominator entered by the end-user and use it to output the simplified fraction.

unlock-access

Solution...

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

Area Calculator

For this challenge we are going to use a Python script to calculate the area in square meters of two different flats.

To do so we will write a computer program that will add up all the areas of each room.

Most rooms have a rectangle shape. So we will first define a function that takes two parameters: width and length and return the area of the rectangle using the following formula:

area = width * length

Let’s use this formula to calculate the area of this small flat:Flat_0

Your Challenge


Tweak the code above to calculate the area of the following two flats: (Click on each picture to zoom in).
Flat_1

Flat_2

Challenge #2


The area of a right-angled triangle can be calculated as follows:
triangle
area = width * length / 2

Add a new function called getTriangleArea to return the area of a right-angled triangle using two parameters: width and length.

Use both the getRectangleArea and getTriangleArea functions to calculate the area of this room:
flat_4

Challenge #3:


Use your code to calculate the area of this small mansion (Click on picture to zoom in):
flat_5

unlock-access

Solution...

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

3D Challenge

3DCubeThe aim of this challenge is to draw a cube in 3D and to make it rotate on the screen.

Drawing 3D shapes on a screen (2D) requires some mathematical formulas to convert 3D (x,y,z) coordinates into 2D coordinates (x,y). This conversion, also known as “oblique projection” is based on the following formulas:
oblique-projection-formulae

This is a great application of trigonometry, especially of the SOCATOA formulas!

socatoa

cosine

sine

(Read more about trigonometric formulas.)

A 3D rotation against an axis (X, Y or Z axis) also requires some complex mathematical formulas. To apply a 3D rotation we can use the rotation matrix as follows:
3d-rotation-matrix

Our Solution:


To decide the angle and axis of rotation we use the position of the mouse pointer.
The X coordinate of the mouse pointer becomes the angle of rotation against the Y axis.
The Y coordinate of the mouse pointer becomes the angle of rotation against the X axis.
In this example we did not implement a rotation against the Z axis.

Your Task


3d-houseAdd more edges to the code given above to create a full house including a roof, a front door and a window.
unlock-access

Solution...

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

Mastermind Challenge

mastermind
Have you ever played the board game “Mastermind”?

If you are not too sure about the rules of this game, you should first check this page.

For this challenge we are going to create this game of mastermind where the end-user plays against the computer. The end-user’s role is to guess the choices of 4 colours made by the computer.

Learning Objectives


By completing this game we are using all our coding skills using nested loops and IF statements.

We are also learning about how flowcharts can be used to describe a complex algorithm.

Flowchart


Can you create the flowchart for this computer game yourself?
Give it a try. Once done, compare your flowchart with our flowchart:
Mastermind-Thumbnail
Note that there is often more than one approach to solve a problem.

Code


Use either your flowchart or the one given above and translate it into programming code using Python.

unlock-access

Solution...

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

Python: Reading a text file

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.

Challenge

Your first challenge consists of writing a Python script that will read the following text file, one line at a time and display the content of each line on screen.


TextFile
My Playlist.txt

To read the content of a text file line by line we are going to use a for loop that will loop through and extract each line of the text file one at a time. It will stop looping only once the it will have reached the last line.

Check this animation that explains this process:
Reading-Text-File-Animation-s

When the text file uses a CSV format (Comma Separtred Values), each line contains several values separated using a special character, often a comma or a semi-colon. In this case we can use the split() method to extract each value of each line and store them in a list.

Check this animation that explains this process further:
Reading-CSV-File-Animation-s

Solution

The solutions below contains 5 main steps:

  1. Step 1: Open the text file using the open() function. This function takes two parameters: The name of the file (e.g. “playlist.txt”) and the access mode. In our case we are opening the file in read-only mode: “r”.
  2. Read through the file one line at a time using a for loop.
  3. Split the line into an array. This is because in this file each value is separated with a semi-column. By splitting the line we can then easily access each value (field) individually.
  4. Output the content of each field using the print method.
  5. Once the for loop is completed, close the file using the close() method.

 

Main Access Modes when opening a file with the open() function.

Mode Description
r Opens a file in read only mode. This is the default mode.
r+ Opens a file for both reading and writing.
w Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist yet, it will create the new file for writing.
w+ Opens a file for both writing and reading. Overwrites the file if the file exists. If the file does not exist yet, it will create the new file for writing.
a Opens a file for appending. The file pointer is at the end of the file. So new data will be added at the end of the file. If the file does not exist, it creates a new file for writing.
a+ Opens a file for both appending and reading. The file pointer is at the end of the file. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.

Your Challenge


Use what you have learnt in this blogbpost to complete these challenges:
My mp3 playlist(Reading a text file using Python) US Population(Reading a text file using Python)

Python Tip: Validating user input as number (Integer)

In most of your Python programs you will want to interact with the end-user by asking questions and retrieving user inputs.

To do so you can use the input() function: e.g.

username=input("What is your username?")

Sometimes you will need to retrieve numbers. Whole numbers (numbers with no decimal place) are called integers. To use them as integers you will need to convert the user input into an integer using the int() function. e.g.

age=int(input("What is your age?"))

This line of code would work fine as long as the user enters an integer. If, by mistake, they enter letters or punctuation signs, the conversion into an integer will fail and generate an exception (error) and the program would stop running.

To validate the user entry and ensure that is a number it is possible to catch this exception when it occurs using the try…except….else block as follows:

try:
    value=int(input("Type a number:"))
except ValueError:
    print("This is not a whole number.")

See how we can use this approach to define our own function (called inputNumber()) to ask for a number. This new function can then be used instead of an input() function whenever we expect the user to enter a whole number. This function uses the try…except….else block within a while loop so that it keeps asking the user to enter a number till the user gets it right.

Final Code:

def inputNumber(message):
  while True:
    try:
       userInput = int(input(message))       
    except ValueError:
       print("Not an integer! Try again.")
       continue
    else:
       return userInput 
       break 
     

#MAIN PROGRAM STARTS HERE:
age = inputNumber("How old are you?")