More results...

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

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

RGB Converter

rgb-color-code-ballsDid you know that every colour on the screen can be represented using an RGB code (Red, Green, Blue) code. This code consists of three numbers between 0 and 255, indicating how much red, green and blue are used to recreate the colour. For instance the RGB code for:

  • Red is (255,0,0)
  • Green is (0,255,0)
  • Blue is (0,0,255)
  • Yellow is (255,255,0)
  • Orange is (255,165,0)

Graphic designer and software programmer sometimes prefer to use another notation based on hexadecimal RGB code where each of the three decimal values are converted into a two-digit hexadecimal code, resulting in a 6-digit (3×2) hexadecimal code. For instance:

  • Red is #FF000
  • Green is #00FF00
  • Blue is #0000FF
  • Yellow is #FFFF00
  • Orange is #FFA500

Check the following RGB Color picker to see how RGB codes work:

The aim of this challenge is to write a program to perform decimal RGB to hexadecimal colour codes conversion and vice-versa.

Your 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:

Binary Converter using Python

Did You Know?

Everything that is stored on a computer is stored as binary code. Binary code is made of bits (0 or 1). We often use Bytes to store data. A Byte is made of eight bits and can be used to store any whole number between 0 to 255. Check it yourself, click on the binary digits to create your own binary number:

1286432168421
11111111

128 + 64 + 32 + 16 + 8 + 4 + 2 + 1 = 255


Python Challenge


The purpose of this challenge is to write a Python script to convert a Binary number into denary and vice versa. To do so we will use the concept of binary left and right shifts as explained below.

Binary Left Shift


A binary left shift is used to multiply a binary number by two. It consists of shifting all the binary digit to the left by 1 digit and adding an extra digit at the end with a value of 0.
binary-left-shift

Binary Right Shift


A binary right shift is used to divide a binary number by two. It consists of shifting all the binary digit to the right by 1 digit and adding an extra digit at the beginning (to the left) with a value of 0.
binary-right-shift

Python 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: ,

BBC micro:bit – Hogwarts Sorting Hat

hogwarts-sorting-hatIn the Harry Potter series of novels written by British author J. K. Rowling, The Sorting Hat is a magical hat at Hogwarts that determines which of the four school Houses each new student belongs most to. These four Houses are Gryffindor, Hufflepuff, Ravenclaw, and Slytherin.

In this challenge we are going to write a program for the BBC micro:bit to act as the sorting hat. Whenever a students from Hogwarts school of Witchcraft and Wizardry will shake the BBC micro:bit, a message will appear telling them which house they belong in.

You will need to use the micro:bit website to create the code using the JavaScript Block Editor.

micro-bit-logo

Block Programming


Here is the code to implement the Sorting Hat algorithm:
harry-potter-sorting-hat-BBC-microbit-javascript-code

Resetting the Sorting Hat


Add the following code to reset the Sorting Hat when either button A or button B is pressed:
harry-potter-sorting-hat-reset-code

Tagged with: ,

Password Checker

password-checkerFor this challenge we will write a program where the end-user has to type a password. The program will then return a score to tell the end-user how secure their password is based on the following criteria:

Criteria Score
The password contains lowercase and uppercase characters. +10 pts
The password contains numbers and letters. +10 pts
The password contains at least one punctuation sign. +5 pts
The password is at least 8 characters long. +5 pts

Video Tutorial

Complete the code


We have started the code but have only implemented the first two criteria. Your task is to implement all 4 criteria.

Test Plan


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

Test # Input Values Expected Output Actual Output
#1 Password: mypassword 5 pts
#2 Password: myPassWord 15 pts
#3 Password: myPassWord123 25 pts
#4 Password: #myPa$$Word123 30 pts
#5 Password: ?gB;45#wq2 30 pts
#6 Password: (leave blank) 0 pts

Extension Task


How could you tweak your code to implement the following rules:

Criteria Score
The password contains at least 2 lowercase and at least 2 uppercase characters. +15 pts
The password contains at least 2 numbers: +15 pts
unlock-access

Solution...

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

Happy Birthday!

happy-birthdayFor this challenge we are going to write a Python program which will ask the end-user to enter their date of birth in the following format: dd/mm/yyyy.

The program will then calculate and display the following information:

  • The age of the user,
  • The number of days the user has lived for,
  • The week day (Monday to Sunday) corresponding to their Date of Birth,
  • The number of days left until the user’s next birthday,
  • A “Happy Birthday” message if today is the user’s birthday!

Learning Objectives


By completing this challenge you are learning various techniques to manipulate and format dates. These include formating a date in the dd/mm/yyyy format, retireving today’s date or calculating the difference in days or years between two dates.

Solution



unlock-access

Solution...

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

Days Until Summer

calendar-date-time

Did you know?

Summer starts on the Summer Solstice which, in the Northern hemisphere, is the 21st of June. It ends three months later, on September the 22nd, a date known as known as Autumnal equinox, when the Autumn season starts.

For this challenge you will write a Python script that retrieves today’s date to find out if we are in Summer or not. If not, it will calculate the number of days until next Summer, which could be in the same calendar year or in the following calendar year (in case we have already passed this year Summer season).

To do so we will reuse and adapt the following code used to calculate the number of days until next Christmas. Your task is to analyse how this code works to then make the necessary amendments to:

  • Find out if we are already in the Summer season,
  • if, not find out if this year Summer is already past,
    • if it has, calculate the number of days left till next year Summer,
    • otherwise, calculate the number of days till this year Summer.

Python 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:

Which Season?

which-season-autumn-date-time

Did you know?:


Though we all agree that a calendar year is divided into four seasons, people sometimes disagree on the dates when these seasons start or finish. Many bodies, for example meteorologists, adopt a convention for the purpose of presenting statistics by grouping the twelve months of the year into four three-month seasons, for example March, April and May being taken as Spring.

In this case the seasons could be defined as follows:

From To Season
1st September 30th November Autumn
1st December 28/29th February Winter
1st March 31st May Spring
1st June 31th August Summer

Other scientists and astronomers prefer to define the four seasons based on astronomical events known as the equinoxes and the solstices. The equinoxes occur in March and September when the Sun is ‘edgewise’ to the Earth’s axis of rotation so that everywhere on Earth has twelve hours of daylight and twelve hours of darkness. The solstices occur in June and December when the Earth’s axis is at its extreme tilt towards and away from the Sun so at mid-day it appears at its highest in one hemisphere and at its lowest in the other.

The exact dates for the solstices and equinoxes vary from one year to the other but are around the 21st of the months mentioned above.

From To Season
21st September 20th December Autumn
21st December 20th March Winter
21st March 20th June Spring
21st June 20th September Summer

Your Challenge:


Write a computer program that retrieves today’s date. The program should then display the season for this date based on the astronomical definition of the four seasons.

We have started the code for you but have only worked out the dates for Spring. You can now complete the code to cater for all four seasons.


unlock-access

Solution...

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