More results...

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

The Zoo Keeper’s Puzzles

Learning Objectives:


This set of puzzles will improve your Python skills when using If Statements (Selection)
You will focus on:

  • Using comparison operators: ==, !=, < , >, <=, >=
  • Using Boolean Operators: AND, OR, NOT

if statements use comparison operators to compare values and make a decision based on the comparison.

The main comparison operators are:

Comparison Operator Meaning Example
== is equal to 4==4
!= is different from 4!=7
< is lower than 3<5
> is greater than 9>2
<= is lower or equal to 3<=5
5<=5
>= is greater or equal to 9>=2
5>=5

When using comparison operators the result of a comparison is either true or false. For instance:

  • 3 < 5 returns true,
  • 3 > 5 returns false.

It is also possible to combine comparisons together using boolean operators such as and and or. This enables to check if more than one comparison are true (and operator) or whether at least one of the comparisons is true (or operator). e.g.

  • (3 < 5) and (3 < 7) returns true,
  • (3 == 5) or (3 < 9) returns true,
  • (3 == 5) and (3 < 9) returns false.

Starter Activity


Click on the picture below to check your knowledge of computing operators:
operators-dominoes


zoo-parrot

Rio the talkative parrot

Rio the parrot gets very talkative if:

  • It is early in the morning (between 5am and 10am).
  • It is sunny outside.

Complete the code below to tell the zoo keeper whether Rio will be quiet or noisy.


zoo-hippo

Gloria the Hippopotamus


When it is hot outside (above 24 Celsius degrees), Gloria the Hippopotamus loves sunbathing for 1 hour (=60 minutes) before having a mud bath to cool down.

Complete the code below to tell the zoo keeper where he can expect to find Gloria: either sunbathing outside on the grass or having a bath in the muddy puddle.


zoo-lions

Leo the sleepy lion!


Did you know that a Lion sleeps on average 18 hours a day! Once Leo is awake he gets very hungry.
Complete the program bellow to tell the Zoo keeper if Leo will be asleep, hungry or happy!

Leo will be:

  • Sleepy if his sleeping time has not reached 18 hours
  • Hungry if his sleeping time is over 18 hours and he has not been fed.
  • Happy if his sleeping time is over 18 hours and he has been fed.


zoo-penguins

Penguins’ sunbathing time

During the summer the penguins love to go for a swim when the water temperature in the pool is at least two degrees cooler than the outside temperature.

Complete the code below to tell the zoo keeper where he can expect to find the penguins: either sunbathing outside or swimming in the pool.


Tagged with:

Marathon Time Calculator

marathonIn this challenge you are going to write a Python script to help a marathoner predict the overall time they can complete a Marathon in (42km).

This estimation will be based on the runner’s pace which is the time they take to run 1km.

For instance:

  • Runner A runs 1km in 5:25 (5 minutes and 25 seconds)
  • Runner B, who is slower, runs 1km in 6:10 (6 minutes and 10 seconds)

Your Python script will:

  1. INPUT: Ask the runner for their pace (e.g. 5:25),
  2. PROCESS: Convert this input into a number of seconds: e.g. 5:25 = 5 * 60 + 25 = 325 seconds,
  3. PROCESS: Multiply this total by 42 as there are 42km in a Marathon,
  4. PROCESS: Convert this new total using the hh:mm:ss format. (e.g 3:47:30)
  5. OUTPUT: Display this new total on screen (using the hh:mm:ss format). (e.g 3:47:30)

Flowchart


The following flowchart describes the main steps of our algorithm based on the
Input > Process > Output model:
marathon-flowchart

Your Solution


Code your solution to this challenge:

Step by Step Solution:


The 5 steps described above are solved to help you complete this challenge step by step:

Step 1: Input the pace in the mm:ss format
This step is fairly straightforward. We will use an input() function to retrieve the user input and a variable called str_pace to store this input as a string.

str_pace = input("At what pace do you run a km? e.g. 5:21")
Step 2: Convert this input into a number of seconds
This step is more complex as we need to extract the left and right side of the input. In python we can split a string using a character as a separator, in this case the colon (:). We will also use the int() function to convert (cast) a string into an integer.

split_pace = str_pace.split(":")
minutes = int(split_pace[0])
seconds = int(split_pace[1])
pace = minutes * 60 + seconds
Step 3: Multiply this total by 42 as there are 42km in a Marathon
totalTime = pace * 42
Step 4: Convert this new total using the hh:mm:ss format
The totalTime tells us how many seconds will the runner complete the Marathon in. Considering that there are 3600 seconds in one hour and 60 seconds in one minute we can use the DIV (//) (whole division) and MOD (%) (remainder operators to convert our total time in the required format.

hours = totalTime // 3600
timeLeft = totalTime % 3600

minutes = timeLeft // 60
seconds = timeLeft % 60
Step 5: Display this new total on screen
print("You should complete a marathon in " + str(hours) + ":" + str(minutes) + ":" + str(seconds) +".")
Note: To be 100% accurate you should time the pace by 42.195 instead of 42 as the exact length of a Marathon is 42km and 195 meters.

Testing


Now that you have implemented your solution you may want to test it by completing the following test plan: (this test plan is based on a length of 42km)

Test # Input Values Expected Output Actual Output
#1 Pace: 5:25 3:47:30
#2 Pace: 6:10 4:19:00
#3 Pace: 4:00 2:48:00
#4 Pace: 2:55 (Close to World Record) 2:02:30
unlock-access

Solution...

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

BBC micro:bit – Voting System

yes-noIn this challenge you will create a voting system using the BBC micro:bit. You can complete the code online on the BBC micro:bit website.

The idea is to use the BBC micro:bit in the classroom to conduct a survey by asking a yes/no question such as:

  • Should our school change our school uniform?
  • Should we have more computer science lessons on our timetable?
  • Should we have more healthy eating options on our school menu?

Then you will pass the micro:bit around so that each pupil can vote using the A and B buttons of the microbit:

  • A: Vote Yes
  • B: Vote No

Using two variables called voteA and voteB the BBC micro:bit will keep track how many times the A button is pressed and how many times the B button is pressed.

After each vote the BBC micro:bit will display a tick for two seconds to confirm the vote.

bbcmicrobit-vote-preview

To finish the vote the user will press both A and B buttons at the same time. In this case the BBC micro:bit will display how many A votes have been recorded (variable voteA), how many B votes have been recorded (variable voteB) and then use an If Statement to decide if option A (Yes) Or B (No) wins. To do so it will use comparison operators such as > or <. (if voteA > voteB then A wins)

Building the voting system step by step:


Step 1: Initialising the BBC micro:bit
bbcmicrobit-vote-1Let’s initialise our voteA and voteB variables that will be used to count how many tumes the A nad B buttons have been pressed.
Step 2: When button A is pressed
When button A is pressed we need to increment A by 1. Then we can display a tick to confirm the vote was recorded.
bbcmicrobit-vote-A
We then display a question mark to inform the user the BBC micro:bit is ready to accept another vote.
Step 3: When button B is pressed
Very similar to the previous code, this time to record the B vote.
bbcmicrobit-vote-B
Step 4: When A+B are pressed simultaneously
The user pressed both A and B at the same time to end the vote. In this case the BBC micro:bit will display how many A votes were recorded, how many B votes were recorded and decide if A or B wins or if it is a draw.
bbcmicrobit-vote-AB

Complete and Test your Voting System


Complete the system using the code provided above.

Test the game using the online emulator. Then when you are confident if fully works, download your code to the BBC micro:bit and conduct your first survey with your classmates. Make sure you ask for a question with only two possible answers (e.g. Yes/No question).

Tagged with:

Cake Sale

cakesaleYou are organising a cake sale and want to predict how much money you will raise.

During this cake sale you will be selling the following three types of cakes:
cakesale-cakes

Input


You decide to write a python script that asks the user three questions:

  • How many cupcakes do you plan to sell?
  • How many macarons do you plan to sell?
  • How many cheesecake do you plan to sell?

Process


The python script will then calculate the total money raised using the three user inputs and the prices as follows:

  • Cupcakes: 40p per cupcake,
  • macarons: 50p per macaron,
  • cheesecake: 70p per slice.

Output


The script will finally display this information (total money raised) to the end-user.

Complete the code


Complete your code in the trinket below.

Testing


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

Test # Input Values Expected Output Actual Output
#1 Cupcakes: 10
Macarons: 10
Cheesecake: 5
£12.50
#2 Cupcakes: 20
Macarons: 30
Cheesecake: 20
£37
#3 Cupcakes: 40
Macarons: 10
Cheesecake: 10
£28
#4 Cupcakes: 20
Macarons: 20
Cheesecake: 20
£32
#5 Cupcakes: 0
Macarons: 0
Cheesecake: 0
£0

ingredients

Video Tutorial


Extension Task


It did cost £12 pounds to buy all the ingredients to bake all the cakes.

Adapt your program to calculate and display the profit knowing that:


profit = money raised – expenses

Then use an If statement to check whether you have made a profit (profit > 0) or a loss (profit < 0) or whether you did break even (profit == 0).

unlock-access

Solution...

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

BBC micro:bit – Ukulele Chord Reader

Ukulele
For this challenge we are going to build a Ukulele Chord Reader for Eric Clapton’s version of the song: “Knock on Heaven’s Door” (Original Author Bob Dylan).

You may want to listen to the song first on youtube

The idea is to use the 25 LEDs of the micro:bit to display each chord of the song to assist a Ukulele player.

First let’s see how a chord works when using a Ukulele:
Ukulele-F-Chord

This is how we will represent the F chord on the BBC micro:bit:
micro-bit-F-chord

Knock on Heaven’s Door


Now let’s look at the full music sheet for “Knock on Heaven’s Door” by Eric Clapton:
Ukulele-Music-Sheet

Challenge


Your task consists of coding your BBC micro:bit (www.microbit.co.k) to represent each chord using the 25 LEDs.

Solution


If you are not sure how to get started, we have started the code for you:
Ukulele-Micro-bit-Solution

Your Task


Use the BBC micro:bit website to code the song. You will need to complete the code provided above to implement the full verse as provided on the above music sheet.

Extension Task 1:


Could you amend your code so that the song restart from the beginning whenever the user presses the A button of the micro:bit.

Extension Task 2:


Could you amend your code further so that the user can use the B button to pause and/or resume the song at any time.

Tagged with: ,

BBC micro:bit – Simon Game

simon-gameIn this blog post we are looking at recreating a fully working Simon Game using the BBC micro:bit.

If you are not sure what a Simon Game is you can check it on this wikipedia page.

You can watch the following two video clips to see the game in action, and understand the Python code used to implement it.

You will notice that our version of the game is simpler as we only use the two inputs from the micro:bit (A and B buttons) whereas the real Simon game is a bit more complex as it has four lights/buttons. The logic of the game remains the same though.

simon-game-vs-microbit

Python Code


If you have a micro:bit yoyu can use the micro:bit website and reuse the code provided below, ready to download to your micro:bit. You will have to use the Python code editor option.

# Simon Game - by 101Computing - www.101computing.net/microbit-simon-game
from microbit import *
import random

left = Image("96300:"
             "96300:"
             "96300:"
             "96300:"
             "96300")
             
right = Image("00369:"
             "00369:"
             "00369:"
             "00369:"
             "00369")

plus = Image("00000:"
             "00900:"
             "09990:"
             "00900:"
             "00000")

AB = ["A", "B"]

#Let's start with a sequence of three characters
sequence = random.choice(AB) + random.choice(AB) + random.choice(AB)

            
correct = True
sleep(1000)

while correct == True:
  #Let's start by displaying the sequence
  for character in sequence:
        if character=="A":
            display.show(left)
        elif character=="B":
            display.show(right)
        sleep(1000)
        display.show(plus)
        sleep(500)
   
  display.scroll("?")
   
  #Capture user input
  #The numbers of time the user will need to press the buttons depends on the length of the sequence
  maxInputs = len(sequence)
  capturedInputs = 0
  while capturedInputs < maxInputs and correct == True:
     if button_a.is_pressed():
        display.show(left)
        #Did the user guess it wrong? 
        if sequence[capturedInputs] == "B":
            correct = False
        sleep(500)    
        display.show(plus)        
        capturedInputs += 1
     if button_b.is_pressed():
        display.show(right)
       #Did the user guess it wrong? 
        if sequence[capturedInputs] == "A":
            correct = False
        sleep(500)
        display.show(plus)
        capturedInputs += 1
        
  #Add an extra character to the sequence
  if correct==True:
        sequence = sequence + random.choice(AB)
        display.show(Image.HAPPY)
        sleep(1000)

#Display Game Over  + final score
if len(sequence)>3:    
    display.scroll("Game Over: Score: " + str(len(sequence))) 
else:
    display.scroll("Game Over: Score: 0")
Tagged with:

BBC micro:bit – Stopwatch

stopwatch-micro-bitIn this challenge we are going to create a Stopwatch (Countdown timer) using the BBC micro:bit.

You do no need a micro:bit to complete this challenge as you can use the online block editor and emulator (www.microbit.co.uk) to code and test your program.

Our program will use both input buttons A and B and the LEDs for as an output:

  • Button A will be used to initialised the stopwatch. Per default the stopwatch will be set at 3 seconds. By pressing button A, the user should be able to increment this value by 1 second at a time.
  • Button B will be used to start the count down. Once this button is pressed the stopwatch should automatically decrement by 1 every second and it should stop when it reaches the value 0 (zero).
  • The LEDs should be used to display the countdown value.

micro-bit-3

Step by Step Solution


Watch this step by step video tutorial to complete the code of your stopwatch.

Extension Task


Option 1:
Can you update this code further so that when both buttons A and B are pressed at the same time, the timer is paused.

Option 2:
Can you update this code so that when the timer reaches zero (0), it displays the text “Happy New Year!”.

Tagged with:

BBC micro:bit – Traffic Light

lego-traffic-light-frontIn this challenge we are going to create and program a traffic light using lego bricks, leds and the BBC micro:bit.

Check this video clip of the complete traffic light in operation:

Step 1: Building the traffic light:

Use a few lego bricks to build the traffic light. Include your LEDs within your blocks and connect their pins to the red and black electric wires.

Make sure that you always connect the cathode of the LED (short leg, flat edge of the LED) to a black wire and use a blue or red wire for the other pin (anode).

lego-traffic-light-frontlego-traffic-light-backlego-led

Step 2: Connecting the traffic light to the BBC micro:bit


We recommend using crocodile clips for this step. Check the diagram below to make the right connections:
traffic-light-leds

Step 3: Programming the micro:bit


Our aim is to reproduce the following traffic light sequence:
traffic-light-sequence

Check below for the recommended code:

Solution 1: BasicSolution 2: Advanced
micro-bit-traffic-lights-blocks-1
In this solution we are adding a countdown when the green or the red light is on to inform the drivers who are waiting for the number of seconds redmaining before the traffic light changes.
micro-bit-traffic-lights-blocks-2

Electronic Circuit


bbc-microbit-traffic-light-circuit

Tagged with: ,

Youtube Channel: Video Tutorials

Python Tutorials: Less than 3 minutes series


video-python-3-min-for-loops

Python Tutorials: Getting Started with Python


video-python-tutorial-1-gettign-started video-python-tutorial-2-sequencing

Python Challenges: Solved!


video-python-challenge-turtle-maze video-python-challenge-discount-price-calculator video-python-challenge-window-cleaner

BBC micro:bit


video-micro-bit-car-racing

Find more videos on our YouTube channel:

101ComputingYouTubeChannel

BBC micro:bit – Car Racing Game

In this challenge you will recreate a fully working game using the BBC micro:bit. You can complete the code online on the BBC micro:bit website.

First check this video to see how this game will work:

Building the game step by step:


Step 1: Initialising the game
yellow-carLet’s initialise a few variables (score, gameOn) as well as our main sprite, the player’s car.

This code will then loop indefinitely while the game carries on. At the end once the game will be over it will display a game over message with the final score.
micro-bit-car-racing-step-1

Step 2: Controlling the main sprite
We are now going to add two event handlers to respond to the user interaction, when the user presses the button A or B. We will use code to move the car to the left or to the right by changing its X coordinate.
micro-bit-car-racing-step-2
Step 3: Adding the first car
The first car called car0 will be positioned at the top of the screen on lane 0. It will then move downwards (by changing the Y coordinate of the car) till it reaches the bottom of the grid. Once at the bottom of the screen we can check if it is colliding with the player’s car. If not we reposition the car at the top of the screen and give it a randomised delay.

The purpose of the randomised delay is to make sure that all 5 cars do not all come down at the same time.
micro-bit-car-racing-step-3

Step 4: Duplicating the code for each car
For this final step we can copy the code from step 3 and paste it for the other 4 cars (car1 to car4).
micro-bit-car-racing-step-4
That’s it the code is complete. You can test the game.

Extension Task


Option 1:
Tweak this code so that the game cars go faster and faster as the user’s score increases.

Option 2:
Change this game into a “Catch the fruit” game, where instead of avoiding the falling sprites the player should try to catch them and score a point each time they do so.

Tagged with: