More results...

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

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

Endurance Shipwreck Search Expedition

The story of the Endurance shipwreck is one of the most remarkable survival tales in the history of exploration, highlighting the endurance and courage of Ernest Shackleton and his crew during their expedition in the early 20th century.

In 1914, Sir Ernest Shackleton, set out on the Imperial Trans-Antarctic Expedition, aiming to be the first to cross Antarctica from sea to sea via the South Pole. The Endurance, a sturdy, three-masted ship, left England in August 1914, just as World War I was beginning. After a long voyage through the icy seas, the ship reached the Weddell Sea in January 1915, but then disaster struck. The ship became trapped in pack ice in the Weddell Sea before reaching the continent. For ten months, the crew lived aboard the ice-bound ship until it was crushed and sank in October 1915.

Stranded on the ice, Shackleton and his men camped for months before taking lifeboats to Elephant Island. With no chance of rescue there, Shackleton and five others made an 800-mile journey in a small lifeboat to South Georgia Island, enduring treacherous seas. After reaching the West side of the Island, Shackleton had to cross the island’s mountains on foot to reach a whaling station. From there he organised a rescue mission. Miraculously, all 28 men were saved in August 1916, despite the extreme conditions they faced.

This survival story is a legendary example of leadership, resilience, and human endurance.

The Endurance22 Expedition

In 2022, a team of historians/marine archaeologists, scientists and engineers/technicians went back to the Weddell Sea on board a modern polar research ship, S.A. Agulhas II, with the aim to locate the exact position of the Endurance shipwreck. Their main technology to help them in this mission was a remote controlled Autonomous Underwater Vehicle/Submarine (AUV) used to scan the seabed more than 3,000m below sea level! With only a vague idea of where the shipwreck could be, they spent around 20 days scanning a fairly large area (approx. 125 nautical miles) of the Wedell Sea, only being able to scan a small surface per day.

You can find our more about this expedition on: https://endurance22.org/ and on this BBC article.

Your Challenge

Your challenge is going to help control the remote-controlled submarine (AUV: Autonomous Underwater Vehicle) by programming some instructions to help the AUV scan the ocean floor one step at a time and hopefully locate the Endurance shipwreck.

To do so, you will need to complete the code provided below. This code has already been started for you but is incomplete and does not cover the whole area to be searched today. You can run the code to see which sections of the seabed are already being covered. You will then be able to complete the code further to cover the whole search area.

Extra Challenge:

Once you have found the shipwreck, challenge yourself by tweaking your code to complete the following exploration paths:

unlock-access

Solution...

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

Storage Devices Python Challenge

The aim of this challenge is to create an “Odd One Out” quiz on storage devices using Python. But let’s first revisit the main technologies used by storage devices in a computer system.

We can categorise all the storage devices found within a computer system into three main categories based on the technology they rely on to store binary data:

Magnetic Storage Devices


Magnetic storage devices such as magnetic tapes, floppy disks, and hard disk drives (HDD). A hard drive contains a spinning disk coated with a magnetic material. A read/write head moves over the disk, changing the magnetic properties to store data. Magnetic tapes work similarly, but data is stored in a linear format on a magnetic ribbon (tape).

Optical Storage Devices


Optical storage devices such as CDs, DVDs and Blu-ray disks. With this technology, data is stored on the disc as tiny pits (dents) and lands (flat areas). A laser shines onto the surface, and the reflection is interpreted as binary data (1s and 0s) by a computer.

Flash/Solid State Storage Devices


Flash (a.k.a. solid state) storage devices such as USB Keys, SD cards, Micro-SD cards and Solid Sate Drives (SSD). Data is stored in memory chips that can be accessed almost instantly. These chips are made of semiconductors, which can retain data even when the device is powered off.

Python Quiz

For the purpose of this quiz we have stored the information regarding the different storage devices used in a computer system and their technology using three lists in Python:

optical = ["CD","DVD","Blu-ray"]
magnetic = ["Magnetic Tape","Floppy Disk","Hard Disk Drive (HDD)"]
flash = ["USB Key","SD Card","Micro-SD Card","Solid State Drive (SSD)"]

Using Python, you can easily merge two or more lists together using the + operator. e.g. to create a list containing all the storage devices:

allDevices = optical + magnetic + flash

Using the random library you can use two key functions shuffle() and choice():

import random

# Shuffle all the values of a list:
random.shuffle(allDevices)
print(allDevices)

# Pick a random value from a list:
randomDevice = random.choice(allDevices)
print(randomDevice)

Odd One Out Quiz

Your task is to create a 10-question quiz where for each question, the computer will randomly pick 2 storage devices of the same technology (e.g. two optical devices) and one random device from a different technology (e.g. either magnetic or flash). The computer will then display these three devices in a random order and ask the user to identify which of the three device is the odd one out.

For each correct answer the user should score 1 point. At the end of the 10 questions, the user should see their score out of 10.

Python Code

To complete this Python challenge you will need to complete the code below:

unlock-access

Solution...

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

Mountains Elevation Quiz

For this quiz we will use a data set of 10 of the most iconic mountains in the world.

Here is our data set, displayed as a table:

Name Location Elevation
Mount Everest Nepal / Tibet 8,849m
Mount K2 Pakistan / China 8,611m
Mount Aconcagua Argentina 6,959m
Mount McKinley Alaska, USA 6,190m
Mount Kilimanjaro Tanzania 5,895m
Mount Kenya Kenya 5,199m
Mount Blanc France 4,809m
Mount Fuji Japan 3,776m
Mount Etna Italy 3,369m
Ben Nevis Scotland, UK 1,345m

This data set will be stored in a Python program using a 2D array (list of lists) as follows:

mountains = [["Mount Everest","Nepal / Tibet",8849],
             ["Mount K2","Pakistan / China",8611],
             ["Mount Aconcagua","Argentina",6959],
             ["Mount McKinley","Alaska, USA",6190],
             ["Mount Kilimanjaro","Tanzania",5895],
             ["Mount Kenya","Kenya",5199],
             ["Mount Blanc","France",4809],
             ["Mount Fuji","Japan",3776],
             ["Mount Etna","Italy",3369],
             ["Ben Nevis","Scotland, UK",1345]]

Using the random library we can easily pick a random peak from this 2D array and display its name, location and elevation:

import random

number = random.randint(0,len(mountains)-1)
peak = mountains[number]
name = peak[0]
location = peak[1]
elevation = peak[2]
print(">>> Did you know?")
print(name + " is located in " + location + " and rises to " + str(elevation) + " meters." )

Your challenge

Your task is to create a quiz based on this data set. The rules of the quiz are as follows:

     A player starts with a health of 10,000 points and a score of 0.
     The computer randomly selects a peak from the data set and displays the name of the peak and its location.
     It then asks the player to estimate the elevation of the selected peak.
     The computer calculates the difference in meters between the answer given by the player and the real elevation of the peak and deducts this difference from the player’s health score.
     If the player’s health score is positive, then the player’s score goes up by 1 point.
     The quiz repeats itself for as long as the player’s health score remains positive.
     Once the player’s health score reaches zero or a negative value, a game over message is displayed alongside the player’s total score.

Python Code

You can complete your quiz by editing the Python code below:

unlock-access

Solution...

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