More results...

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

Hardware Quiz

computer-hardwareComputers hardware consists of all the components that you will find inside the computer (Motherboard, CPU, RAM, graphic card, sound card, network card, etc.) as well as all the peripherals/devices than you can plug to a computer.

Peripherals are often categorised into three types:

  • Input Devices,
  • Output Devices,
  • Storage Devices.

  • input-output-devices-2

    Input Devices Output Devices Storage Devices
    Mouse
    Keyboard
    Microphone
    Webcam
    Scanner
    Barcode Reader
    Sensors
    Chip & Pin Card Reader
    Magnetic Stripe Card Reader
    Touchpad
    Game Controller
    Joystick
    Screen
    Projector
    Speakers
    Headphones
    Printer
    Actuators
    LED
    Magnetic Hard drive
    SSD Hard drive
    USB Key
    CD Drive
    DVD Drive
    SD Card Reader

    input-output-devices-1

    Coding Challenge #1


    Your challenge consists of creating a quiz that will randomly pick and display a peripheral and ask the end-user to decide whether the device is an input device, storage device or output device.

    The user should score 10 points per correct answer. The game should carry on as long as the user is giving a correct answer.

    Video Tutorial


    Coding Challenge #2: The odd one out


    Adapt your quiz so that it displays 4 devices on screen: 3 devices from the same category (e.g. 3 input devices) and 1 device from another category (e.g. storage device). All 4 devices should be displayed in a random order.

    The user is then asked to identify the “odd one out”. The user should score 10 points per correct answer. The game should carry on as long as the user is giving a correct answer.

    e.g. Which device is the odd one out?

    mouse, webcam, printer, keyboard

    unlock-access

    Solution...

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

Sorting Algorithms

Computers are often used to process large amounts of data. Some of the tasks they can be used for is to sort data sets in order, e.g. numerical order or alphabetical order.

Though this may seem like a simple task to complete, a lot of research has focused on finding the most effective approach to sort a list very effectively.

Different solutions have been developed resulting on a range of sorting algorithms, the most popular once being:

  • Bubble Sort Algorithm,
  • Insertion Sort Algorithm,
  • Selection Sort Algorithm,
  • Merge Sort Algorithm,
  • Quick Sort Algorithm.

The effectiveness of an algorithm results in the number of steps it takes to complete a task.

For sorting algorithms, the effectiveness of an algorithm is not just based on the algorithm itself but also on the list of data to be sorted. Some algorithms for instance will be more effective than other on small lists but not on large lists. Some algorithms will be more effective than others if the data is already nearly sorted. Some algorithms such as the merge sort algorithm will be more effective in a concurrent-processing environment as they use a divide and conquer approach.

The following animations are a visual representation of six of the key sorting algorithms:

Tagged with:

Tally Marks Counter

tally-marksTally marks are a form of numeral system used for counting. They are most useful in counting or tallying ongoing results, such as the score in a game or sport, as no intermediate results need to be erased or discarded.

For this challenge you will write a Python script that:

  1. Asks the user to enter a number,
  2. Converts the user input to an integer,
  3. Translates this number into tally marks,
  4. Displays the tally marks on screen.

Note that, as we will be using a text-based output, we will use the following text to represent the tally marks:

1 2 3 4 5 6 7 …
| || ||| |||| ||||- ||||-   | ||||-   || …

DIV & MOD


In Python, the // operator and the % operator can be used to calculate the quotient (a.k.a. DIV) and the remainder (a.k.a. MOD) of a division. For instance:

  • Quotient: 14 DIV 5 = 14 // 5 = 2
  • Remainder: 14 MOD 5 = 14 % 5 = 4

In other words: 14 = 5 * 2 + 4

We will use these operators to find out how many blocks of 5 tallies we need to print and how many tallies are remaining.

Tally Marks Counter – Solved


Your Task


Use a similar approach to:

  1. Ask the user to type a number of hours and convert this into days and hours knowing that there are 24 hours in a day. So for instance: 54 hours should be displayed as 2 days and 6 hours.
  2. Ask the user to type a number of days and convert this into years and days assuming that there are 365 days in a year. So for instance: 892 days should be displayed as 2 years and 162 days.
  3. Ask the user to type a number of seconds and convert this into hours, minutes and seconds knowing that there are 60 minutes in an hour and 60 seconds in a minute. So for instance: 8500 seconds should be displayed as 2 hours and 21 minutes and 40 seconds.
unlock-access

Solution...

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

Hangman Game

hangman-codeFor this challenge, you are going to create a game of hangman. The computer will pick a word randomly within a given list of words. The player will have to guess the word by suggesting one letter at a time and the computer will automatically check if the letter given is included in the word to guess. If not it will add one element to the hanged stick man drawing.

Complete the Code


We have started the code for you, but you will need to complete this code:

Step 1: Display the word replacing “_” with letters that have been guessed correctly. You can use the following flowchart to help you with this step:

Step 2: Display the hangman based on the number of lives remaining.
Step 3: Use a loop to repeat the above steps. The game should stop when the user guessed the words or when they have lost all their lives.

unlock-access

Solution...

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

Bowling Scoreboard

10-pin-bowlingThe aim of this challenge is to create a scoreboard for a game of ten-pin bowling. It will be used to automatically calculate the total score of a player as they progress through the ten rounds of the game.

The scoring system in a game of ten-pin bowling is fairly complex to understand. Check the link provided below to fully understand the scoring system before attempting to complete this challenge:

Ten-pin Bowling – Scoring System:
https://en.wikipedia.org/wiki/Ten-pin_bowling#Scoring

World Bowling Scoring

The World Bowling scoring system—described as “current frame scoring”—awards points as follows:

  • strike: 30 (regardless of ensuing rolls’ results)
  • spare: 10 plus pinfall on first roll of the current frame
  • open: total pinfall for current frame

The maximum score is 300.

World Bowling scoring is an easier scoring system as the traditional scoring system described below. It is thought to make bowling easier to follow than with traditional scoring, increase television viewership, and help bowling to become an Olympic sport.

Traditional Scoring

In general, one point is scored for each pin that is knocked over. So if a player bowls over three pins with the first shot, then six with the second, the player would receive a total of nine points for that frame. If a player knocks down nine pins with the first shot, but misses with the second, the player would also score nine. When a player fails to knock down all ten pins after their second ball it is known as an open frame.

In the event that all ten pins are knocked over by a player in a single frame, bonuses are awarded.

BowlingstrikeA ten-pin bowling scoresheet showing how a strike is scored
  • Strike: When all ten pins are knocked down with the first ball (called a strike and typically rendered as an “X” on a scoresheet), a player is award ten points, plus a bonus of whatever is scored with the next two balls. In this way, the points scored for the two balls after the strike are counted twice.
Frame 1, ball 1: 10 pins (strike)
Frame 2, ball 1: 3 pins
Frame 2, ball 2: 6 pins
The total score from these throws is:

  • Frame one: 10 + (3 + 6) = 19
  • Frame two: 3 + 6 = 9
TOTAL = 28

Two consecutive strikes are referred to as a “bakfast”. Some locations still call it a “Hambone” even though that term has been changed to mean 4 strikes in a row by announcers on television. (Four strikes in a row is also referred to as a “Llama.”)

A double’s pinfall is:

Frame 1, ball 1: 10 pins (Strike)
Frame 2, ball 1: 10 pins (Strike)
Frame 3, ball 1: 9 pins
Frame 3, ball 2: 0 pins (recorded as a dash ‘-‘ or ‘0’ on the scoresheet)

The total score from these throws is:
Frame one: 10 + (10 + 9) = 29
Frame two: 10 + (9 + 0) = 19
Frame three: 9 + 0 = 9

TOTAL = 57

Three strikes bowled consecutively are known as a “turkey” or “triple”.

A turkey’s pinfall is:

Frame 1, ball 1: 10 pins (Strike)
Frame 2, ball 1: 10 pins (Strike)
Frame 3, ball 1: 10 pins (Strike)
Frame 4, ball 1: 0 pins (Gutterball)
Frame 4, ball 2: 9 pins

The total score from these throws is:
Frame one: 10 + (10 + 10) = 30
Frame two: 10 + (10 + 0) = 20
Frame three: 10 + (0 + 9) = 19
Frame four: 0 + 9 = 9

TOTAL = 78

Longer strings of strikes are called by various names, including “-Bagger” (Four Bagger), “Llama” (Four consecutive), and “-Pack” (Six Pack) depending on local use, equipment, and exposure to the sport. Recently, the event of bowling four consecutive strikes has also been called a “hambone”.Six strikes and nine strikes in a row can also be referred to “Wild Turkeys” and “Golden Turkeys” respectively. Any string of strikes starting in the first frame or ending “off the sheet” (where all of a bowler’s shots from a certain frame to the end of the game strike) are often referred to as the “front” or “back” strikes, respectively (e.g., the “front nine” for strikes in frames 1–9, or the “back six” for strikes in frames 7, 8, and 9 with a turkey in the tenth). A “perfect game” or 12 strikes in a row is also rarely referred to as the “Thanksgiving Turkey”. A “Clean Game” is a game with strikes or spares in every frame (not counting bonus balls).

A small number of bowling fans have recognized that naming each strike in a consistent manner adds to the enjoyment and excitement of the game. Based on this, a growing number of bowlers subscribe to the “Duck, Duck, Turkey” method of titling consecutive strikes. In keeping with the tradition that the third consecutive strike is called a “Turkey,” every third strike references turkeys and all strikes under this method have been named after birds as follows: Strike 1 – Duck; Strike 2 – Duck; Strike 3 – Turkey; Strike 4 – Goose; Strike 5 – Chicken; Strike 6 – Turducken; Strike 7 – Penguin; Strike 8 – Flamingo; Strike 9 – Turkey Vulture; Strike 10 – Woodpecker; Strike 11 – Eagle; Strike 12 – Turkey Hawk.

A player who scores multiple strikes in succession would score like so:

Frame 1, ball 1: 10 pins (strike)
Frame 2, ball 1: 10 pins (strike)
Frame 3, ball 1: 4 pins
Frame 3, ball 2: 2 pins
The score from these throws are:

  • Frame one: 10 + (10 + 4) = 24
  • Frame two: 10 + (4 + 2) = 16
  • Frame three: 4 + 2 = 6
TOTAL = 46
The most points that can be scored in a single frame is 30 points (10 for the original strike, plus strikes in the two subsequent frames).
A player who bowls a strike in the tenth (final) frame is awarded two extra balls so as to allow the awarding of bonus points. If both these balls also result in strikes, a total of 30 points (10 + 10 + 10) is awarded for the frame. Some people call it “striking out”, since three strikes in baseball equals an out.
BowlingspareA ten-pin bowling scoresheet showing how a spare is scored
  • Spare: A “spare” is awarded when no pins are left standing after the second ball of a frame; i.e., a player uses both balls of a frame to clear all ten pins. A player achieving a spare is awarded ten points, plus a bonus of whatever is scored with the next ball (only the first ball is counted). It is typically rendered as a slash on scoresheets in place of the second pin count for a frame.
Example:

Frame 1, ball 1: 7 pins
Frame 1, ball 2: 3 pins (spare)
Frame 2, ball 1: 4 pins
Frame 2, ball 2: 2 pins
The total score from these throws is:

  • Frame one: 7 + 3 + 4 (bonus) = 14
  • Frame two: 4 + 2 = 6
TOTAL = 20

A player who bowls a spare in the tenth (final) frame is awarded one extra ball to allow for the bonus points.

unlock-access

Solution...

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

Guess the Number: Binary Search

guess-the-number-quizBefore attempting this challenge, make sure you have completed our previous Guess the Number challenge first where the player plays against the computer.

In this version, the player will be asked to enter a number between 1 and 100. The computer will then use a binary search algorithm to try to guess the correct number keeping the number of guesses to a minimum.

The binary search is a very effective algorithm to search through a large list that is already sorted, in our case the list of numbers from 1 to 100. It is based on the following flowchart:
binary-search-algorithm

Complete the Code


unlock-access

Solution...

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

Roman Numerals Conversion

roman-numeralsFor this challenge, your aim is to write a program used to convert whole numbers (integer) into roman numerals and vice versa.

Roman Numerals are based on seven symbols:

Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1,000

Complete the code


Test Plan

Test # Input Values Expected Output Actual Output
#1 8 VIII
#2 75 LXXV
#3 2017 MMXVII
#4 CI 101
#5 MMXVII 2017
#6 MCMXLV 1945
unlock-access

Solution...

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

Leaderboard

leaderboard-mario

Before completing this challenge you will need to make sure you have already completed a game or a quiz in Python with a scoring system.

You will then add a leaderboard functionality to your existing game or quiz in order to:

  • Store the player score at the end of the game,
  • Add an option for the player to view the leaderboard showing the ten highest scores sorted in descending order.

For this challenge you will create a leaderboard using a text file. The leaderboard.txt file will use the following format:

player_name;score;

You can download this example file:

TextFileleaderboard.txt

In order to complete this challenge you can read more about file handling techniques using Python, including how to append data at the end of a text file and how to read and extract data from a text file.

Storing New Scores

Our first step, is to store a new leaderboard entry at the end of the text file. This could would be needed once the player has completed the game/quiz.

The following code would be used to append the username and the score at the end of the leaderboard.txt file.

import random
username = input("Enter username:")
score = random.randint(0,2000) #Here we don't have a game or a quiz, so let's generate a random score instead.

file = open("leaderboard.txt","a")  
file.write(username + ";"+str(score)+";"+"\n")  
file.close()  

Reading, Sorting and Displaying the Leaderboard

Before displaying the leaderboard on screen, we need to sort it in descending order of scores (highest to lowest). To do so we will first extract all the entries from the leaderboard.txt file and store these into a list using the following code:

file = open("leaderboard.txt","r")  
#Prepare the list (empty list to start with)  
scores = []  
  
#Read through the text file line by line  
for eachLine in file:  
   #Extract the data from the text file  
   splitData=eachLine.split(";")  
   if len(splitData)==3:  
      username = splitData[0]  
      userscore = int(splitData[1])  
      #Append this data to the list of scores  
      scores.append([username,userscore])  
  
file.close()  

Now that we have loaded all the entries from the leaderboard.txt file into a list called scores, we can sort this list in descending order of scores, using the following code:

#Sort the list of scores in DESCENDING order  
sortedScores = sorted(scores,key=lambda sort: sort[1], reverse=True)  

To only keep the top 10 scores we will slice the sorted list to the top 10 scores.

#only keep the top 10 scores:  
del sortedScores[10:] 

The final step is to display these 10 top scores on screen:

#Output top 10 scores  
for score in sortedScores:  
   print(score[0] + ": " + str(score[1])) 

Python Code

Let’s test this code. To make our program easier to read we have used the code provided below to create our own functions storeScore() to append a new score to the leaderboard file and displayLeaderboard() to extract data from the learberoard.txt file, sort all entries in descending order of score, and display the top 10 scores.

unlock-access

Solution...

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

Boarding Pass Validation

Boarding-Pass-Validation

Scenario


You are writing a computer program for an airline company. The program will be used at a check-in desk to generate and print custom boarding passes.

The program captures several user inputs before generating the pass.

In order to make your program more robust, you decide to implement validation routines so that any invalid input is detected and automatically rejected by the program.

Your task is to complete the code below to implement the following validation checks:

  1. The firstname and lastname of the passenger cannot be left blank,
  2. The airport codes (departure and arrival) have to be exactly 3 characters long,
  3. The airport codes (departure and arrival) should be automatically converted to UPPERCASE,
  4. The program should ask whether or not a QR code will be printed on the boarding pass. Only a “Yes” or a “No” answer should be accepted,
  5. The gate number has to be based on the following format: 1 uppercase letter + 2-digit number,
  6. The flight number has to be based on the following format: 2 uppercase letters + 4-digit number,
  7. The departure and arrival times must be in the 12:60 AM/PM format,
  8. The date must be in the DD/MM/YYYY format.

Validation Techniques


String CasePresence CheckInteger OnlyRange CheckLookup CheckCharacter CheckLength CheckTry again!
In Python you can change the case of a sting using .lower(), .upper() and .title() method.

e.g. To retrieve a username in lower case:

username = input("Enter your username:").lower() 

e.g. To retrieve a last name in title case:

lastname = input("Enter your last name:").title() 

e.g. To retrieve a postcode in upper case:

postcode = input("Enter your postcode:").upper() 

You can also remove all leading and tailing space from a user input you can use the .strip() method.

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

Input Validation: Presence Check

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

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

Input Validation: Type Check – Integer?

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

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

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

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

Input Validation: Character Check

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

password = input("Type a password:")

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

Try Again! Using a While Loop:

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.

Complete the code



unlock-access

Solution...

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

Arithmetic Quiz

arithmetic-quiz-calculatorFor this challenge we will create a maths quiz consisting of ten arithmetic questions. Each question will be randomly generated using two random operands between 1 and 12 and one random operator, either + (addition), – (subtraction) or x (multiplication). We will not include the division operator as this could result in a decimal value.

We will include a scoring system to our quiz. The player will be asked one question at a time and score 10 points per correct answer and lose 5 points per incorrect answer.

Complete the code


We have started with just a few lines to generate a random question.
Your task is to add some code to:

  1. Calculate the correct answer,
  2. Compare the user answer with the correct answer to see if the user is correct or not,
  3. Add 10 points for a correct answer or subtract 5 points for an incorrect answer,
  4. Use a loop to repeat this code 10 times,
  5. Display the final score, out of 100.

Extension Task


Why not add a leaderboard to your quiz. This would be used to store the player’s scores and display the top ten scores on screen, in descending order.
unlock-access

Solution...

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

This website will store some information about your preferences on your own computer inside a tiny file called a cookie. A cookie is a small piece of data that a website asks your browser to store on your computer or mobile device. The cookie allows the website to remember your actions or preferences over time.

You can delete all cookies that are already on your computer, and you can set most browsers to prevent them from being placed. However, if you do this, you may have to manually adjust some preferences every time you visit a site, and some services and functionalities may not work.

Most browsers support cookies, but you can set your browser to decline them and can delete them whenever you like. You can find instructions here for how you can do that on various browsers.

This website uses cookies to:

  1. Identify you as a returning user and to count your visits in traffic statistics analysis
  2. Remember your custom display preferences (such as light/dark theme option)
  3. Provide other usability features, including tracking whether you have already given your consent to cookies

Enabling cookies is not strictly necessary for the website to work but it will provide you with a better browsing experience.

The cookie-related information is not used to identify you personally and is not used for any purpose other than those described here.

There may also be other types of cookies created after you have visited this website. This site uses Google Analytics, a popular web analytics service that uses cookies to help to analyse how users use the site. The information generated by the cookie about your use of this website (including your IP address) will be transmitted to and stored by Google on servers in the United States. Google will use this information for the purpose of evaluating your use of other website, compiling reports on website activity, and providing other services relating to website activity and internet usage. Google may also transfer this information to third parties where required to do so by law, or where such third parties process the information on Google’s behalf. Google undertakes not to associate your IP address with any other data held by Google.