More results...

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

Discount Price Calculator

discountShopping during the sales can sometimes be very confusing. With discounted prices at 10%, 20%, 50% or even 70%!

For this challenge you are going to write a Python script that prompts the user to enter a price in pounds (or in your own currency) (e.g. £90) and a discount rate to apply (e.g. 20%).

Your program will then calculate and display the discounted price.

Video Tutorial


Python Code


Complete the code provided below:

Testing


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

Test # Input Values Expected Output Actual Output
#1 Price: £100
Discount Rate: 25%
Discount: £25
Discounted Price: £75
#2 Price: £160
Discount Rate: 40%
Discount: £64
Discounted Price: £96
#3 Price: £180
Discount Rate: 10%
Discount: £18
Discounted Price: £162
unlock-access

Solution...

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

Fahrenheit to Celsius Converter

Fahrenheit-CelsiusDegree Fahrenheit (°F) and Degree Celsius (°C) are the main two units to measure temperature.

The Fahrenheit scale is used mainly in the USA whereas other countries tend to use the Celsius scale.

It is possible to convert a temperature from Celsius degrees to Fahrenheit and vice-versa using the following conversion formulas:
fahrenheit_to_celsius_formulas

Your Challenge


Write a Python script to:

  • Ask the end-user whether they want to convert from Fahrenheit to Celsius or from Celsius to Fahrenheit,
  • Ask the user to enter a temperature in the correct unit,
  • Apply the conversion formula and display the temperature in the new unit.

Testing


You can now use your code to complete the following test plan to test your code:

Celsius degrees to Fahrenheit conversions:

Test # Input Values (°C) Expected Output (°F) Actual Output
#1 20 68
#2 -10 14
#3 0 32

Fahrenheit to Celsius degrees conversions:

Test # Input Values (°F) Expected Output (°C) Actual Output
#1 68 20
#2 14 -10
#3 32 0

Challenge #2


On the temperature scale, the 0°C (=32°F is called Freezing Point which is when water starts freezing and becomes ice. At 100°C (=212°F) water starts to boil. This is called Boiling Point.

Adapt your script to write a message to the end user as follows:

  • You are above boiling point for all temperatures above 100°C
  • You have reached boiling point if the temperature is exactly 100°C
  • You are between freezing point and boiling point for all temperatures between 0°C and 100°C
  • You have reached freezing point if the temperature is exactly 0°C
  • You are below freezing point for all temperatures below 0°C
unlock-access

Solution...

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

The legend of the chessboard

chessboardThe story tells us that long long ago the great Sultan of India loved to play games. As he started to get bored of the games that were present at the time he asked a wise man who lived in his kingdom to come up with a new game.

This, according to the legend, is how the game of chess was invented. The Sultan was very pleased with the wise man who had invented the game and in return he offered the wise man a reward of his own choosing.

riceTo the Sultan’s surprise, the wise man did not ask for any gold. Instead he only had one request: He asked just for a few grains of rice in the following manner: the sultan was to put a single grain of rice on the first chess square, two grains on the second square, four on the third square and carry on doubling this number on every consequent square to fill up all 64 squares of the chessboard.

This seemed to the ruler to be a modest request, so he called for his servants to bring the rice. Did the Sultan manage to fulfil the wise man’s request?

Python Code


Your task consists of writing a python script to calculate the total number of grains of rice required to cover the chessboard following’s the wise man’s request.

unlock-access

Solution...

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

Fraction Simplifier

This challenge consists of writing a program that asks the end-user to enter a fraction (numerator and denominator) and output the matching reduced fraction when the fraction can be reduced.

To see what this program should do in action you may want to try fractionsimplifier.com.

fraction_numerator_denominator

To simplify a fraction your program will need to find the greatest common divisor (aka greatest common factor) of the numerator and denominator that will have been entered by the end user. Then, your program will divide the numerator and denominator of the fraction by this number.

fraction

To find out if a number is a factor of the numerator you will need to check that the remainder of the numerator divided by this number is null (=0):

  • For instance 3 is a factor of 24 because 24 mod 3 = 0.
  • remainder_24

  • Whereas 5 is NOT a factor of 32 because 32 mod 5 = 2 != 0.
  • remainder32

Extra tip: A factor of a number is always lower or equal to this number.

Your Challenge:


Complete the code below to find the greatest common factor of both the numerator and denominator entered by the end-user and use it to output the simplified fraction.

unlock-access

Solution...

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

Area Calculator

For this challenge we are going to use a Python script to calculate the area in square meters of two different flats.

To do so we will write a computer program that will add up all the areas of each room.

Most rooms have a rectangle shape. So we will first define a function that takes two parameters: width and length and return the area of the rectangle using the following formula:

area = width * length

Let’s use this formula to calculate the area of this small flat:Flat_0

Your Challenge


Tweak the code above to calculate the area of the following two flats: (Click on each picture to zoom in).
Flat_1

Flat_2

Challenge #2


The area of a right-angled triangle can be calculated as follows:
triangle
area = width * length / 2

Add a new function called getTriangleArea to return the area of a right-angled triangle using two parameters: width and length.

Use both the getRectangleArea and getTriangleArea functions to calculate the area of this room:
flat_4

Challenge #3:


Use your code to calculate the area of this small mansion (Click on picture to zoom in):
flat_5

unlock-access

Solution...

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

3D Challenge

3DCubeThe aim of this challenge is to draw a cube in 3D and to make it rotate on the screen.

Drawing 3D shapes on a screen (2D) requires some mathematical formulas to convert 3D (x,y,z) coordinates into 2D coordinates (x,y). This conversion, also known as “oblique projection” is based on the following formulas:
oblique-projection-formulae

This is a great application of trigonometry, especially of the SOCATOA formulas!

socatoa

cosine

sine

(Read more about trigonometric formulas.)

A 3D rotation against an axis (X, Y or Z axis) also requires some complex mathematical formulas. To apply a 3D rotation we can use the rotation matrix as follows:
3d-rotation-matrix

Our Solution:


To decide the angle and axis of rotation we use the position of the mouse pointer.
The X coordinate of the mouse pointer becomes the angle of rotation against the Y axis.
The Y coordinate of the mouse pointer becomes the angle of rotation against the X axis.
In this example we did not implement a rotation against the Z axis.

Your Task


3d-houseAdd more edges to the code given above to create a full house including a roof, a front door and a window.
unlock-access

Solution...

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

Mastermind Challenge

mastermind
Have you ever played the board game “Mastermind”?

If you are not too sure about the rules of this game, you should first check this page.

For this challenge we are going to create this game of mastermind where the end-user plays against the computer. The end-user’s role is to guess the choices of 4 colours made by the computer.

Learning Objectives


By completing this game we are using all our coding skills using nested loops and IF statements.

We are also learning about how flowcharts can be used to describe a complex algorithm.

Flowchart


Can you create the flowchart for this computer game yourself?
Give it a try. Once done, compare your flowchart with our flowchart:
Mastermind-Thumbnail
Note that there is often more than one approach to solve a problem.

Code


Use either your flowchart or the one given above and translate it into programming code using Python.

unlock-access

Solution...

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

Python: Reading a text file

Learning Objectives

In this challenge we are going to focus on accessing a text file in Python to read the content of the file line by line.

Challenge

Your first challenge consists of writing a Python script that will read the following text file, one line at a time and display the content of each line on screen.


TextFile
My Playlist.txt

To read the content of a text file line by line we are going to use a for loop that will loop through and extract each line of the text file one at a time. It will stop looping only once the it will have reached the last line.

Check this animation that explains this process:
Reading-Text-File-Animation-s

When the text file uses a CSV format (Comma Separtred Values), each line contains several values separated using a special character, often a comma or a semi-colon. In this case we can use the split() method to extract each value of each line and store them in a list.

Check this animation that explains this process further:
Reading-CSV-File-Animation-s

Solution

The solutions below contains 5 main steps:

  1. Step 1: Open the text file using the open() function. This function takes two parameters: The name of the file (e.g. “playlist.txt”) and the access mode. In our case we are opening the file in read-only mode: “r”.
  2. Read through the file one line at a time using a for loop.
  3. Split the line into an array. This is because in this file each value is separated with a semi-column. By splitting the line we can then easily access each value (field) individually.
  4. Output the content of each field using the print method.
  5. Once the for loop is completed, close the file using the close() method.

 

Main Access Modes when opening a file with the open() function.

Mode Description
r Opens a file in read only mode. This is the default mode.
r+ Opens a file for both reading and writing.
w Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist yet, it will create the new file for writing.
w+ Opens a file for both writing and reading. Overwrites the file if the file exists. If the file does not exist yet, it will create the new file for writing.
a Opens a file for appending. The file pointer is at the end of the file. So new data will be added at the end of the file. If the file does not exist, it creates a new file for writing.
a+ Opens a file for both appending and reading. The file pointer is at the end of the file. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.

Your Challenge


Use what you have learnt in this blogbpost to complete these challenges:
My mp3 playlist(Reading a text file using Python) US Population(Reading a text file using Python)

Python Tip: Validating user input as number (Integer)

In most of your Python programs you will want to interact with the end-user by asking questions and retrieving user inputs.

To do so you can use the input() function: e.g.

username=input("What is your username?")

Sometimes you will need to retrieve numbers. Whole numbers (numbers with no decimal place) are called integers. To use them as integers you will need to convert the user input into an integer using the int() function. e.g.

age=int(input("What is your age?"))

This line of code would work fine as long as the user enters an integer. If, by mistake, they enter letters or punctuation signs, the conversion into an integer will fail and generate an exception (error) and the program would stop running.

To validate the user entry and ensure that is a number it is possible to catch this exception when it occurs using the try…except….else block as follows:

try:
    value=int(input("Type a number:"))
except ValueError:
    print("This is not a whole number.")

See how we can use this approach to define our own function (called inputNumber()) to ask for a number. This new function can then be used instead of an input() function whenever we expect the user to enter a whole number. This function uses the try…except….else block within a while loop so that it keeps asking the user to enter a number till the user gets it right.

Final Code:

def inputNumber(message):
  while True:
    try:
       userInput = int(input(message))       
    except ValueError:
       print("Not an integer! Try again.")
       continue
    else:
       return userInput 
       break 
     

#MAIN PROGRAM STARTS HERE:
age = inputNumber("How old are you?")

My mp3 playlist

Learning Objectives


In this challenge we are going to focus on accessing a text file in Python to:

  • Read the content of the file line by line,
  • Append data at the end of the file,
  • Write into a new text file.

To complete these challenges we recommend you to use Coding Ground which let you code online and use multiple files. You will first need to create a text file to copy the content of the playlist (from the text file given below)

codingground

Challenge #1


Your first challenge consists of writing a Python script that will read the following text file, one line at a time and display the content of each line on screen.


TextFile
My Playlist.txt


As you are willing to complete this challenge we assume that you already have some good Python skills. To learn more about accessing text files in Python, you will first need to do some research on the Internet.

Challenge #2


Your second challenge consists of opening the text file with Python in “write” mode to add the following song at the end of the playlist:

“Happy” by Pharrell Williams – Duration: 3:52

You will need to research the Intenet on how to write at the end of a text file.

Challenge #3


For your third challenge you will edit the playlist so that the song “Happy” by Pharrell Williams appear in third position.

Tagged with: ,
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.