More results...

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

Using text files in Python

file-handling

Learning Objectives


In this post you will learn how to code the main file handling operations to manipulate text files as follows:

  • Opening a file
  • Reading from a text file
  • Reading writing to a text file
  • Appending to a text file
  • Closing a file
Open a fileClose a fileReadWriteAppend to
To open a file use the following code:

file = open("myTextFile.txt","r")

Folder name/File name


When opening a text file you need to specify the filename you want to open. If the file is not stored in the same folder as your Python file, you will also need to specify the location (e.g. subfolder) where the text file is saved. E.g.

file = open("myFolder/myTextFile.txt","r")

Access Mode


When opening the file you have to specify the access mode using one of the following codes:

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.
Once you have finished using your file, make sure that you close this file! It will free up resources and allow other users/processes to access this file if they need to.
Closing a file is extremely easy using the close method.

file.close()
To read a text file, line by line, you will need to:

  1. Open the text file in read mode (either “r” or “r+”),
  2. Loop through the text file, line by line, using a for loop,
  3. Close the text file.

Reading line by line

file = open("myTextFile.txt","r")

for line in file:
  print(line)
  
file.close()

What’s About CSV files?


CSV files (Comma Separated Values) are text files that store data where each record is stored on a line and each field is separated using a comma “,”. Sometimes we use other symbols instead of the comma such as a semi-colon “;” or a pipe “|”.
In this case when reading a line of the text file you can use the split() method to then access each field one by one.

file = open("myTextFile.txt","r")

for line in file:
  data = line.split(";")
  print(data[0] + " - " + data[1] + " - " + data[2])
  
file.close()
To write to a text file you will need to:

  1. Open the text file in read mode: “w”,
  2. Write to the file using the write() method,
  3. Close the text file.

Be careful, when using the write command, you are overwriting the content of your file. If instead of overwriting the content of your file you want to append (write at the end of the file) check the next tab: “Append to a text file”.

Note that when opening the text file, if the file specified does not exist, Python will create a new file automatically.

Writing to a text file

file = open("myTextFile.txt","w")

file.write("Hello World\n");
  
file.close()

The “\n” at the end of the text means “new line”. Only use it if you want the next call to the write() method to start on a new line.

The write method will overwrite the content of your file. If instead you want to write at the end of a text file you can use the “Append access mode”:

To append to a text file you will need to:

  1. Open the text file in append mode: “a”,
  2. Write to the file using the write() method,
  3. Close the text file.

Appending to a text file

file = open("myTextFile.txt","a")

file.write("Hello World\n");
  
file.close()

The “\n” at the end of the text means “new line”. Only use it if you want the next call to the write() method to start on a new line.

Practice makes perfect


Try one of these challenges to put into practice what you have learnt about file handling operations.
Class Register(Handling Text Files) My Mp3 Playlist(Handling Text Files)

London 2012

london-2012

Learning Objectives


In this challenge we are going to investigate methods that can be used to:

  • Read and extract data from a text file,
  • Sort this data in ascending or descending order,
  • Display this sorted data on screen.

Context


We have a text file with the list of the 10 top countries at the London 2012 Olympic Games. (Countries which won the most gold medals). This data is not sorted and is organised as follows:

Name of Country;Number of Gold Medals;Number of Silver Medals;Number of Bronze Medals

You can download this text file:

TextFilecountries.txt

Step by Step


To achieve our goal of reading the text file, sorting its data and displaying it on the screen we will proceed in 5 steps:
5steps

Python Code


Your Challenge


Tweak this code to:

  • Sort this list in ascending order of gold medals
  • Sort this list in alphabetical (ascending) order of name of country
  • Sort this list in descending order of silver medals
  • Sort this list in descending order of bronze medals
  • Sort this list in descending order of total number of medals (Bronze + Silver + Gold medals)

unlock-access

Solution...

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

Batman vs. Python Turtle

For this challenge we are focusing on a set of equations used to draw different sections of the Batman logo:

  • f(x) = 1.5*sqrt((‑abs(abs(x) – 1)) * abs(3 – abs(x))/((abs(x) – 1)*(3 – abs(x)))) * (1+abs(abs(x) – 3)/(abs(x)- 3)) * sqrt(1 – (x/7)^2)+(4.5+0.75 * (abs(x – 0.5)+abs(x+0.5)) – 2.75 * (abs(x-0.75)+abs(x+0.75))) * (1+abs(1 – abs(x))/(1 – abs(x)))
  • g(x) = (‑3)*sqrt(1 -(x/7)^2) * sqrt(abs(abs(x) – 4)/(abs(x)-4))
  • h(x) = abs(x/2) – 0.0913722 * x^2-3+sqrt(1 – (abs(abs(x) – 2) – 1)^2)
  • i(x) = (2.71052+1.5 – 0.5 * abs(x) – 1.35526 * sqrt(4 – (abs(x) – 1)^2)) * sqrt(abs(abs(x) – 1)/(abs(x) – 1))

We will import two Python libraries:

  • math library to use functions such as sqrt() and fabs(),
  • turtle library to draw/plot on the screen using x and y coordinates.

Batman Logo:


Your Challenge


Check the following page for additional maths equations to draw heart shapes. See how you could tweak the code given above to reuse these equations and draw a heart shape on screen.

Tagged with: ,

HTML Code Builder (in Python)

html-tag

Learning Objectives


By completing this challenge you will learn how to use count-controlled loops (for loops). You will include a loop within a loop: This is called nesting.

In this challenge you will also use string concatenation techniques.

Finally you will also learn about the following tags in HTML:

  • <UL>, <LI> tags used to create bullet point lists in HTML,
  • <TABLE>, <TR> and <TD> tags used to create tables in HTML.

Bullet Point Lists in HTML


In HTML you can create bullet point lists to display information on the page as follows:
  • First bullet point,
  • Second bullet point,
  • and so on…

To do so you need to use both a <UL> tag to open and close the list and a <LI> tag for each bullet point within the list.
Here is HTML the code:

<UL>
	<LI>First bullet point,</LI>
	<LI>Second bullet point,</LI>
	<LI>and so on...</LI>
</UL>

Using Python we have written a script that prompts the user to enter the number of bullet points they need. In return the script produces the HTML code for the user to copy and paste to their webpage.

HTML Tables


From time to time, when building a webpage in HTML you need to present your data using a table.

A table (<TABLE>) is made of rows (<TR>). Each row is made of data cells (<TD>).

So for instance a 3×2 table contains 3 rows and each row contains 2 data cells. The HTML code of such a table is as follows:

HTML-Table

This is the full code in HTML:

<TABLE>
	<TR>
		<TD> ... </TD>
		<TD> ... </TD>
	</TR>
	<TR>
		<TD> ... </TD>
		<TD> ... </TD>
	</TR>
	<TR>
		<TD> ... </TD>
		<TD> ... </TD>
	</TR>
</TABLE>

Check this other example of table from w3schools.

Your Challenge


Write a python script (or reuse the script above) to prompt the user to enter the number of rows and the number of columns they need for their table. The program should then generate the HTML code for the required table.

Extension Task:


Check how this online HTML Table Code Generator works.

Update your code to ask for additional settings such as:

  • Table width,
  • Table alignment,
  • Cell padding,
  • Background Colour,
  • Border thickness and colour,
  • etc…

Your program should then generate the HTML code for the table, including the given parameters using HTML or CSS attributes.

unlock-access

Solution...

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

Calculating Pi using a Python script

Did you know?


Pi (π) is one of the most important and fascinating numbers in mathematics. Roughly 3.14, it is a constant that is used to calculate the circumference of a circle from that circle’s radius or diameter. Pi is also an irrational number, which means that it can be calculated to an infinite number of decimal places without ever slipping into a repeating pattern. This makes it difficult, but not impossible, to calculate precisely.

How to calculate Pi?


Method #1


All we need to calculate Pi is a round object such as a golf ball and a tape measurer.
We will need to take two measurements as follows:

  • Diameter,
  • Circumference

Knowing that Circumference = π x Diameter we can calculate π as follows: π = Circumference / Diameter.
pi-calculation-method-1
As you may have noticed, this method does not give you the exact value of Pi. This due to the fact that the measurements of the diameter and of the circumference of an object are never 100% accurate.

Challenge #1


Your challenge consists of writing a Python script that prompts the end-user to enter both the diameter and the circumference of a round object. Your program should return the corresponding estimation of π by using the formula from method #1: π = Circumference / Diameter.

You can try your algorithm with the following measurements:
pi-calculation-method-1-earth

Method #2: Calculating Pi Using an Infinite Series (Gregory-Leibniz series)


Mathematicians have found several different mathematical series that, if carried out infinitely, will accurately calculate Pi to a great number of decimal places. Some of these are so complex they require supercomputers to process them. One of the simplest, however, is the Gregory-Leibniz series. Though not very efficient, it will get closer and closer to Pi with every iteration, accurately producing Pi to five decimal places with 500,000 iterations. Here is the formula to apply:
pi-calculation-method-2

Challenge #2


Write a Python script that will calculate Pi with at least three accurate decimal places using the Gregory-Leibniz series.
Tip: You will need to use a for loop and decide of a number of iteration for your algorithm.

Method #3: Calculating Pi Using an Infinite Series (Nilakantha series)


The Nilakantha series is another infinite series to calculate Pi that is fairly easy to understand. While somewhat more complicated, it converges on Pi much quicker than the Gregory-Leibniz formula. Here is the formula to apply:
pi-calculation-method-3

Challenge #3


Write a Python script that will calculate Pi with at least three accurate decimal places using the Nilakantha series.

Help?


Our flowcharts can help you complete these three challenges.
unlock-access

Solution...

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

Word Score Challenge

word-score

Did you know?


The ASCII code (Pronounced ask-ee) is a code for representing English characters as numbers, with each character assigned a number from 0 to 127. For example, the ASCII code for uppercase M is 77. The extended ASCII contains 256 characters (using numbers from 0 to 255).

To see a list of the most useful ASCII codes you can download our simplified ASCII helpsheet.

Using Python you can easily access ASCII values of a character using the ord() function. For instance ord(“M”) returns 77 and chr(77) returns “M”

Your Challenge

Write a Pyhon script that prompts the end-user to enter a word, e.g. “Hello”
The script should calculate the score of this word using the letter values (A=1, B=2, C=3…)

So if the use inputs the word “Hello” the script should output: 8 + 5 + 12 + 12 + 15 = 52%.

Solution


Hide SolutionView SolutionExtended Solution
This solution uses a for loop to access each letter of the word one letter at a time.
Using the ord() function it returns the ASCII code for the letter.
The ASCII code for A is 65, for B is 66 and so on. So by taking away 64 to the ASCII code we then get A=1, B=2, C=3 etc.

word = input("Type a word").upper()
wordScore=0

for letter in word:
  letterValue=ord(letter) - 64
  wordScore += letterValue
  
print(str(wordScore) + "%")
This solution is exactly the same as the previous one but displays the full formula to calculate the score e.g. “8 + 5 + 12 + 12 + 15 = 52%”. This formula is stored as a string in a variable called addition.

word = input("Type a word").upper()
wordScore=0
addition=""

for letter in word:
  letterValue=ord(letter) - 64
  if (addition==""):
    addition = str(letterValue)
  else:
    addition = addition + " + " + str(letterValue)
  wordScore += letterValue
  
print(addition + " = " + str(wordScore) + "%")
unlock-access

Solution...

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

Name the colour

paint-bucketsComputer programmers, web-designers, graphic designers often have to choose specific colours to design eye-catchy user interfaces. To do so they use colour codes which are used to uniquely identify each of the 16 million colours available on the RGB colour palette.

Some of the colours from this palette however have names such as red, white, blue, cyan, magenta, brown, yellow, etc.

For this challenge we are going to write a program that asks the user to type the name of colour and returns its matching colour code.

Let’s look at the code

Let’s test this code

Your task is to complete the following test plan to see if your program works as expected:

Test # Purpose Input Value Expected Output Actual Output
#1 Test to see if the program finds a colour that exists. Cyan #00FFFF
#2 Test to see if the program finds a colour that exists. Purple #8E35EF
#3 Test to see if the program displays a meaningful message if it cannot find the colour. rainbow “We cannot find your colour”
#4 Test to see if the program displays a meaningful message if the user did not enter any colour name (leave blank) “Make sure you type the name of a colour.”
#5 Test to see if the program still works without being affected by the case of the input value. pUrPLE #8E35EF

Fixing Bugs


While testing you may have noticed that test #4 did not produce the expected output.

Your task is to tweak the code to make sure it validates the user input. If the user did not type anything when asked to enter the name of the colour you will display a message saying: “Make sure you type the name of a colour.”

Final Testing


Now that you have fixed this issue, you are going to test it to see if you get the expected outcome.

Test # Purpose Input Value Expected Output Actual Output
#4 Test to see if the program displays a meaningful message if the user did not enter any colour name (leave blank) “Make sure you type the name of a colour.”

Extension Task:


Can you tweak this code so that if the user types a colour code (beginning with a “#” tag) the program finds the name of this colour.

Make sure you fully test your program!

Tagged with: ,

My thesaurus

thesaurusYour English teacher has asked you to write a description of your favourite imaginary pet. They want you to use plenty of adjectives in your description and suggest that you use a thesaurus to find synonyms to use in your description.

synonym

As a computer scientist, you have decided to write a computer program that will take a description of a pet as an input, lookup for synonyms in a thesaurus and output an alternative description of the pet.

Let’s look at the code

Let’s test this code

Copy the following description and use them with the code provided above. Copy the improved description in the output column.

Pet Input Output
pet-1
pets-2
pets-3
pet-4
Tagged with: ,

HTML Chess Challenge

chessboard2

Learning Objectives


In this challenge you are going to learn how to create and format a table using HTML. You will also learn how to insert special characters (using UNICODE characters) on to a webpage.
First you may want to learn about the three HTML tags used to create a table: <TABLE>,<TR> and <TD>

  • Tables are defined with the <TABLE> tag,
  • Tables are divided into table rows with the <TR> tag,
  • Table rows are divided into table cells with the <TD> tag.

Find out more about HTML tables…

HTML Chess Symbols

SymbolHTML CodeSymbolHTML Code
White King&#9812;White Queen&#9813;
White Rook&#9814;White Bishop&#9815;
White Knight&#9816;White Pawn&#9817;
Black King&#9818;Black Queen&#9819;
Black Rook&#9820;Black Bishop&#9821;
Black Knight&#9822;Black Pawn&#9823;

Challenge


Complete the code below to display a full 8×8 chessboard. (Click “Edit with CodePen” to be able to edit the code)

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

unlock-access

Solution...

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

Where are you calling from?

phone
Have you ever received a phone call from an unrecognised number and wondered who was calling and where is the person calling you located? Did you know that, in the UK, for landline phone numbers (not mobile phones), the first 5 digits of the number are called the area code and gives you in indication of where this phone number originates from.

For instance any phone number starting with 01624 comes from the Isle of Man, whereas a number starting with 01224 comes from Aberdeen.

The aim of this challenge is to write a program that lets the user input a UK based landline phone number. The program will then perform a linear search on a large CSV file containing all of the UK based area codes and their matching locations. This linear search will enable the program to identify the exact location of the given phone number.

Learning Objectives


By completing this challenge you will further improve your file manipulation techniques.

If you cannot remember how to open and read through a text file or CSV check our blog post about “how to access text files using Python”.

Your Challenge


Your challenge consists of writing a program that will:

    Prompt the end-user to enter their telephone number.
    Extract the area code (e.g. first 5 digits) for this number
    Perform a linear search for this area code using the CSV provided file.
    If the location is found, display the location this phone number is linked to.
    If the location is not found, display a message to let the user know the location cannot be identified.

Here is the CSV file our programs will be based on:


TextFile
phonecodes.csv

Complete the Code


Video Tutorial


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 Pass/Fail?
#1 01424000000 Hastings
#2 01223999999 Cambridge
#3 01736123456 Penzance
#4 01401000000 Not found!

Extension #1


If the area code cannot be found in the CSV file it may be because some locations, such as Manchester, only use the first 4 digits (e.g. 0161) as their area code. Adapt your code, so that if an area code cannot be found, the program performs a second linear search, but this time only looking for the first 4 digits of the phone number.

Extension #2

The CSV file also gives you the longitude and latitude coordinates of each area code. These coordinates can be used to calculate the distance between two sets of coordinates on the earth, using the Haversine formula. You could adapt your script to calculate the distance in miles between two UK phone numbers.

To find out more about the Haversine formula you may want to complete this challenge first: UK Postcodes distance calculator.

unlock-access

Solution...

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