More results...

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

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

Countdown

countdown_animatedThe aim of this blog post is to create a countdown timer that will display the numbers on screen using a 7-segment display. A lot of electronic devices use this approach to display numbers on a LED or LCD screen. (Watch, alarm clock, calculator etc.)

First we need to investigate how the 7-segment display works. You will find this page quite useful.

Typically 7-segment displays consist of seven individual coloured LED’s (called the segments). Each segment can be turned on or off to create a unique pattern/combination. Each segment is identified using a letter between A to G as follows:

7segments

The following truth table shows which segments need to be on to display the digits from 0 to 9:

Digit A B C D E F G
tmp-0 1 1 1 1 1 1 0
tmp-1 0 1 1 0 0 0 0
tmp-2 1 1 0 1 1 0 1
tmp-3 1 1 1 1 0 0 1
tmp-4 0 1 1 0 0 1 1
tmp-5 1 0 1 1 0 1 1
tmp-6 1 0 1 1 1 1 1
tmp-7 1 1 1 0 0 0 0
tmp-8 1 1 1 1 1 1 1
tmp-9 1 1 1 1 0 1 1

Your Challenge

The code below is used to display a countdown timer counting from 5 to 0 and using the 7-segment approach to display the numbers.

Your challenge consists of using the truth table given in this post to start your countdown from 9 (instead of 5).

Challenge #2:


With 7 segments there are 128 possible symbols. Some can be used to represent letters. For instance:

tmp-10tmp-11tmp-12tmp-13tmp-14tmp-15

Tweak the code above to write a message using the 7-segment display.

Start with the following message “Hello” (HELLO)

Morse Code Encoder

The aim of this challenge is to create a Morse code converter that lets the user enter any message. The program should then display the message in Morse code. To complete this challenge you will need to know how Morse code works. If the information given below is not clear enough you can find out more about Morse code on this wikipedia page.

Morse code is a method of transmitting text information as a series of on-off tones, lights, or clicks that can be directly understood by a skilled listener or observer without special equipment.

Each character (letter or numeral) is represented by a unique sequence of dots and dashes. The duration of a dash is three times the duration of a dot.

For this challenge we will be using the international Morse code as follows:
Morse_code

Learning Objectives


By completing this challenge we are going to learn about Python dictionaries.
In Python, a dictionary consists of pairs (called items) of keys and their corresponding values.

Python dictionaries are also known as associative arrays or hash tables. The general syntax of a dictionary is as follows:
PythonDictionary

myDictionary = {"Red": "#FF0000", "Green": "#00FF00", "Blue": "#0000FF"}
print("The colour code for Green is:")
print(myDictionary["Green"])

btnTryCodeOnline

Morse Code Encoder


Check the code below to encore your own message into Morse code:

Challenge #1:


Complete the code above to add the Morse code for number digits between 0 and 9 as follows:
Morse_code_numbers

Challenge #2: Morse Code Decoder


Write a program that enables you to decode a message written in Morse code. For instance, your program should be able to decode the following message:
… — … -.-. –.- -.. – .. – .- -. .. -.-. .– . .- .-. . … .. -. -.- .. -. –. ..-. .- … –

Challenge #3: Sending Light Signals


Morse_code_signalsCheck the following code used to simulate a lamp going on and off to reproduce an SOS call in Morse code: … — …

Combine this code with the code from the Morse code encoder to create light signals in Morse code. Remember the rules of Morse code:

  • Each character (letter or numeral) is represented by a unique sequence of dots and dashes.
  • The duration of a dash is three times the duration of a dot.
  • Each dot or dash is followed by a short silence, equal to the dot duration.
  • The letters of a word are separated by a space equal to three dots (one dash).
  • The words are separated by a space equal to seven dots.


unlock-access

Solution...

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

Home Alone – Kevin is not here!

First, let’s watch this short video clip from the movie Home Alone 2.

This video clip highlights a typical case of recursion.

Recursive Functions


A recursive function is a function which calls itself.
To make sure that a recursive function does not loop indefinitely it needs a stopping condition to check if a condition is met: If it is, it should stop calling itself.

In this challenge we are writing a recursive function that asks the person standing next to us to “pass this bag to Kevin”. Each person in the queue forwards this message by calling the same function. However if we reach the end of the queue or if we reach Kevin then we stop asking. So in this case we have two conditions that can stop the recursion: we reach the end of the queue/list or we reach Kevin.

Give this to Kevin: Recursive Function


For more examples based on recursive functions, check this post.

The Gruffalo

This challenge is inspired from Julia Donaldson and Alex Sheffler’s children book: “The Gruffalo”.

In this story a little mouse describes a ferocious animal/monster called a “Gruffalo” to scare other dangerous animals (fox, snake, owl) she encounters while taking a walk in the forest.

This little mouse being very imaginative she uses plenty of frightening adjectives to describe this fictional animal.

In this challenge you are going to write a program that generates a description of a Gruffalo. Each time the program is run, a new description will be generated.

Learning Objectives:


By investigating this challenge you are going to further improve your skills at:

  • Using lists and accessing values of a list randomly,
  • Concatenating strings together to create a longer string.

Remember, in Python, a list is a collection of values. It uses [square brackets].
For instance:

colourList = ["red","blue","yellow","green","magenta"]

To access a random value from this list, you can use the random.choice method.

For instance:

colourList = ["red","blue","yellow","green","magenta"]
randomColour=random.choice(colourList)

Challenge


Complete the code below to describe your gruffalo further:

  • Has he got terrible teeth in his terrible jaws?
  • Has he got a poisonous wart at the end of his nose?
  • Has he got a black tongue and purple prickles all over his back?

Each time you run this code it will create a new description!

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 Twelve Days of Christmas

Christmas“The Twelve Days of Christmas” is an English Christmas carol that enumerates in the manner of a cumulative song a series of increasingly grand gifts given on each of the twelve days of Christmas.

Let’s look at how we could use Python to write the lyrics of a cumulative song.

Learning Objectives


By investigating this program you will understand more how to use lists in Python and how to use loops to iterate through all the values of a list.

Remember, in Python, a list is a collection of values. It uses [square brackets].
For instance:

giftList = ["Teddy Bear","Toy car","Electric Train"]

To find out the number of items in a list we can use the len method.

giftList = ["Teddy Bear","Toy car","Electric Train"]
numberOfGifts = len(giftList)

To iterate through all the items in a list we can use a for loop.

For instance:

giftList = ["Teddy Bear","Toy car","Electric Train"]
numberOfGifts = len(giftList)

print("My Chritmas wish list to Santa:")
for i in range(0,numberOfGifts):
  print(giftList[i])

We can then use string concatenation techniques to add punctuation:

giftList = ["Teddy Bear","Toy car","Electric Train"]
numberOfGifts = len(giftList)

letterToSanta = "Dear Santa,\n\nThis is my wish list for Christmas:\n"
for i in range(0,numberOfGifts):
  letterToSanta += "\n    " + giftList[i] + ","

letterToSanta = letterToSanta[:-1] + "." #Replace last comma with a full stop.
letterToSanta += "\n\nWishing you a Merry Christmas!"

print(letterToSanta)

btnTryCodeOnline

Python Script for The Twelve Days of Christmas:


The code below is used to write the lyrics of this Christmas carol.

Challenge:


Your challenge consists of re-using this script to adapt it to create the lyrics of another cumulative song such as:

Happy New Year!

HappyNewYear_CSS

Learning Objectives

In this challenge you will learn how to format text using CSS including how to:

  • Changing font style,
  • Changing font color,
  • Changing font weight,
  • Changing text to italic,
  • Underlining text.

We will also investigate the use of borders, border radius and background colours as well as padding and margin options.

CSS Box Model

To understand how margin, borders and padding works you need to understand the CSS Box Model. Click on this picture to find out more:CSS-Box-Model

Your Task


Complete the HTML and CSS code below to finalise customising the look & feel of this “Happy New Year!” message.

See the Pen MYevOP by 101 Computing (@101Computing) on CodePen.

Tagged with: ,