More results...

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

Name the Country: Python Challenge


In this challenge, you will use your Python skills to create a quiz where the player has to guess the name of a country when they can only see the first letter of that country.

When a player gives an incorrect guess, the next letter of the correct answer is revealed.

The quiz should have a scoring system that adds to the player score a number of points corresponding to the number of letters still hidden.

The quiz should repeat itself 10 times, each time with a different country. At the end the computer should reveal the total score of the player.

As an extension task, a leader board should be added to store the player’ name and score in a text file (CSV format).

Structure Diagram

Here is the structure diagram (Decomposition diagram) for this project:

The main tasks for this project are as follows:

    Initialise the game

       Initialise a list of at least 20 countries
       Initialise player score to 0

    Quiz Engine

       Randomly pick a country from the list of countries
       Display the clue (e.g. C _ _ _ _ _ )
       Collect the user guess
       Check if the user is correct and if not repeat the process with a new clue.
       If the user is correct, calculate and display their new score
       Repeat the quiz 10 times with 10 different countries

    Game Over / Leaderboard

       Display a “Game Over” message and the total score
       Ask the player to enter their name
       Store the player’s name and score in a leaderboard file
       Display the leader board (Top 10 scores in descending order)

Displaying the Clue

To help you with this project, we have already created a procedure called displayClue() that takes two parameters: word and x and displays the first x letter of a word following with _ characters for each remaining letters of the given word.

The Python code for our function is as follows:

# A subroutine to display the first x letters of a word
# and replace the remaining letters with _
def displayClue(word,x):
   clue = ""
   for i in range (0, len(word)):
      if i<x:
         clue = clue + word[i]
      else:
         clue = clue + "_"
      clue = clue + " "   
   print("Name the country: " + clue.upper())

Python Code

Your task is to complete the code below to recreate this “Name the Country” Quiz:

unlock-access

Solution...

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

Periodic Table of Elements – JSON Challenge

The periodic table is a chart that organises all known chemical elements based on their atomic number, electron configurations, and recurring chemical properties. It serves as a fundamental tool in chemistry, physics, and other sciences, helping scientists understand the relationships and behaviours of elements.

For this programming challenge, we are going to search through a list of all 118 elements of the Periodic Table to answer specific queries, generate some statistics and create quizzes. All the information needed for this challenge about the elements of the Periodic Table is stored in a JSON file called periodic-table.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].

periodic-table.json

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

Within this file, the main key is “elements”. Its value is an array of all the elements of the Periodic Table. Each element is stored as a dictionary with 4 keys:

  • Symbol: e.g. H
  • Name: e.g. Hydrogen
  • Atomic Number: e.g. 1
  • Atomic Mass: 1.008
  • Phase: Gas

Here is an extract of the periodic-table.json file showing the data for the first three elements: Hydrogen, Helium and Lithium.

{
  "elements": [
	{
	"Symbol": "H",
	"Name": "Hydrogen",
	"Atomic Number": 1,
	"Atomic Mass": 1.008,
	"Phase": "Gas"
	},
	{
	"Symbol": "He",
	"Name": "Helium",
	"Atomic Number": 2,
	"Atomic Mass": 4.0026022,
	"Phase": "Gas"
	},
	{
	"Symbol": "Li",
	"Name": "Lithium",
	"Atomic Number": 3,
	"Atomic Mass": 6.94,
	"Phase": "Solid"
	},

        ...

   ]
}

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 periodic-table.json file. We can then perform a basic linear search to retrieve all the elements in the “Solid” form.

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

# Perform a linear search using the JSON data
elements = data["elements"]
for element in elements:
    if element["Phase"]=="Solid":
       print(element["Name"])

You can try and edit this code on our online IDE below:

Your Task:

In the periodic table, the phase of an element refers to its physical state (solid, liquid, or gas) under standard conditions of temperature and pressure (STP), which are typically defined as a temperature of 0°C (273.15 K) and a pressure of 1 atmosphere (atm).

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

     Generate some statistics to calculate and display the percentage of elements in the Periodic Table which are solid, liquid and gas.

     Create a quiz consisting of 10 questions. For each question your program will randomly pick an element from this json file (e.g. Helium) and ask the user to guess its phase (Solid, liquid or gas?).
     Create another quiz where, for each question, your program will randomly pick an element from this json file and display its symbol (e.g. Au) to then ask the user to guess the name of the element (e.g. Gold).

Help…

You can use the following code to randomly pick an element from the periodic table:

import json, random
 
# load JSON data from file
with open('periodic-table.json','r') as file:
    data = json.load(file)

# Perform a linear search using the JSON data
elements = data["elements"]
element = random.choice(elements)

print("Randomly picked element: " + element["Name"])
Tagged with:

Computer Software Card Game

There are a wide range of software that can be used on a computer system and these can be grouped in three main categories:

  • Operating System: The Operating System (OS) is the foundational software that manages a computer’s hardware and software resources, providing a platform for other software to run (e.g., Windows, macOS, Linux).
  • Utility Software: Utility Software includes tools designed to maintain and optimise the performance of the computer, such as antivirus programs, disk defragmentation software, and file management utilities.
  • Application Software: Application Software consists of programs designed for specific user tasks, like word processors, web browsers, graphic editing software and video games, enabling users to perform activities on the computer.

For this challenge we will consider a deck of cards where each card represents a piece of software. The game will consist of randomly selecting three cards from the deck and revealing them to the player:

Based on the cards selected, the player may score points as follows:

Three of a KindSplitPair
Three of a Kind: If all three software are from the same category, the player will score 100 points. This could be when three Operating System cards are revealed, or three utility software or three application software. e.g.

Split: If the first card and the third card are from the same category, the player will score 50 points. Note that the card in the middle will need to be from a different category. e.g.

Pair: If either the first two cards or the last two cards are from the same category, the player will score 30 points. Note that the remaining card will need to be from a different category. e.g.

Python Code


We have started the code by first creating three lists, each of these listing 6 different pieces of software:

OS = ["Windows 10","Linux","MacOS","iOS","Android","MS DoS"]
utilities = ["Anti-Virus Software","Firewall","Encryption Software","File Compression Software","Disk Defragmentation Software","Backup Software"]
application = ["Word Processing Software","Presentation Software","Spreadsheet Software","Web Browser","Graphic Editing Software","Video Editing Software"]

Then we are creating a full deck of 18 cards by combining all three lists into a single list.

software = OS + utilities + application

Using the random library, we can easily pick a random software card from our list of software:

import random
card = random.choice(software)

We can easily check what type of software our card by checking if it belongs to one of the three sub lists:

if card in OS:
   print(card + " is an example of Operating System.")
elif card in utilities:
   print(card + " is an example of Utility Software.")
elif card in application:
   print(card + " is an example of Application Software.")

You can check the following code below. Your task is to complete this code to implement the card game with its scoring system and making sure the player can repeat the process of picking three cards randomly as long as they wish to.

unlock-access

Solution...

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

For Loops Challenges

For this set of challenges, we are going to teach our AI:Bot some basic maths skills such as how to count in 5 from 0 to 500 or how to count down from 100 to 0. We are also going to make our AI:Bot practise the times tables and recite the alphabet from A to Z.

Writing Lines!Counting in 5Counting DownTimes TablesThe AlphabetIterative SumFactorial

Writing Lines!


First we need to make sure that our AI:Bot is fully focused and willing to complete the work when asked to. So let him learn our expectations by making the AI:Bot copy the following lines on the screen:

Can you tweak the code below for the following line to appear 100 times on the screen:

“I will listen to my teacher and complete my work on time.”

Counting in 5

We are now going to use a step in our for loop to count in 5.

Check the code below and tweak it to train your AI:Bot to count in 5 from 0 to 500.

# Counting in 2 from 0 to 100
for i in range(0,100, 2):
   print(i)

Counting down

Tweak the code from the previous task to train your AI:Bot to count down from 100 to 0! (Tip: you will have to use a negative step of -1)

Times Tables

Train your AI:Bot to display the 12 times table as follows:

Once done, tweak your code so that it starts by asking for a number. It will then display the times table for this given number.

The Alphabet

We are now going to train our AI:Bot to recite the 26 letters of the Alphabet from A to Z.
To do so we will use the ASCII code which give a unique integer value to each character that appears on your keyboard, including the 26 uppercase letters of the alphabet.

You can for instance try the following code to display the first three letters of the alphabet:

# Using the ASCII code to display letters of the alphabet
print(chr(65))
print(chr(66))
print(chr(67))

Combine the above code with a For loop to train your AI:Bot to recite the entire alphabet from A (ASCII code 65) to Z (ASCII code 90).

Iterative Sum


Let’s look at the following code that can be used to find the iterative sum for number 5 using the following calculation:

Iterative sum for 5 = 5 + 4 + 3 + 2 + 1

#Iterative Sum for number 5

sum = 0
for i in range(1,6): 
   sum = sum + i

print("Iterative Sum for 5 = " + str(sum))

Your task is to tweak the above code to get the computer to ask for a positive integer value and calculate the iterative sum for this given number.

Factorial!

We are now going to train our AI:Bot to calculate a factorial of a number! Your program will ask for the user to enter a positive integer value and return its factorial value as follows:

You can complete this program by tweaking the code used to calculate the iterative sum as the two calculations are quite similar.

Python Code

unlock-access

Solution...

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

The Programming Skills Survey

You have been tasked with creating a Python program that generates a survey about programming preferences and skills. Your program will have to:

Ask the user a series of questions about their programming experience.
Validate the user’s input for each question of the survey using different validation checks.
Store the responses in a text file (CSV file format).

Validation Checks in Python


The following tabs will show you how to implement different validation checks using Python.
Presence CheckType CheckRange CheckLookup CheckCharacter CheckLength CheckTry again!

Input Validation: Presence Check


A presence check is useful to ensure an input is not empty.

name = input("Enter your name:").strip() 

if name=="":
    print("Empty name!")
else:
    print("Thank you!")


Input Validation: Type Check – Integer?


A type check ensures the input is of the correct data type (e.g. check that te user enters an integer value when required to do so).

number = input("Type a number:")

if number.isdigit():
    print("This is a number")
else:
    print("This is not a whole number")


Input Validation: Range Check


A range check is used to ensure an input falls within a numerical range, between a minimum value and a maximum value).

number = int(input("Type a number between 1 and 5:"))

if number>=1 and number<=5:
    print("Valid number")
else:
    print("Invalid number")


Input Validation: Lookup Check


A lookup check ensures the input provided matches one of a predefined set of valid options.

drive = input("Can you drive?").lower()

if drive in ["yes","no"]:
    print("Valid answer")
else:
    print("Invalid answer")


Input Validation: Character Check


Format checks/Character checks: can be used to ensure the input is following a specific format or include specific characters (e.g. a valid e-mail address should include an @ character).

email = input("Type your e-mail address:")

if "@" in email:
    print("Valid e-mail address")
else:
    print("Invalid e-mail address")

postcode = input("Type your postocode:").upper()

if postcode[0] in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" and postcode[1] in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" and postcode[2] in "123456789":
    print("Valid postcode")
else:
    print("Invalid postcode")

Input Validation: Length Check


Length checks are used to validate the length of the input (e.g. minimum or maximum number of characters).

password = input("Type a password:")

if len(password)>=8:
    print("Valid password")
else:
    print("Invalid password")


Try Again! Using a While Loop:


Using a while loop within your validation checks instead of an if statement will allow the user to have multiple attempts if needs be to enter a valid input.

name = input("Enter your name:")

while name=="":
    print("You must enter your name! Please try again!")
    name = input("Enter your name:")

print("Welcome " +  name)

You can investigate more advance approaches to implement validation subroutines on this blog post.

List of questions for the survey

Your survey will consist of the following questions and validation checks:

Question Validation check
1. What is your name? Presence Check – User input cannot be an empty string
2. What is your e-mail address?” Format Check – Must be contain an @ character
3. How many years have you been programming? Type Check / Range Check – Must be a positive integer value.
4. What is your favourite programming language? Lookup Check – Must be one of [“Python”, “JavaScript”, “Java”, “C++”, “Other”]
5. Describe your programming skills in a few words. Length Check – Must be at least 10 characters
6. How would you rate your programming skills using a score value between 1 (Beginner Level) and 5 (Advanced Level)? Range Check – Must be a number between 1 and 5

Python Code

We have stared the survey for you but have only completed the code for the first question. Complete the code below to ask all 6 questions and implement the required validation checks for each question. You will also need to add some code to save all the survey results in a text file (CSV file format).

Extension Ideas:

Complete your code to:

    Add more questions with other validation checks.
    Allow users to view their responses before saving them to the file.
    Provide an option to retake the survey or correct specific answers.

Parameter Passing: Take the Quiz

When we call a function in a programming language, we often need to pass data (or parameters) to that function for it to operate on. The way these parameters are passed — either by value or by reference — plays a critical role in how a function interacts with the data. This distinction influences whether changes made to the parameters within the function affect the original data outside the function.

Passing parameters by value or reference determines whether a function receives a copy of a variable (value) or a reference to the original variable (reference).

Passing Parameters by Value

When parameters are passed by value, a copy of the data is passed to the function. This means that the function works with a separate copy, and any changes made to the parameter inside the function do not affect the original data outside the function. This approach provides a level of safety, ensuring that the function’s operations on the parameter do not have unintended side effects on the original data.

Did you know? In Python, immutable data types such as integers, strings, and tuples are always passed by value.

def modify_value(x):
    x = x + 5
    print("Inside function:", x)

a = 10
modify_value(a)
print("Outside function:", a)

With this example the output would be:
Inside Function: 15
Outside Function: 10

Explanation:
We define a function, modify_value, which adds 5 to its parameter x.
We call the function with a, an integer set to 10.
Inside the function, x becomes 15, but a outside the function remains unchanged at 10.

Since integers are immutable, Python effectively passes them by value. The function receives a copy of a, not the original a, so any changes within the function do not reflect outside it.

Passing Parameters by Reference

When parameters are passed by reference, the function receives a reference to the original data, not a copy. Therefore, any modifications to the parameter inside the function will directly affect the original data outside the function. This approach can make code more efficient, as it avoids copying large amounts of data, but it requires careful handling to avoid unintended side effects.

In Python, mutable types such as lists and dictionaries are passed by reference.

def modify_list(list):
    list.append(5)
    print("Inside function:", list)

my_list = [1, 2, 3, 4]
modify_list(my_list)
print("Outside function:", my_list)

With this example the output would be:
Inside Function: [1, 2, 3, 4, 5] Outside Function: [1, 2, 3, 4, 5]

Explanation:
The function modify_list adds the value 5 to the list parameter list.
We pass my_list, which is [1, 2, 3, 4], to the function.
After the function executes, my_list outside the function has been modified to [1, 2, 3, 4, 5].
Since lists are mutable, Python passes my_list by reference, meaning the function operates on the original list. Any modifications to list within the function also apply to my_list.

Note that an alternative approach to using parameters for a subroutine to access a variable defined outside the subroutine is to use a global variable though this is often a less desirable option.

Take the Quiz! (open full screen)


MS-DOS Emulator

MS-DOS (Microsoft Disk Operating System) is an early operating system developed by Microsoft in the early 1980s. It was widely used on IBM-compatible personal computers and is known for its command-line interface, where users type commands to perform tasks rather than using a graphical interface. MS-DOS was foundational in the development of later Windows systems and provided basic functions for file management, program execution, and device control.


Functions of an Operating System

An Operating System (OS) is an essential system software needed to manage a computer’s hardware and software resources.

The main functions of an operating system (OS) include:

  • Process Management & Multitasking: Controls and manages tasks and processes, allocating resources and CPU time to each one, and for some OS such as Windows or MacOs enabling the processing of several applications at the same time (multi-tasking).
  • Memory Management: Allocates and manages computer memory for applications and system processes.
  • File System Management: Provides a structure for data storage, allowing users to save, retrieve, and manage files using folders and sub-folders.
  • Peripheral Management: Manages hardware devices such as printers, disk drives, and input/output devices.
  • User Interface: Provides an interface (mostly graphical or command-line) for users to interact with the system and run applications.
  • User Management: Protects system data and resources from unauthorised access, ensuring system integrity. Maintains user accounts and access levels.

MS-DOS Task


The purpose of this task is to create a folder structure using the command line interface of MS-DOS. By completing this task we will focus on two of the main functions of an operating system:

  • File Management: To create your folder structure, you will create and navigate through a set of folders and sub-folders.
  • User Interface: Your will create your folder structure using a set of MS-DOS commands using a command line interface (CLI): A text-based interface where the user type instructions on a command prompt. In the early days all Operating Systems where based on a command line interface. These were progressively replaced by Operating Systems such as Windows that are based on a Graphical User Interface (GUI) where user can view their folder structure in a window, using icons that they can click on and drag and drop within the folder structure making it a lot more intuitive to use the system.

In MS-DOS, the main commands to navigate through and maintain a folder structure are:

DOS Command Purpose
dir To list the content of a directory/folder.
cd foldername To open a directory/folder. This is used to access a subfolder
cd .. To go back to the parent directory/folder
cd / To go back to the root directory/folder (e.g. C: drive)
mkdir foldername To make a new sub-directory/folder.
rename oldname newname To rename a file or a directory/folder.
rmdir foldername To delete a folder/directory.
cls To clear the screen
time To display the current date and time
help /all To display the help screen

MS-DOS Emulator


Use our MS-DOS emulator and the commands listed above to recreate the following folder structure:



Click on the above screenshot to access the online MS-DOS emulator.

Getting Started


Try the following command to help you get started.

First, let’s list the content of the C: Drive (Root) by using the dir instruction:

You can see here a list of all the directories and files within the C drive.

To create the folder called “MyFiles” we will use the following instruction:

You can type the dir command again to check that your folder has been successfully created:

We will then open the MyFiles folder:

We can check the content of this empty folder:

We will then create the Maths subfolder:

We can check the content of the MyFiles folder to see if now contains a new Maths subfolder:

Let’s go back to the parent folder:

It’s also possible to go back to the root folder using:

You can now repeat these steps to recreate the folder structure described above (see above picture).

Spider Web Challenge

For this challenge our aim was to use Python Turtle to draw a spider web on the screen.

Our code will first will the screen in black (Colour code #000000) and create a Python Turtle called spider, with a light grey colour (Colour code #EEEEEE).


#Spider Web Challenge - 101Computing.net/spider-web-challenge
import turtle

window = turtle.Screen()
window.bgcolor("#000000")
spider = turtle.Turtle()
spider.color("#EEEEEE")
spider.speed(0)
spider.pensize(1)

The second part of our code is to draw the 8 main straight threads in a * shape:

for threads in range(8):
   spider.forward(180)
   spider.back(180)
   spider.left(45)

This is what our spider web looks like so far:

To complete our spider web, we now need to draw arc shapes between these main threads. To do so we will use the following function called drawArc() used to draw an arc shape.

def drawArc(radius,startingAngle,angle):
   spider.setheading(startingAngle+90)
   spider.circle(radius,angle) 

Our 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.

We will then have to use an iterative approach to draw all the arcs to make up the spider web.

Here is our full code for this spider web challenge:

Irrational Numbers – Python Challenge

An irrational number is a real number that cannot be expressed as a ratio of integers, in other words you cannot write an irrational number as a fraction p/q where p and q are both integer values.

Two of the most well known irrational numbers are Pi (Π) and the Golden ration (φ).

One of the characteristics of irrational numbers is that their decimal expansion is infinite with no recurring patterns.

Another interesting fact about irrational numbers is that the square root of a prime number is always irrational. So the following numbers are all irrational numbers:

We will base our Python challenge based on this latest fact. Your task is going to write a Python script that:

    Ask the user to enter two positive integer values, a and b.
    List a set of irrational numbers between a and b by listing the square roots of all the prime numbers between a2 and b2.

For instance for a = 4 and b = 7, we will find all the prime numbers between a2 = 16 and b2 = 49 and work out a list of irrational numbers using the square root values of these prime numbers. So √17, √19, √23, √29, √31, √37, √41, √43, √47 are all irrational numbers between 4 and 7. We will display a rounded version of these numbers on screen as it is impossible to display an irrational number with its full decimal expansion.

Note that to help you with this code, we have already created a function called isPrime() that takes a number as a parameter and returns True is this number is a prime number.

def isPrime(number):
   if number > 1:
      for i in range(2, int(number ** 0.5) + 1):
         if number % i == 0:
            return False
      return True
   else:
      return False

Also note that the square root of a number can be calculated by raising this number to the power of half.

Python Code

You can now complete this challenge using the code provided below:

unlock-access

Solution...

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

Storage Units – Bigger or Smaller Quiz

In this challenge we are going to create a quiz using Python to test the end-user’s understanding of storage units used to describe the capacity of a storage device.

Our quiz will consist of 10 “Bigger or Smaller” questions as follows:

To complete this quiz you will need to complete the code provided below to:

    Display a welcome banner with the name of the quiz.
    Generate a random number between 1 and 999 and a random storage unit (Bytes, KB, MG, GB, TB or PB) for the first storage capacity.
    Generate a second random number between 1 and 999 and a second random storage unit for the second storage capacity.
    Display both storage capacities on the screen and ask the user if the first one is bigger or smaller than than the second one.
    Convert both storage capacities in Bytes to work out which capacity is actually bigger.
    Inform the user if their answer is correct or not.
    Repeat the whole process 10 times to create a quiz with 10 different questions.
    Include a scoring system where the suer receives a score out of 10, each correct answer giving the user and extra point.

Python Code

We have started the code below to generate the first storage capacity. Check out how the import library is used to generate a random number between 1 and 999 and to also picks a storage unit at random.

unlock-access

Solution...

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