More results...

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

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:

My Library

For this challenge you will work for the librarian who needs a computer program to help pupils find out where books can be found in the library.

MyLibrary

The library contains nine bookshleves labelled from A to I. Each bookshelf specialises in one genre. For instance, bookshelf A is for comedy fiction books.

Below is the list of bookshelves and genres:
MyLibrary-bookshelves

Your Task:


Your task is to write a computer program that asks the user if they are looking for a fiction or a non-fiction book. Based on the user answer the program will ask the user to choose the genre from a list of available genres. Finally the program will return the location (A to I) of books of this genre.

Learning Objectives


By completing this challenge you will use selection statements (if, elif and else). You will also use nested constructs by having if statements within if statements.

When using if statements you have to indent your code as follows:
code-indentation

Let’s get coding


We have started the code for you but this code is incomplete: Can you complete the code to cater for all nine genres?

Extension Task:


The Science and Technology section of the library is growing. The librarian decides to have five sub-sections for this section as follows:

    H1: Biology Books
    H2: Physics Books
    H3: Chemistry Books
    H4: Computer Science Books
    H5: Design & Technology Books

Extend your code further to include these five subcategories in your algorithm. (See below for a full list of all the required genres.)

MyLibrary-bookshelves-2

To do so you will need to indent your code further as follows. This is called nested indentation:
code-nested-indentation

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 Secret Key

Richard_II_of_EnglandThe legend of the secret key is based around King Richard II, King of England. In 1399, Richard II decided to hide his treasure in a treasure chest and used four keys to lock his treasure chest.

He asked his finest locksmith to design four unique keys. He then locked his treasure chest and threw away the four keys in a fire and watched them melt down.

For more than 600 years the treasure chest has been kept in a secret location and has not yet been opened. Nobody has ever been able to create the four keys to open the treasure chest.

Recently, historians from Cambridge University found a piece of parchment and a letter signed by Richard II’s locksmith. In this letter he explains that when they were made, each key was given a unique code and that these codes were all what was needed to recreate the keys.

On the parchment, historians found a rough drawing of each key and the code for three of the keys. The code for the fourth key is no longer readable.

Looking at the codes of the first three keys, will you be able to find out the code for the fourth key?

four-keys

If you find the code, test it in the trinket below to see if it gives you the right key:

Tagged with:

Number based brainteasers

In this collection of challenges you are going to manipulate numbers and perform basic arithmetic operations with numbers as well as use string manipulation techniques to format numbers.

Challenge #1: Square Number


ChallengeSolutionLearning Outcome?
Write a program that prompts the user to enter a number and returns (displays on screen) the square of this number (e.g. by multiplying this number by itself or by raising this number to the power of 2).

number = int(input("Type a number:"))
squareNumber = number * number
print("The Square Number is " + str(squareNumber)) 
Notice the need to be able to convert a user input from a string to an integer using the int() function on line 1.

Converting a user input to an integer is required to do some maths based calculations such as the calculation used on line 2.

Vice versa, we can convert an integer to a string using the str() function on line 3.

Challenge #2: Total 100


ChallengeSolutionLearning Outcome?
Write a program that prompts the user to enter a number between 0 and 100. The program should return the number that needs to be added to reach 100. For instance if the user enters 36, the program should return 64 because 36 + 64 = 100.

number = int(input("Type a number:"))
total100 = 100 - number
print("The Total 100 Number is " + str(total100)) 
Once again notice the use of the int() function on line 1 to convert a user input to an integer and the str() function on line 3 to convert an integer to a string.

Challenge #3: Odd or Even?


ChallengeSolutionLearning Outcome?
Write a program that prompts the user to enter a number and returns whether this number is an odd number or an even number. (tip: A number is even if the remainder of dividing this number by two is null). So, in Python if number % 2 = 0 then this number is even otherwise it is odd.

number = int(input("Type a number:"))
if (number % 2) == 0:
  print("This number is even.")
else:
  print("This number is odd.") 
In Python the % operator is used to calculate the remainder of a division. This is very useful here to find out if a number can be divided by 2 (even number) or not (odd number).

Challenge #4: Telephone Number


ChallengeSolutionLearning Outcome?
Ask the user to enter their telephone number using 11 digits. Format this number as follows (xxxx) xxx xxx. For instance if the user types 01473123456, the program output should be (01473) 123 456

number = input("Type your telephone number usin 11 digits:")
telephoneNumber = "("  + number[0:5] + ") " + number[5:8] + " " + number[8:11]
print(telephoneNumber)
In Python it is easy to slice a string to extract certain characters. This is done by using the following approach: using the square brackets on a string: e.g. string[startingPosition:endPosition] will retrieve all the characters of the string between the startingPostion and the endPosition.

Notice that in this challenge we are treating the user input as a string not a number. (We did not convert the user input on line 1 to an integer as we did in previous challenges using the int() function.) Each digit of our number/string is in fact a character from the string.

Challenge #5: Palindrome


ChallengeSolutionLearning Outcome?
Ask the user to enter any large number (e.g. at least 3 digits long). The program should return the palindrome of this number. For instance if the user enters 123 the program should return 123321.

number = input("Type a large number:")
palindrome = ""

for digit in number:
  palindrome = digit + palindrome

palindrome = number + palindrome  
print("The palindrome number is " + palindrome)  
In Python it is easy to iterate (loop through) through each character of a string one at a time using a for loop.

Notice that in this challenge, once again we are treating the user input as a string not a number. (We did not convert the user input on line 1 to an integer as we did in previous challenge using the int() function.) Each digit of our number/string is in fact a character from the string.

Challenge #6: Number Upgrade


ChallengeSolutionLearning Outcome?
Ask the user to enter any large number (e.g. at least 3 digits long). The program should return a number where each digit is being incremented by 1 except if the digit is equal to 9 then it becomes 0. For instance if the user enters 2489740 the program should return 3590851.
number = input("Type a large number:")
numberUpgrade = ""

for digit in number:
  if int(digit)==9:
    newDigit = 0
  else:
    newDigit = int(digit) + 1
  numberUpgrade = numberUpgrade + str(newDigit)
  
print("The Number Upgrade is " + numberUpgrade) 
This is the same approach as for challenge number #5 where we iterate (loop through) each character of a string one at a time using a for loop.

We retrieve each digit (character) one at a time and have to convert these digits to integers using the int() on line 5 and 8 to be able to perform maths calculation with them (adding them up).

Challenge #7: Spaced Out Number


ChallengeSolutionLearning Outcome?
Ask the user to enter any large number (e.g. at least 3 digits long). The program should return this same number adding a “-“ between each digit. For instance if the user enters 3658 the program should return 3-6-5-8.

number = input("Type a large number:")
spacedOutNumber=""

for digit in number:
  spacedOutNumber = spacedOutNumber + "-" + str(digit)
  
print("The Spaced Out Number is " + spacedOutNumber[1:])  
Once again we are iterating (looping through) each character of a string one at a time using a for loop.

Notice the slicing approach used to truncate the string from its first digit on line 7 using the string[1:] which returns all the characters from a string from position 1. (So slicing out the first character which is at position 0).

Challenge #8: Total Number


ChallengeSolutionLearning Outcome?
Ask the user to enter any large number (e.g. at least 3 digits long). The program should return the result of adding each digit together. For instance if the user enters 7324 the program should return 7+3+2+4 = 16.

number = input("Type a large number:")
totalNumber = 0

for digit in number:
  totalNumber += int(digit)
  
print("The Total Number is " + str(totalNumber))  
Nothing new here… Once again we are iterating (looping through) each character of a string one at a time using a for loop.

Challenge #9: Plus Minus


ChallengeSolutionLearning Outcome?
Ask the user to enter any large number (e.g. at least 3 digits long). The program should return the result of alternatively adding and subtracting each digit together. For instance if the user enters 7324512 the program should return 7-3+2-4+5-1+2 = 8.

number = input("Type a large number:")
plusMinusNumber = 0
plusminus = 1

for digit in number:
  plusMinusNumber += int(digit) * plusminus
  plusminus = plusminus * (-1)
  
print("The Plus Minus is " + str(plusMinusNumber)) 
Nothing new here… Once again we are iterating (looping through) each character of a string one at a time using a for loop.

Challenge #10: Digit Grouping


ChallengeSolutionLearning Outcome?
When displaying numbers it is good practice to group digits together and use the comma to separate groups of three digits. For instance 100000000 is easier to read when it is displayed as 100,000,000.
Ask the user to enter any large number (e.g. at least 3 digits long). The program should display the result of formatting this number using the comma. For instance if the user enters 65738924 the program should return 65,738,924.

number = input("Type a large number:")
digitGroupingNumber = ""
counter=0

for digit in number[::-1]:
  if counter==3:
     digitGroupingNumber = digit + "," + digitGroupingNumber
     counter=0
  else:   
     digitGroupingNumber = digit + digitGroupingNumber
     counter+=1
  
print("The Digit Grouping Number is " + digitGroupingNumber)
You will notice on this code that we are iterating through each character of a string starting from the last character and going backwards up to the first character. To do so we used a negative step in our for loop using the [::-1] notation on line 5.