More results...

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

Smoothies Ingredients Data Set

For this programming challenge, we are going to practise reading and extracting data from a JSON file. We will be using a JSON file storing information about the ingredients and recipes for
20 different smoothies.

JavaScript Object Notation (JSON)

JavaScript Object Notation (JSON) is a lightweight, text-based format for storing and exchanging data that is human and machine-readable. It is a standard format that is often used to transfer/retrieve data from a server using an API. It is used in a wide range of web and mobile applications that rely on accessing/exchanging live data.

A JSON file is like a dictionary data structure. It is made up of two primary parts: keys and values. A key/value pair follows a specific syntax:

  • Key: Always a string enclosed in quotation marks
  • Value: Can be a string, number, Boolean expression, array/list, or object

Complex data structure can be created using JSON by combining {dictionaries} and [arrays/lists].

The smoothies data set: JSON vs. XML format

JSON Data SetXML Data Set
Here is an extract of the smoothies.json file showing the data for the first three smoothies.

Within this file, the main key is “smoothies”. Its value is an array of 20 different smoothies. Each smoothie is stored as a dictionary with 3 keys:

  • Name
  • Ingredients: a list of ingredients
  • Recipe
{
  "Smoothies": [
    {
      "Name": "Strawberry Banana",
      "Ingredients": ["Strawberries", "Banana", "Greek Yogurt", "Honey", "Almond Milk"],
      "Recipe": "Blend 1 cup of strawberries, 1 banana, ½ cup of Greek yogurt, 1 tablespoon of honey, and 1 cup of almond milk. Blend until smooth."
    },
    {
      "Name": "Green Detox",
      "Ingredients": ["Spinach", "Kale", "Green Apple", "Cucumber", "Lemon Juice", "Coconut Water"],
      "Recipe": "Combine 1 cup of spinach, 1 cup of kale, 1 green apple (cored and chopped), ½ cucumber, 1 tablespoon of lemon juice, and 1 cup of coconut water. Blend until smooth."
    },
    {
      "Name": "Mango Pineapple",
      "Ingredients": ["Mango", "Pineapple", "Orange Juice", "Coconut Milk", "Chia Seeds"],
      "Recipe": "Blend 1 cup of mango, 1 cup of pineapple, 1 cup of orange juice, ½ cup of coconut milk, and 1 tablespoon of chia seeds. Blend until smooth and creamy."
    }
  ]
}
An alternative approach to store data is to use an XML file. Here is the same data for the first three smoothies, stored as an XML file.

<Smoothies>
    <Smoothie>
        <Name>Strawberry Banana</Name>
        <Ingredients>
            <Ingredient>Strawberries</Ingredient>
            <Ingredient>Banana</Ingredient>
            <Ingredient>Greek Yogurt</Ingredient>
            <Ingredient>Honey</Ingredient>
            <Ingredient>Almond Milk</Ingredient>
        </Ingredients>
        <Recipe>Blend 1 cup of strawberries, 1 banana, ½ cup of Greek yogurt, 1 tablespoon of honey, and 1 cup of almond milk. Blend until smooth.</Recipe>
    </Smoothie>
    <Smoothie>
        <Name>Green Detox</Name>
        <Ingredients>
            <Ingredient>Spinach</Ingredient>
            <Ingredient>Kale</Ingredient>
            <Ingredient>Green Apple</Ingredient>
            <Ingredient>Cucumber</Ingredient>
            <Ingredient>Lemon Juice</Ingredient>
            <Ingredient>Coconut Water</Ingredient>
        </Ingredients>
        <Recipe>Combine 1 cup of spinach, 1 cup of kale, 1 green apple (cored and chopped), ½ cucumber, 1 tablespoon of lemon juice, and 1 cup of coconut water. Blend until smooth.</Recipe>
    </Smoothie>
    <Smoothie>
        <Name>Mango Pineapple</Name>
        <Ingredients>
            <Ingredient>Mango</Ingredient>
            <Ingredient>Pineapple</Ingredient>
            <Ingredient>Orange Juice</Ingredient>
            <Ingredient>Coconut Milk</Ingredient>
            <Ingredient>Chia Seeds</Ingredient>
        </Ingredients>
        <Recipe>Blend 1 cup of mango, 1 cup of pineapple, 1 cup of orange juice, ½ cup of coconut milk, and 1 tablespoon of chia seeds. Blend until smooth and creamy.</Recipe>
    </Smoothie>
</Smoothies>

Python Code

To be able to read and extract data from our JSON file using Python, we will use the json library. Here is an example of how to use Python code to load the JSON data from the smoothies.json file. We can then perform a basic linear search to retrieve all the smoothies with “Mango” listed in their list of ingredients.

import json
 
# load JSON data from file
file = open('smoothies.json','r')
data = json.load(file)
file.close()

# Perform a linear search using the JSON data
smoothies = data["Smoothies"]
for smoothie in smoothies:
   if "Mango" in smoothie["Ingredients"]:
      print(smoothie["Name"])
      print(smoothie["Recipe"])
      print("--------------------")

You can test and edit this code below:

Your Task:

Your task consists of creating a program that lets the end-user do the following:

     Enter a list of ingredients they would like to have in their smoothie. e.g. Papaya, Pineapple and Mango
     Enter a list of ingredients they do not want to have in their smoothie. e.g. Peanut Butter and Cocoa Powder.
     Retrieve a list of all smoothies matching these criteria.
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 Coffee Shop – Price Calculator

Your local coffee shop would like to set up a touchscreen tablet on the counter for the baristas to quickly calculate the cost of the cups of coffee ordered by the customers.

Here are the options available when ordering a coffee:

The new system will need a computer program to let a barista pick up the order details. The barista should be able to specify:

     The type of coffee being ordered: There are 7 options: Espresso, Americano, Latte, Cappuccino, Macchiato, Mocha and Flat White
     The size of their coffee cup. Per default a coffee comes in a medium cup, however a customer may ask of a large or an XL cup.
     Whether they would like to eat in or take their coffee away

Based on the user inputs and the price list provided above, the system should automatically calculate and display the total price of the chosen cup of coffee.

Step 1: Draw a Flowchart for your algorithm

Before attempting to complete the code for this task, grab a piece of paper and draw the flowchart to identify the key inputs, decisions and calculations for your algorithm.

Alternatively, you can also create your flowchart online:
Flowchart Studio

Step 2: Complete the Python Code

Complete the Python code below.

Step 3: Add validation checks

To make your program more robust, add some validation rules on your inputs so that:

     The barista can only enter one of the seven options when entering the type of coffee.
     The barista can only opt for M, L or XL when entering the size of the cup.
     The user can only enter Yes or No when asked whether they would like to opt for the takeaway option.

You can find out more about implementing validation checks in Python using this page (input validation tab).

Step 4: Test Plan

Once your code is complete, test it using the following test plan to make sure all your calculations are correct!

Test # Input Values Expected Output Pass / Fail
#1 Type of Coffee: Espresso
Cup Size: L
Takeaway? Yes
Coffee Cup Price: £4.50
#2 Type of Coffee: Cappuccino
Cup Size: M
Takeaway? No
Coffee Cup Price: £3.00
#3 Type of Coffee: Mocha
Cup Size: XL
Takeaway? Yes
Coffee Cup Price: £6.00
#4 Type of Coffee: Flat White
Cup Size: XL
Takeaway? Yes
Coffee Cup Price: £5.00
#5 Type of Coffee: Breakfast Tea
Cup Size: L
Takeaway? Yes
Invalid option. Please select a type of coffee from the menu.

Ordering Multiple Coffees…

We would like you to improve this system so that when a customer order multiple coffees, the barista can enter all the details for the different coffees being ordered and the system works out the total cost of the order.

These are the three amendments you will have to make to your code:

     Your system should start by asking the barista how many cups of coffees are being ordered.
     Then for each coffee, the barista will enter the details (Type of drink, cup size, takeaway?)
     The system will calculate and output the total price of the order.
unlock-access

Solution...

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

School Room Finder

Your school is organising an open evening event where prospective parents will be able to visit the different classrooms and departments to get to find out more about the school and meet with the teachers. Parents have been given a list of rooms and activities going on during this open evening. The school will use students leaders to help guide the parents between the different buildings. The school would also like to develop an App for parents to use on their phones to help them locate a room. They would like this app to:

  • Let the parent enter the name of a room (e.g. Sports Hall) or its room code (e.g. A205).
  • The App should indicate in which building this room is located and on what floor it is.

The school consists of 5 main buildings: The A Block, the B Block, the C Block, a 6th Form Block and a Sports Hall.

The A, B and C blocks have three floors. Each classroom within these blocks is given a code such as A205. The first letter of this code is referring to the building (e.g. A for A Block).
The number is based on which floor the room is on:

  • Classrooms with a number lower than 100 are on the ground floor. (e.g. A15, B7, C23)
  • Classrooms with a number between 100 and 199 are located on the first floor. (e.g. A101, B120, C119)
  • Classrooms with a number of 200 and above are located on the second floor. (e.g. A205, B220, C231)

The Sixth Form block only contains two floors: the ground floor and the first floor. Classrooms in the 6th form block have a code starting with letter S.

  • Classrooms with a number lower than 20 are on the ground floor. (e.g. S4, S15)
  • Classrooms with a number of 20 and above are located on the first floor (e.g. S20, S27)

Other rooms of the school (other than classrooms) do not have a specific code. They include the Main Reception, the Dance Studio, the Activity Studio, the Sports Hall, the Staffroom and the Canteen. These are spread around the school site within the different blocks. Specific instructions on where these are located also need to be provided by the App.

Your Task

Last year, the head of school asked one of the Computer Science GCSE students to produce the code for this App. Initially, the app was not meant to cater for the 6th From block as it was not used for the open evening. This year however, the 6th form block will be accessible by parents. The student who created the App has now passed his GCSE and left the school. We therefore need you to look at their code and complete the code to make sure that it does provide instructions to locate classrooms from the 6th form block.

A new Coffee Bar has also been created on the first floor of the C block. You will need to amend the code to also include directions to the Coffee Bar.

We have also realised an issue with the code. If a parent enters a room code for a building that does not exists (e.g. D102) the app should tell them that this room does not exist. This is not the case currently. Can you fix this code to make sure only valid room codes starting with A, B, C or S or valid room names are used.

Test Plan

To make sure your app is fully working as expected, you will have to make sure that it passes the following 10 tests!

Test # Input Values Expected Output Pass or Fail?
#1 A205 This room is located in the A Block. It is on the second floor.
#2 B14 This room is located in the B Block. It is on the ground floor.
#3 C101 This room is located in the C Block. It is on the first floor.
#4 S12 This room is located in the 6th Form Block. It is on the ground floor.
#5 S22 This room is located in the 6th Form Block. It is on the first floor.
#6 D102 We cannot locate this room! Are you sure this is a valid room?
#7 Main Reception This room is located at the main entrance of the A block.
#8 Sports Hall This room is located on the side of the B Block.
#9 Coffee Bar This room is located on the first floor of the C block.
#10 Swimming Pool We cannot locate this room! Are you sure this is a valid room?

Python Code

Here is the Python code for the App so far…

Extension Task

Adapt this whole code to make it work for your school. Find out how room codes are used and tweak the code accordingly.

unlock-access

Solution...

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

Circular Maze Challenge

The aim of this challenge is to use Python Turtle to trace a path to solve this circular maze.

By doing so we will investigate how we can draw different arcs of different radiuses and different lengths to guide the Python turtle through the maze.

Our Python code will make use of a function called drawArc() that takes three parameters:

  • The radius of the arc (in pixels)
  • The starting angle of the arc (in degrees)
  • The angle of the arc (in degrees)

To fully understand the purpose of these three parameters let’s look at the following three examples:

The third examples demonstrate how we can use a negative angle to change the direction of the arc. A positive angle draws an arc anti-clockwise, whereas a negative angle draws and arc clockwise.

Now let’s use Python Turtle to solve this challenge.

Python Code

We have started the code for you and drawn the first two arcs using our drawArc() function. Your task is to complete this code by drawing additional arc until you reach the exit gate.

To complete this challenge, you will have to use a trial and error approach, testing your code with different parameter values when using the drawArc(), forward() and setheading() functions and refining your code by tweaking these values.

unlock-access

Solution...

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

Pronic Numbers Challenge

A pronic number is a number which is the product of two consecutive integers.

For instance 42 is a pronic number because 42 = 6 x 7.

One approach to work out if a number n is a pronic number or not is to find out if there is a positive integer i lower than n that solve this equation: n = i(i+1).

If there is such a number i, then n is a pronic number.

Did you know?

Pronic numbers are also called oblong numbers or heteromecic numbers.

Python Challenge

Your task is to write new function called isPronic that takes one parameter, an integer value and returns True is the parameter is a pronic number, False otherwise.

You should then write a small program that will:

     Prompt the user to enter a number.
     Use the isPronic function to find out is the number entered is pronic or not.
     Produce a meaningful output to the end-user.

Extra Challenge

Reuse your function to write a new Python program that outputs all the pronic numbers between 0 and 1,000!

Python Code

unlock-access

Solution...

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

Olympics Host Cities (CSV Challenge)

For this challenge we are going to work with a list of host cities of the Olympic Games since the modern Olympics began in 1896. Our list will include both Summer and Winter games. This information is stored in a CSV file called olympics.csv. We will use a Python program to access this file and extract relevant data to answer specific queries about the Olympic Games.

Comma Separated Values (CSV)

Comma-separated values (CSV) is a text file format used to save tabular data. When considering a table of data, each line of the table is called a record. A record is made of fields. Each field stores a single value for each record.

To save this structured/tabular data, a CSV file uses commas (,) to separate values/fields, and newlines to separate records: each line of the file typically represents one data record. Each record consists of the same number of fields, and these are separated by commas in the CSV file.

Note that on occasions, it is not possible to use the comma as a separator if it is likely that the comma might be used in the data being stored. In this case a less common character might be used as a separator instead of the comma. This could be a semi-colon (;) or a pipe (¦). Even though the comma is not used, we can still consider such a file to be a CSV file.

In our case, our CSV file will use one line per Olympic Games. Each line/record will consists of four fieds:

year,city,country,season

You can see below the first few lines of the olympics.csv file:

1896,Athens,Greece,Summer,
1900,Paris,France,Summer,
1904,St. Louis,United States,Summer,
1908,London,United Kingdom,Summer,
1912,Stockholm,Sweden,Summer,
1920,Antwerp,Belgium,Summer,
1924,Chamonix,France,Winter,
1924,Paris,France,Summer,
...

Python Code

We can easily read the content of a text file in Python and iterate through each line of the file:

file = open("olympics.csv","r")
for line in file:
    print(line)      
file.close()

As each line consists of 4 fields separated by a comma, we can use the split() function in Python to convert each line into a list of values. We can then extract each value one at a time:

file = open("olympics.csv","r")
for line in file:
    data = line.split(",")
    year = data[0]
    city = data[1]
    country = data[2]
    season = data[3]    
    print(city + " hosted the " + season + " olympics in " + year)
file.close()

We have completed a Python script to scan through all the lines of the CSV file to only display a list of Summer Olympic Games and ignore the Winter games.

Your Task

Update the above code to let the user:

     List all the Winter Olympic Games
     List all the Olympic Games that were hosted in the United States
     Find out how many times did London (UK) host the Olympic Games
     Let the user enter a year and find out which city hosted the Olympic Games on the year they entered.
unlock-access

Solution...

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

Paris 2024 – JSON Challenge

The Paris 2024 Olympics provided a great opportunity for around 10,500 athletes to compete in 329 events, each event giving an opportunity for competing athletes to win one of the three medals: Gold, Silver and Bronze. All together, 206 countries were represented and the 2024 Olympics also included athletes from the IOC Refugee Team, which regroups displaced and refugee athletes.

For this programming challenge, we are going to search through a list of all the Paris 2024 medallists to answer specific queries and generate some statistics. All information about the Paris 2024 is stored in a JSON file called medals.json.

JavaScript Object Notation (JSON)

JavaScript Object Notation (JSON) is a lightweight, text-based format for storing and exchanging data that is human and machine-readable. It is a standard format that is often used to transfer/retrieve data from a server using an API. It is used in a wide range of web and mobile applications that rely on accessing/exchanging live data.

A JSON file is like a dictionary data structure. It is made up of two primary parts: keys and values. A key/value pair follows a specific syntax:

  • Key: Always a string enclosed in quotation marks
  • Value: Can be a string, number, Boolean expression, array, or object

Complex data structure can be created using JSON by combining {dictionaries} and [arrays].

medals.json

Before attempting this challenge you will need to familiarise yourself with the structure of the provided JSON file: medals.json

Within this file, the main key is “athletes”. Its value is an array of all the medallists of the Paris 2024 Olympics. Each medallist is stored as a dictionary with 4 keys:

  • name (Lastname firstname): e.g. Marchand Leon
  • gender: e.g. M
  • country: e.g. France
  • medals: An array of all the medals won by this athlete. Each medal within this array is another dictionary consisting of four keys:
    • discipline: e.g. Swimming
    • medal: e.g. Gold
    • event: e.g. Men’s 200m Butterfly
    • date: e.g. 2024-07-31

Here is an extract of the medals.json file showing the data for the first two athletes: Yufei Zhang who won 6 medals for China and Leon Marchand who won 5 medals for France.

{
  "athletes": [
    {
      "name": "Zhang Yufei",
      "country": "China",
      "gender": "F",
      "medals": [
        {
          "discipline": "Swimming",
          "medal": "Bronze",
          "event": "Women's 4 x 100m Medley Relay",
          "date": "2024-08-04"
        },
        {
          "discipline": "Swimming",
          "medal": "Bronze",
          "event": "Women's 4 x 100m Freestyle Relay",
          "date": "2024-07-27"
        },
        {
          "discipline": "Swimming",
          "medal": "Bronze",
          "event": "Women's 50m Freestyle",
          "date": "2024-08-04"
        },
        {
          "discipline": "Swimming",
          "medal": "Silver",
          "event": "Mixed 4 x 100m Medley Relay",
          "date": "2024-08-03"
        },
        {
          "discipline": "Swimming",
          "medal": "Bronze",
          "event": "Women's 100m Butterfly",
          "date": "2024-07-28"
        },
        {
          "discipline": "Swimming",
          "medal": "Bronze",
          "event": "Women's 200m Butterfly",
          "date": "2024-08-01"
        }
      ]
    },
    {
      "name": "Marchand Leon",
      "country": "France",
      "gender": "M",
      "medals": [
        {
          "discipline": "Swimming",
          "medal": "Gold",
          "event": "Men's 200m Breaststroke",
          "date": "2024-07-31"
        },
        {
          "discipline": "Swimming",
          "medal": "Gold",
          "event": "Men's 400m Individual Medley",
          "date": "2024-07-28"
        },
        {
          "discipline": "Swimming",
          "medal": "Gold",
          "event": "Men's 200m Individual Medley",
          "date": "2024-08-02"
        },
        {
          "discipline": "Swimming",
          "medal": "Bronze",
          "event": "Men's 4 x 100m Medley Relay",
          "date": "2024-08-04"
        },
        {
          "discipline": "Swimming",
          "medal": "Gold",
          "event": "Men's 200m Butterfly",
          "date": "2024-07-31"
        }
      ]
    }
  ]
}

Python Code

To be able to read and extract data from our JSON file using Python, we will use the json library. Here is an example of how to use Python code to load the JSON data from the medals.json file. We can then perform a basic linear search to retrieve all the medallists from Great Britain.

import json
 
# load JSON data from file
with open('medals.json','r') as file:
    data = json.load(file)

# Perform a linear search using the JSON data
athletes = data["athletes"]
for athlete in athletes:
    if athlete["country"]=="Great Britain":
       print(athlete["name"])

Let’s use this code to enable the end-user of our program to list all the medallists for their chosen country.

Your Task:

Your task consists of adding extra functions to the above code to perform the following:

     List all the athletes for a given country who won at least one gold medal
     Ask the end-user to enter a discipline. List all the medallists for this discipline.
     Ask the end-user to enter the name of an athlete. The program should list all the medals won by this athlete.
unlock-access

Solution...

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

Online Python IDE

Try this Online Python IDE (Integrated Development Environment) to help you code in Python within your web-browser. The main benefit of using an online IDE is that you will not need to install anything on your computer. Your Python code is interpreted and executed within you web browser.

With this IDE, it is not possible (yet!) to save your code online. You can however use the download button to save your files locally.

This IDE includes some built-in libraries that you can import in your projects including:

  • Turtle library (import turtle)
  • Random library (import random)
  • Time library (import time)
  • Math library (import math)

Try it yourself:

To access this IDE directly from your web-browser use the following URL: https://www.101computing.net/python

Space Explorer: The Way Back Home

Space Explorer
You are onboard a spaceship lost in a distant galaxy, far far away from planet Earth. Your aim is to return to planet Earth by using teleportation gates (black holes) to jump from one galaxy to another until you can reach planet Earth. Follow the instructions given to locate these black holes. But be aware, space is a dangerous environment. If you fail to follow the given instructions or if you hit an asteroid or a planet, your shape ship will be lost in space forever!

To complete this activity you will need to use the arrow keys on your keyboard to go North, East, South or West.
Arrow Keys

Click on the picture below to access this activity.
Space Explorer - The Way Back Home

The Lost Treasures of Pirate Island


Be the captain of your own pirate ship and sail the seven seas to find the 32 lost treasures of pirate island. Follow the instructions given to locate these treasures. But be aware, the sea is dangerous and its storms can be terrible. If you fail to follow the given instructions or if you hit a rock or an island, your ship will sink to the bottom of the deep blue sea!

To complete this activity you will need to use the arrow keys on your keyboard to go North, East, South or West.

Click on the picture below to access this activity.