More results...

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

Timelapse Video Recording Using a Rapberry Pi

RaspberryPi

Getting Ready…

For this challenge you will need:

  • A Raspberry Pi with Python 2 installed,
  • A PiCamera.

Follow the steps described on the following pages to make sure you have plugged the camera in your raspberry pi and that you have enabled it. Also make sure you have installed the picamera library.

Getting Started


timelapse

First we need to write a Python script to take and store a picture every “x” seconds. We will do this using an infinite loop.

To make sure we can exit the loop we will catch a keyboard interrupt (when the user presses CTRL + “C”. This will terminate the program.

The main variable used in this script is the timeInterval variable. Per default we set it to 5 seconds. You may want to change this depending on what you are recording and how long you intend to record it for.

import picamera, time
#Initailise the camera
camera=picamera.PiCamera()

#This will be used to name the pictures once stored.
filename = "frame_"
timeInterval = 5 # The time interval between two pictures, in seconds

#We have left all the settings in case you need to make some adjustments to improve the picture quality
camera.hflip = True
camera.vflip = True
#camera.sharpness = 0
#camera.contrast = 0
#camera.brightness = 50
#camera.saturation = 0
#camera.ISO = 0
#camera.video_stabilization = False
#camera.exposure_compensation = 0
#camera.exposure_mode = 'auto'
#camera.meter_mode = 'average'
#camera.awb_mode = 'auto'
#camera.image_effect = 'none'
#camera.color_effects = None
#camera.rotation = 0
#camera.crop = (0.0, 0.0, 1.0, 1.0)

i=1
try:
    while True: #Infinite Loop
        camera.capture(filename + str(i) + '.jpg')
        print(filename + str(i) + '.jpg')
        time.sleep(timeInterval)
        i+=1
except KeyboardInterrupt: #Press Ctrl+C to interrupt
    pass

print('All done...')

Final Step


Now that we have all the pictures stored. We need to combine them into a video clip (.avi).

To do so we will use the following script, from Claude Pageau: Source: https://github.com/pageauc/pi-motion-orig

print "initializing ...." 
import StringIO 
import subprocess 
import os 
import time 
import csv 
from datetime import datetime 
import cgi, cgitb 

imageWidth = 1296 
imageHeight = 972 
# Aspect ratio of video eg 4/3 16/9 Etc. 
# Note put value in quotes. 
aspectRatio = "4/3" 
# Video fps (frames per second) vulue usually  between 2 to 30.  I recommend 5 fps to start 
framesPerSec = 5 
# Video output filename. 
# Can also include folder path, othewise file saved to current folder.  
movieName = "./makemovie.avi" 
 
print "makemovie.py" 
print "============" 
print "Creating makemovie.txt file of *jpg files in google_drive folder."  
ls_params = " -t -r ./*jpg > makemovie.txt" 
exit_status = subprocess.call("ls %s " % ls_params, shell=True) 

print "Creating movie file %s using makemovie.txt" % ( movieName ) 
print "Settings = Image W=%s H=%s aspect=%s fps=%s filename=%s" % ( imageWidth, imageHeight, aspectRatio, framesPerSec, movieName ) 

mencoder_params = "-nosound -ovc lavc -lavcopts vcodec=mpeg4:aspect=%s:vbitrate=8000000 -vf scale=%s:%s -o %s -mf type=jpeg:fps=%s  mf://@makemovie.txt" % ( aspectRatio, imageWidth, imageHeight, movieName, framesPerSec ) 
print "memcoder_params = %s" % ( mencoder_params ) 
print "Creating Movie. This will take a while ......." 
print "----------------------------------------------" 

exit_status = subprocess.call("mencoder %s" % mencoder_params, shell=True) 
print "makemovie.py" 
print "============" 
print "Finished timelapse movie filename= %s" % ( movieName ) 
Tagged with: ,

Daily Calorie Intake

apple

Did You Know?

Keeping a healthy lifestyle consists of adapting our daily food intake with our level of physical activities. The calories we intake (by eating food) has to roughly match the calories we burn throughout the day.

Your Challenge


For this challenge you are going to write a Python program that asks the user for their gender (Male of Female), their lifestyle (Sedentary, Moderately Active, Active) and their age.
The program will then tell them what their daily calorie intake should be.

The program should make use of the following table of data:


GenderAge (years)SedentaryModerately ActiveActive
Female2 to 3100012001400
4 to 8120014001800
9 to 13160019002200
14 to 18180021002400
19 to 30200022002400
31 to 50180020002200
51+160019002200
Male2 to 3100012001400
4 to 8140017002000
9 to 13180022002600
14 to 18220027003200
19 to 30240027003000
31 to 50220026003000
51+200024002800

Learning Objectives


By Completing this learning challenge you will use:

  • Nested If Statements,
  • Comparison Operators such as ==, !=, <, <=, >, >=,
  • Boolean Operators: AND or OR.

Tip:


Complete this task progressively using the following 3 steps:

Step 1:

    Start by asking the end-user for their gender.
    If their gender is Male display your calorie intake is around 2400 calories for a man, or 2000 for a woman. If you need a reminder on how to use the input, if and print instructions in python check this page.

Step 2:

    Add an input at the beginning to ask the user for their age (in years). Convert this input to an integer using the int() function. Use nested if to display the right daily calorie intake based on both the gender and the age. (Use the data from the first column, “sedentary” at this stage.)

    Remember when using nested if statements to indent your code accordingly.

Step 3:

    You can now use a third question to ask the user if they are “S” – Sedentary, “M” – Moderately Active, “A” Active.
    Use a third level of indentation/nesting to complete this challenge using all the data from the given table.

Your Code:


Extension Task:


Ask the user how many calories they have eaten so far (this day) and return the number of calories they can still have till the end of the day to match their recommended daily calorie intake.

Review…


Complete this fill in the gaps activity to check whether you can use the right computing terminology.

Tagged with: , ,

Find the monster!

door-140 door-140 door-140

Will you dare open one of the three doors above. (Click on a door to open or close it.)

Did you come across any monster? If not carry on opening doors till you find a monster!

Your Challenge

Check the Python code below. This code lets the user open one of the three doors to see if there is a monster behind the selected door.

Your task consists of tweaking this code further to enable the user to carry on opening doors till they find the monster. To do so you will need to use a while loop.

The program should count how many doors the user did open and stop once the user meets the monster.


unlock-access

Solution...

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

Tagged with: , ,

Revise: If Statements


Complete this drag and drop activity to use the right computing terminology about If Statements, boolean operators and comparison operators.

equal to
False
comparison
elif
OR
!=
boolean
<=

  • == and != are operators,
  • == means “is ?”,
  • means “is not equal to?”, aka “is different from?”
  • Other comparison operators can be used in selection statements such as >, <, , >=,
  • AND and are operators,
  • The result of a comparison is a boolean, which means it is either True or ,
  • In Python we can use the following three instructions: if, and else.

Tagged with: ,

NATO Phonetic Alphabet

Did You Know?


The NATO Phonetic Alphabet is the most widely used spelling alphabet. A spelling alphabet (aka radio alphabet, or telephone alphabet) is a set of words used to stand for the letters of an alphabet in oral communication. Each word in the spelling alphabet typically replaces the name of the letter with which it starts. It is used to spell out words when speaking to someone not able to see the speaker, or when the audio channel is not clear.

Nowadays people may use the NATO Phonetic alphabet when they have to spell their name or their postcode over the phone.

For instance, the name Smith would spell Sierra – Mike – India – Tango – Hotel.

Challenge


This challenge consists of writing a computer program that will ask the end-user to enter their lastname. The program will output their lastname using the NATO Phonetic Alphabet.

To complete this challenge you may want to investigate the use of a dictionary in Python.

Learning Objectives


By completing this challenge we are going to learn about Python dictionaries.
In Python, a dictionary consists of pairs (called items) of keys and their corresponding values.

Python dictionaries are also known as associative arrays or hash tables. The general syntax of a dictionary is as follows:
PythonDictionary

myDictionary = {"Red": "#FF0000", "Green": "#00FF00", "Blue": "#0000FF"}
print("The colour code for Green is:")
print(myDictionary["Green"])

btnTryCodeOnline

NATO Phonetic Alphabet

Letter Code
A Alfa
B Bravo
C Charlie
D Delta
E Echo
F Foxtrot
G Golf
H Hotel
I India
J Juliett
K Kilo
L Lima
M Mike
N November
O Oscar
P Papa
Q Quebec
R Romeo
S Sierra
T Tango
U Uniform
V Victor
W Whiskey
X X-ray
Y Yankee
Z Zulu
Dash

Let’s get coding…

Extension


You can use the same approach to create a Morse Code Encoder!

Morse-Code-NATO

unlock-access

Solution...

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

Google Translate

english-frenchHave you ever used Google Translate to translate some text or a full webpage?

For this challenge we are going to try to write a Python script to translate from English to French. However we are only going to translate numbers as follows:

Number English French
7 Seven Sept
24 Twenty-four Vingt-quatre
365 Three hundred and sixty-five Trois cent soixante-cinq
25,642 Twenty-five thousand six hundred and forty-two Vingt-cing mille six cent quarante-deux


From the examples given above we can see that the same rules are used in both English and French to write numbers in full. This means that we can write a simple algorithm here to translate word for word each of the words used from English to French. Note that even though this approach will be quite accurate to translate numbers written in full, it would be very inaccurate to translate full sentences. This is because the English grammar and the French grammar are different and though both languages have a lot of similarities they do not follow exactly the same rules. (Grammar and conjugation)

grammar-conjugation

For our translation algorithm we will focus on a word for word translation. To do so we need an English/French dictionary. We will use a text file containing all the words we need: One, Two, Three… Ten, Eleven, Twelve, … Thirty, Forty, Fifty, … Hundred, Thousand.


TextFiledictionary.txt

Finally we can write our algorithm which will:

  1. Ask the user to enter a number in full English,
  2. Open the dictionary.txt file in read mode,
  3. Loop through each line of the text file
    • Split and extract the data (English and French word)
    • Replace the English word with the French word in the number
  4. Close the text file
  5. Display the translated number on screen

Un, Deux, Trois…


Let’s test this code. You can use the numbers given in the table above to test this code:

Your Task:


Complete this code for the program to:

  1. Ask the user if they want to translate from English to French (Option 1) or from French to English (Option 2),
  2. Allow for the French to English translation using a similar approach as the one used to translate from English to French, using the same dictionary.txt file, without having to change it.
unlock-access

Solution...

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

Formula 1 Grand Prix

For this challenge we are going to use pseudo-code to analyse the timings of the best two formula 1 drivers of the season, Lewis Hamilton and Sebastian Vettel on four different Grand Prix.

For the purpose of this task we will assume that the drivers are competing against each other on four Grand Prix, each race consisting of ten laps only.

The timings of both drivers will be recorded using pseudo-code. Your task will be to analyse the pseudo-code for each of the four grand prix to decide who of the two drivers won each race!

F1-Melbourne

Race #1: Australian Grand Prix – Melbourne

Here are the timings of the race:

Race Timings

hamiltonTime = 0
vettelTime = 0

for lap in range(1,10):

    hamiltonTime += 100
    vettelTime += 102

    if lap==8:
        hamiltonTime += 18
Running Commentary
Both drivers are on the starting line, ready to push on the accelerator.

Lewis Hamilton has a better start and on average completes each lap in 100 seconds (1 minute and 40 seconds) where Sebastian Vettel completes each laps in 102 seconds (1:42).

We are now on lap 8 and it seems that Lewis Hamilton is going to win this race.

Oh no, Lewis Hamilton is having a technical issue with his car and now needs to stop in the pits to get his car fixed. He has lost 18 seconds! Will he still be able to win the race at the end of lap 10?

Analyse the race above. Can you find out who won this first Grand Prix? Type the name of the winner below:

F1-Silverstone

Race #2: British Grand Prix – Silverstone

Here are the timings of the race:

Race Timings

hamiltonTime = 0
vettelTime = 0

for lap in range(1,10):
    if lap <= 4
       hamiltonTime += 100
       vettelTime += 102
    else:
       hamiltonTime += 103
       vettelTime += 102

    if lap==9:
        hamiltonTime += 18
        vettelTime += 15
Running Commentary
Once again Lewis Hamilton has a better start than Sebastian Vettel and is completing the first 4 laps with an average of 100 seconds (1 minute and 40 seconds) per lap where Sebastian Vettel completes each lap in 102 seconds (1:42).

From lap 5 onwards, however Lewis Hamilton seems to be slowing down a bit and is now completing each lap in 103 seconds while Sebastian Vettel remains at the same speed, completing each lap in 102s. He is progressively reducing the gap and catching with Lewis Hamilton.

We are now on lap 9 and both drivers decide to have a pitstop losing respectively 18 seconds and 15 seconds. Will this 3-second difference have an impact on the final outcome of this race?

Analyse the race above. Can you find out who won this second Grand Prix? Type the name of the winner below:

F1-Monaco

Race #3: French Grand Prix – Monaco

Here are the timings of the race:

Race Timings

hamiltonTime = 0
vettelTime = 0

for lap in range(1,10):

    hamiltonTime += 103
    vettelTime += 101

    if lap==5:
        hamiltonTime +=14
    if lap==4 or lap==7:
        vettelTime += 12
Running Commentary
What a fantastic race from Sebastian Vettel who is taking risks and completing each lap in on average 101 seconds (1:41) whereas Lewis Hamilton is 2 seconds slower on every lap.

During this race, Lewis Hamilton will only stop once in the pits, on lap 5 losing 14 seconds whereas Sebastian Vettel will make two stops losing 12 seconds each time.

This is a very risky strategy. Which of the two drivers will have made the right decision?

Analyse the race above. Can you find out who won this third Grand Prix? Type the name of the winner below:

F1-Monza

Race #4: Italian Grand Prix – Monza

Here are the timings of the race:

Race Timings

hamiltonTime = 0
vettelTime = 0

for lap in range(1,10):

    if lap <= 3
       hamiltonTime += 101
       vettelTime += 101
    elif lap>3 and lap<=8:
       hamiltonTime += 103
       vettelTime += 102
    else:
       hamiltonTime += 100
       vettelTime += 101
Running Commentary
What an exciting start to this race. For 3 full laps both drivers are ex aequo, driving their formula 1 car at exactly the same speed, completing each lap on 101 seconds.

From lap 3, Sebastian Vettel is taking the lead, completing laps in 102 seconds, 1 second quicker than his main opponent, Lewis Hamilton.

Towards the end of the course however Lewis Hamilton is accelerating progressively closing the gap with Sebastian Vettel. Will he have time to catch up with him and overtake him before the finishing line?

Analyse the race above. Can you find out who won this forth Grand Prix? Type the name of the winner below:

Tagged with: , ,

Guess Who

Did You Know?


The aim of the “Guess Who” game is to look at a list of character cards and to ask “Yes/No” questions to progressively eliminate cards from the set by flipping them down. At the end of the game there should only be one card still standing up. The aim is to find this card by eliminating all the others.

Learning Objectives


By Completing this challenge you will understand more about the use of boolean logic when using selection statements (if statements).

Before completing this challenge, remember that:

  • == and != are comparison operators,
  • == means “is equal to?”,
  • != means “is not equal to?”, aka “is different from?”
  • Other comparison operators can be used in selection statements such as >, <, <=, >=, but we will not use these in this challenge,
  • AND and OR are boolean operators,
  • The result of a comparison is a boolean, which means it’s either True or False.

Now let’s look at our set of seven “Guess Who” cards: Click on a card to flip it.

Click to flip!Click to flip!Click to flip!Click to flip!
Click to flip!Click to flip!Click to flip!

Round #1:


Look at the pseudo-code below to find out who is on the remaining card:

if gender == "Male" AND wearsGlasses == True:
	flipCardDown()
if hairColor == "Black" OR hairColor == "Blonde":
	flipCardDown()
if gender == "Female" AND wearsHat != True:
	flipCardDown()

print("All cards have now been flipped down but one. Who is on the remaining card?")

Not sure? Check the solution by clicking on the card below:
Click to flip!

Click to flip!Click to flip!Click to flip!Click to flip!
Click to flip!Click to flip!Click to flip!

Round #2:


Look at the pseudo-code below to find out who is on the remaining card:

if hasBeard == True OR wearsHelmet == True:
	flipCardDown()
if wearsEarings == True AND wearsNecklace == True:
	flipCardDown()
if hairColor == "Brown" OR gender == "Male":
	flipCardDown()

print("All cards have now been flipped down but one. Who is on the remaining card?")

Not sure? Check the solution by clicking on the card below:

GuessWho8

Click to flip!Click to flip!Click to flip!Click to flip!
Click to flip!Click to flip!Click to flip!

Round #3:


Look at the pseudo-code below to find out who is on the remaining card:

if hairColor == "Blonde" OR hairColor == "Brown":
	flipCardDown()
if wearsGlasses == True OR wearsHat == True:
	flipCardDown()

print("All cards have now been flipped down but one. Who is on the remaining card?")

Not sure? Check the solution by clicking on the card below:

GuessWho8

Click to flip!Click to flip!Click to flip!Click to flip!
Click to flip!Click to flip!Click to flip!

Round #4:


Look at the pseudo-code below to find out who is on the remaining card:

if eyeColor != "Blue" AND gender == "Female":
	flipCardDown()
if wearsHat == True OR wearsHelmet == True:
	flipCardDown()
if wearsGlasses == True:
	flipCardDown()
if wearsTie == True :
	flipCardDown()

print("All cards have now been flipped down but one. Who is on the remaining card?")

Not sure? Check the solution by clicking on the card below:

GuessWho8

Click to flip!Click to flip!Click to flip!Click to flip!
Click to flip!Click to flip!Click to flip!

Round #5: Your Turn!

Select one of the character and create your own pseudo-code. Ask one of your classmate to guess which card you picked by analysing your pseudo-code.

Type your pseudo-code in the textbox below:

Tagged with: ,

Live Metrics

First let’s have a look at the following two webpages…

Our Challenge


In this challenge we are going to write our own Python scripts to generate live metrics.

Let’s look at our first fact:

Every second, on average 10,260 tweets are tweeted on Twitter.

And check the Python script to make transform this fact into a “live metrics program”.

Task #1:


Update the code above to create “live metrics” from the following facts:

On average 1,200 photos are posted on Instagram every second.
On average 98,000 youtube videos are viewed every second.
Google now processes over 107,000 search queries every second on average.

Task #2:

Around 80 million cars are produced in a single year worldwide.

To create a live metrics program based on this fact you will first need to use Python to calculate the number of cars produced in one second.

Task #3:

The current world population is estimated at: 7,985,000,000 human beings.
It is currently growing at a rate of around 1.05 % per year.

To create a live metrics program based on this fact you will first need to use Python to calculate the population growth (in human beings) in one second.

unlock-access

Solution...

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

How eco-friendly are you?

ecoFriendlyIt would not be hot news for you to hear that throughout your everyday life, whatever you do, you are having an impact on the environment. Words like pollution, global warming, carbon dioxide, recycling, energy saving, waste reduction are no mystery to you.

For this challenge you are going to design a quiz that people can take to find out how green or eco-friendly they are. The quiz will consist of eight questions and will be used to give the end-user a score.

Here are the eight questions for the quiz.


  1. How do you come to school?
    • By Car (-50pts)
    • By Bus (-10pts)
    • On Foot (+100pts)
    • Cycling (+100pts)
       
  2. Did you travel by plane in the last 12 months?
    • No (+100pts)
    • Yes once (-25pts)
    • Yes twice (-50pts)
    • At least 3 times (-100pts)
       
  3. Do you use your recycling bins at home?
    • Never (-50pts)
    • Rarely (+10pts)
    • Often (+50pts)
    • Yes every day (+100pts)
       
  4. When you go shopping do you?
    • Bring your own reusable carrier bags (+20pts)
    • Ask for plastic bags (-20pts)
       
  5. At home do you use Energy saving bulbs?
    • Yes (+30pts)
    • No (-30pts)
       
  6. When you clean your teeth, do you let the water run?
    • Yes (-30pts)
    • Sometimes (-10pts)
    • No, never (+20pts)
       
  7. Is your house equipped with solar panels?
    • Yes (+100pts)
    • No (0pt)
       
  8. When it’s getting a bit colder at the end of the summer do you?
    • Put an extra layer on (e.g. jumper, extra blanket) (+50pts)
    • Turn the heater on? (-50pts)
       

At the end of the quiz, the user will be told what is their score and what category they belong to amongst these four categories:

Score Category
Negative score (<0) Amber
Between 0 and 100 Light Green
Between 101 and 200 Emerald Green
Above 200 Deep Green

Let’s get coding


We have started the code for you but only completed the first question. Your task consists of:

  1. Completing the code to ask all seven questions,
  2. Giving the user their final score and the category they belong to (Amber, Light Green, Emerald Green or Deep Green) based on their final score.

unlock-access

Solution...

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