Programming Python Workbook (1)
Programming Python Workbook (1)
Programming
for GCSE Computing
*Updated for 2020 OCR Specification
Ken’s Python Book is licensed under CC BY-NC-SA 4.0. To view a copy of this
license, visit: https://creativecommons.org/licenses/by-nc-sa/4.0
Introducti
on
Ken’s Python Book is licensed under CC BY-NC-SA 4.0. To view a copy of this
license, visit: https://creativecommons.org/licenses/by-nc-sa/4.0
Copies of this book, and a web based version are available at:
www.kenspythonbook.co.uk
2
Housekeepi
ng
kenspythonbook.co.uk/housekeeping
3
Content
s
▶ 1. Accuracy 7
▶ 2. Output 8
▶ 3. Variables Part 1 9
▶ 4. Variables Part 2 10
▶ 5. Input 11
▶ 6. Test 1 - Ask And Tell 12
▶ 7. Variable Conversion Part 1 13
▶ 8. Variable Conversion Pt 2 14
▶ 9. Numbers 15
▶ 10. Working With Numbers 16
▶ 11. Test 2 - Volume And Area 17
▶ 12. Comments And Blank Lines 18
▶ 13. Decimal Places 19
▶ 14. Random Numbers 20
4
Content
s
▶ 29. Subroutines 35
▶ 30. Functions 36
5
Starting
Python
▶ Successful Output
6
The IDLE
Interpreter
▶ A very powerful beast. Works magic with numbers. It’s kind of like a
calculator on steroids. Work out what the following operations do by typing
them into the IDLE interpreter shell and hitting ENTER. Try to work out what
each line of code is doing.
2+5
67/34
30*4
4<10
3==6
22-7
23>=5
3!=5
39==39
“hello” + “world”
“hello” * 3
list(range(0,100,2))
len(“hello there”)
Tasks
1. Type the commands into the IDLE interpreter, and make a note of what
each line does
2. Save & label your code
7
1.
Accuracy
▶ If you can’t write code accurately, you’ll have difficulty with programming
▶ Correct spelling and accurate use of other important symbols (brackets,
colons, speech marks) is crucial
▶ Case also matters. Instructions are always in lowercase (highlighted orange
or purple in the code below)
▶ Double and single quotes are interchangeable most of the time. Choose one
or the other and stick to it!
Tasks
1. Type the program above into a new Python window
2. Hit F5 to run it and check it works
3. Print and label your code, explaining any parts you understand
8
1.
Accuracy
9
2.
Output
print(“Hello World”)
print(“Hello\nWorld”)
print(“H\tE\tL\tP”)
print(3+4)
Tasks
1. Create programs to…
a. print your name three times, separated by a space
b. draw Robbie the robot
c. print the number table
2. Save and label your programs
Extension
1. Type the commands into the IDLE interpreter, and make a note of what
each line does
2. Save & label your code
1
0
2.
Output
1
1
3. Variables
Part 1
x = 20
y = 40.5
z = x + y
messageA = “Hello”
messageB = “World”
messageC = messageA + messageB
Tasks
1. Assign some variables using the code above
2. Print out all the variables using the print() function
3. Remember, you don’t need speech marks “” to print variables!
4. Save and label your code
Extension
1. Try setting and combining different variables. What happens when you try
to add text and a number?
12
4. Variables
Part 2
Tasks
1. Copy the code below. What is happening to the message variable?
13
4. Variables
Part 2
5.
Extension
1. Can you multiply a word? What happens if you try?
14
5.
Input
▶ Once you understand variables, you can take input from the keyboard and
store it
▶ All input from the keyboard is stored as a string
▶ The example below asks the user to Enter something and stores the input
in a variable called thing
Tasks
1. Write a program that asks for a name, and prints out the name entered
2. Modify the code to ask for both first name and surname, and print
them out on a single line
3. Add an additional line to print the first name 5 times
4. Save, print and label your code
Extension
1. Type the commands into the IDLE interpreter, and make a note of what
each line does
2. Save & label your code
15
6. Test 1 - Ask And
Tell
Main Task
1. Write a program that will
a. Prompt and ask for name and favourite colour.
b. Return a message like the example shown below (substituting in
the colour entered
Extension
1. Extend your program so it asks for first name and surname separately,
and prints the users full name, as well as their favourite colour
Hints
▶ You will need to use the input function to read in data from the user
▶ You will need suitable variables to store the input
▶ Use a single print statement to output the message
16
7. Variable Conversion
Part 1
Tasks
1. Type in the first example and observe the output. Why is it incorrect?
2. Type in the second example and observe the output. What has changed?
3. Type in the final line to print out the doubled age as part of a sentence
4. Save and label your code
Extension
1. Can you modify the program to ask 2-3 questions, and print them out
as part of a sentence?
17
8. Variable Conversion
Pt 2
a = 3
b = 22.54
print(a)
print(int(a))
print(float(a))
print(str(a))
print(b)
print(int(b))
print(float(b))
print(str(b))
Tasks
1. Type in the code and test that it works
2. Save and label your code
Extension
1. When converting data types, the examples above are only temporary as
they are enclosed within print statements. To permanently change the
data type, reassign the variable as shown below
a = float(a)
18
9.
Numbers
x = 10
y = 10.4
z = "hello"
▶ If you input from the keyboard, the computer will always treat input as a
string. You can save some time by casting (converting) the data type of
variable when you ask for the input
Tasks
1. Type in the code and test that it works
2. Save and label your code
Hints
1. Remember to use str() to convert back when printing if you are adding
strings and numbers. For example:
Extension
1. Use these techniques to ask the user several questions (both string and
number), and print out a short story using the entered values
19
10. Working With
Numbers
Tasks
1. Write a program that asks for the width and height of a rectangle, and
outputs the area
2. Write a program that asks for the radius of a circle, and outputs the area
3. Assume pi (π) is 3.14159
4. The formula to calculate the area of a circle is πr2
5. Save, print and label your code
Extension
1. Can you modify the programs above to calculate the volume of the three
dimensional versions of these shapes? A cuboid and a cylinder.
20
11. Test 2 - Volume And
Area
Main Task
1. Create a program that will:
a. Ask for the radius and height of a cylinder
b. Calculate the volume and surface area
c. Output the values separately
2. Save and label your code
Extension
1. Create a similar program that will:
a. Ask for the length, width and height of a cuboid
b. Calculate the volume and surface area
c. Output the values separately
2. Save and label your code
Hints
▶ Assume the user will enter numbers with decimal points
▶ Create an answer variable to store the result before printing
▶ pi (π) = 3.14159265359
▶ r2 is the same as r*r
21
12. Comments And Blank
Lines
#convert to euros
euros = pounds * 1.2406
#print normally
print(euros)
Tasks
1. Go through some of the examples you have completed so far and add
comments and blank lines, where necessary, to make your code easier to
read
22
13. Decimal
Places
▶ Sometimes, you need to print out numbers with a set number of decimal
places
▶ This method is useful when working with currency values or when you
are dividing numbers that may create answers with many decimal places
#convert to euros
euros = pounds * 1.2406
#print normally
print(euros)
Tasks
1. Enter the code above and test it works
2. Modify the code to print to 2 decimal places
3. Modify the code to print € symbol before the converted amount
4. Save, print and label your code
Extension
1. There is a function that can round numbers called round(). An example
is shown below. Incorporate it into your program
x = 3.566532
print(round(x,4))
23
14. Random
Numbers
▶ Sometimes you need to create random numbers to make ‘lucky dip’ choices
from lists or ranges of numbers
▶ To create a random integer (whole number) you can use the code below:
Tasks
1. Create a program to simulate a lottery draw. It should generate 6
numbers between 1-49 and print them appropriately
2. Run the program multiple times. Why will this program not be suitable
for drawing lottery numbers?
3. Save and label your code
Extension
1. Can you figure out a way of picking six unique numbers for the lottery draw?
24
15. Selection
With IF
#Declare variables
letter = "a"
Tasks
1. Type in the code above and make sure it works
2. Modify the program to accept a character typed in by the user
3. Modify the program to check for the letter ‘b’
4. Save, print and label your code
Extension
1. If statements work with numbers too. Create an IF statement to check a
number.
25
16.
IF...ELSE
#Declare variables
letter = "a"
Tasks
1. Modify your IF Selection program to use the ELSE statement
2. Save and label your code
Extension
1. How could you use this technique to identify if a given number is greater,
or less than zero?
26
17.
IF..ELIF..ELSE
▶ You can check a variable for many different conditions using ELIF
#Declare variable
letter = "a"
Tasks
1. Modify your IF ELSE program to use the ELIF statement to check for the
letters a-f
2. Save and label your code
27
18. Checking
Numbers
#Check x
if x < 0:
print("x is negative")
elif x > 0:
print("x is positive")
elif x == 0:
print("x is 0")
else:
print("x is not a number")
Tasks
1. Type in the code above and make sure it works
2. Modify the program to print a message if the number is over 50
3. Modify the program to print a message when the number is over 100
4. Save and label your code
Extension
1. Investigate what happens if you type in letters instead of numbers. How
might you prevent these issues?
28
19. Checking Data
Types
▶ The example below uses the Try/Except statement to catch the error
▶ The program attempts to execute the code in the try section
▶ If an error occurs, the code in the Except section is executed
▶ This works equally well at checking float() conversions too
try:
x = int(x)
except:
x = 0
print("You didn't enter a number")
Tasks
1. Type in the code above and ensure it works
2. Modify the program to output “You entered a number” if the input is
valid
3. Save and label your code
Extension
1. You can use this technique to detect an attempt to divide by zero. Use
this code to create a small program that will ask for two numbers and
detect any attempt to divide by zero
29
20. Logical
Operators
x = 4
Tasks
1. Type in the code and test that it works
2. Modify the program to check if a number entered is between 1-10, 11-20,
21-30, 31-
40 or 41-50
3. Save and label your code
Extension
1. Modify the program to accept user input, and handle unexpected input
appropriately (i.e. the user does not enter a valid number)
30
21. Test 3 -
Calculator
Main Task
1. Create a basic calculator program that will take two numbers, and perform
one of the following functions depending on what the user chooses:
a. add
b. subtract
c. multiply
d. divide
2. You should assume that all user input will be valid whole numbers. You
should ask the user which function they wish to perform. The output
should be formatted and laid out appropriately.
3. Have the program display an error message and exit if the user attempts to
divide by zero
4. Save and label your code
Extension
1. Modify the program so it prints to 2 decimal places
2. Modify the program so it checks the input numbers are valid numbers
3. Save and label your code
Hints
▶ It may help to sketch out on paper the order in which you need to
perform parts of the program
▶ You’ll need to cast (convert) inputs to integers
▶ Think about what input your program requires
▶ IF/ELIF/ELSE can be used to select different arithmetic operations
▶ All the required knowledge required for this task is contained in the previous
tasks on the website
31
22. Checking
Strings
Tasks
1. Type in the code above and make sure it works
2. Modify the program to check if the character entered is in the alphabet
(there are two ways to do this using the examples shown)
3. Save and label your code
Extension
1. The use of the NOT operator can be used as follows. Experiment.
32
23. Operators And
Strings
ASCII
▶ Less than (<) and greater than (>) works because the computer assigns all
letters a preset numerical value, documented in the ASCII character set
Tasks
1. Type in the code above and check it works
2. Modify the program to accept user input
3. Save and label your code
Extension
1. You can combine these techniques with an IF statement to check for any
allowed alphanumeric character (look at the table and find the lowest, and
highest numbers that identify the range of characters you want to accept)
33
24. Other String Things
Part 1
Reversing A
String
▶ Sometimes you might need to
print(str.upper())
reverse a string. This may be to
print(str.lower()) make a working
print(str.swapcase()) with binary strings easier, or to help
print(str.capitalize())
#This code reads the string variable,
#reverses it into the r_str variable
#Length of string
r_str = string[::-1]
print(len(str))
Tasks
1. Type in the code and make sure that it works
2. Add code to reverse the string and print it out
3. Save and label your code
Extension
1. You can combine these techniques with an IF statement to ask the user
to input a letter, and print a message if the input is 1 in length, and is an
uppercase letter.
34
25. Other String Things
Part 2
▶ All the different ways of checking strings and characters on the last page
return either TRUE (1) or FALSE (0). This means that they can be used with IF
statements
▶ If you played around with the input string, you should have realised that
islower() and isupper() only return true when the entire string is a
particular case
Tasks
1. Type in the code above and test it works
2. Modify the program to print out a message to say if the character is
uppercase or lowercase
3. Modify the program to print a message if the character is a number
4. Save and label your program
Hints
▶ You can use these techniques to perform rigorous checks on user input to
protect your program
▶ Checking user input is called validation and it helps make sure your program
runs as expected
35
26. Count Controlled
Iteration
▶ One of the things that makes a computer useful is the ability to repeat
an operation many times over at high speeds. This is called iteration or
looping
▶ The FOR loop allows us to carry out a set of instructions a specific number
of times
▶ The code within the loop must be indented
▶ The range arguments set the number of loops to perform: range(start,finish)
▶ The counter variable i displays the number of times the loop has executed
▶ Remember that the computer always starts counting at 0!
Tasks
1. Type in the code and make sure that it works
2. Modify the program so it prints out a list of numbers: 1-20
3. Modify the program so it takes in a word and number, and prints
the word the number of times specified
4. Save and label your code
Extension
1. The code below adds an extra parameter to the range() function that
controls the step, i.e. how many it jumps by each time it counts. The
example below counts up in twos from zero to one hundred. Can you
work out how to get the loop to count down from 100?
36
27. Condition Controlled
Iteration
#Set x to 0
x = 0
Tasks
1. Type in the code and make sure that it works
2. Change the code so it loops 20 times and prints out x each time
3. Modify the program so it prints out the squares of the numbers 1-10
(hint: multiply the counter by itself)
4. Save and label your code
Extension
1. Create a loop that will ask for a password and continue to do so until
‘apple’ is entered. A hint is shown below, but what other code do you
need to make it work (use the example above to help)?
37
28. Test 4 -
Iteration
Main Task
1. Create a program that:
a. Randomly generates a number between 1 -100
b. Asks the user to guess the number until they get it right
c. Says whether the guess is too high or too low
d. Says when they have guessed correctly, and quits
Extension
1. Modify the program so it records the number of guesses taken
Hints
▶ It may help to sketch out on paper the order in which you need to
perform parts of the program
▶ A good way of doing this is pseudocode, an example of which is shown below
▶ Write pretty much what you like, but each line should translate directly
into a line in your program. You should keep indents to show the bits that
loop
38
29.
Subroutines
#Subroutines first
def mySub():
for i in range(0,3):
print("hello")
def mySub2(word,times):
for i in range(0,times):
print(word)
Tasks
1. Type the code and make sure it works
2. Create a subroutine that prints the cube of a number passed to it
3. Save and label your code
Extension
1. You can create subroutines to do many things. Create subroutines to
perform basic calculations (add, subtract, multiply, divide) that you can
pass values to
39
30.
Functions
▶ The subroutines on the other page are simply procedures that run the
code within then when called. The other type is a function that returns
value(s) rather than printing to the screen
#Functions first
def double(number):
doubled = number * 2
return doubled
#Use in IF statements
x = 25
if double(x) > 100:
print("It's a big one!")
Tasks
def pos_or_neg(x):
1. Type in the code and make sure it works. if x > 0:
2. Create a function that takes the radius of a circle,
and returns the area of a circle πr2 return "Positive"
3. Save and label your code elif x < 0:
Tasks
1. Type in the code and make sure that it works
2. Add print statements at relevant points to show what effect each line has
on the list
3. Save and label your code
Extension
1. A while loop if frequently used to allow a user to keep adding new names
to the list, until a specific character (such as ‘Q’) is detected, when it will
stop and print out the list. Can you implement this technique?
41
32. Cycling Through & Checking
Lists
▶ FOR and WHILE loops are essential to make full use of lists with the
minimum amount of code
▶ The len() function can tell you how big your list is
▶ The in operator will be your best friend soon. It makes life very easy
#Using the 'in' operator to cycle through each name and print.
#The IF statement checks for "Joe" and finds index
for name in names:
print(name)
if name == "Joe":
print("Hey Joe, love Jimi!")
position = names.index("Joe")
print("Found at index: " + str(position))
Tasks
1. Type in the code and make sure that it works
2. Modify the program to allow the user to input a name to search for
3. Modify to use a list of 10 names, and print custom messages for two other
names
4. Save and label your code
Extension
1. The index number is frequently used to identify the exact position of an
item in the list, usually so you can delete it using the code below, the
position variable containing the index of the item to remove. Modify the
program to ask if the name should be deleted if it is found in the list
names.pop(position)
42
33. Searching and editing list
items
▶ The index number of the list item allows you to edit and delete particular
items
▶ This example uses the in operator to quickly check the whole list
▶ If the search term exists, it then looks up the index, and uses this to directly
edit the name “Sarah”, changing it to “Sara”
Tasks
1. Type in the code and make sure it works
2. Modify the program to ask the user for a name, search for it and
allow the user to update it if found
3. Save and label your code
Extension
1. This ‘search’ technique is essential knowledge because you must be able
to search in order to delete, or edit items in a list that already exists. Can
you modify the program to offer an option of edit (or) delete if the name is
found?
43
34. Quick Sorting/Searching
Lists
▶ A couple more tricks can be performed with lists to make them really useful
Tasks
1. Type in the code and make sure it works
2. Create a new list with 10 numbers in it, and print them sorted into order
3. Modify the program to accept user input to add more items to the list
4. Save, print and label your code
Extension
1. When you have a list with duplicate values, the quick search technique
above will not work. When faced with duplicate values, you must use a
FOR loop to cycle through the list and check each item individually, and
count, or display the occurrences. Can you do this? Refer back to the
earlier list tasks to help.
44
35. 2D Lists (Lists Within
Lists)
▶ This may sound complicated, but lists within lists are the best way to save
‘records’
i.e. multiple bits of information about one thing, such as the name, address
and telephone number of a user
▶ This type of list is known as a two-dimensional list
▶ Lists are sometimes referred to as ‘arrays’
45
35. 2D Lists (Lists Within
Lists)
Index 0 1 2
0 Mike Smith 24
1 John Thompson 56
2 Mary Field 19
Tasks
1. Type in the code and make sure it works
2. Add a new field to the list items to hold the e-mail address of each
person, and show you can print and edit it
3. Save and label your code
Extension
1. Creating code to neatly print out a list is important. Use a for loop and
appropriate escape characters (\n) or (\t) to display the list as a table.
There are several ways to do this, the most efficient using two FOR loops,
one inside the other
46
36. Searching/Sorting 2D
Lists
#Sort and print the list once the loop has finished
users.sort()
print(users)
47
36. Searching/Sorting 2D
Lists
Tasks
1. Type in the code above and make sure that it works
2. Add 3 more people into the original list
3. Modify the program to search for first name
4. Save and label your code
Extension
1. Investigate how this program reacts if there are duplicate names in the
list. What happens when you search and there are two people named
‘Smith’ for example? You can also modify this code to allow the editing of
a name if it is found
48
37. Advanced String Handling
Part 1
▶ Using loops and comparisons, you can do some pretty nifty things with
strings of characters
▶ Performing comparisons is much more powerful when you use loops to
inspect each individual character
▶ Note the in operator works on strings as well as lists
#Declare a string
string = "John Henry was a desperate little man."
#Loop through each letter in the string, and print with a space
after each
for letter in string:
print(letter)
#Set counters to 0
vowels = 0
others = 0
#if a vowel...
if letter in "aeiuo":
vowels += 1
49
37. Advanced String Handling
Part 1
Tasks
1. Type in the code and test it works
2. Modify the program to count uppercase and lowercase letters
3. Modify the program to count punctuation and spaces
4. Save and label your code
Extension
1. The break command allows you to exit a for loop at any time. You can
use this to modify your program to print an error and quit if a number is
detected in the input string.
50
38. Advanced String Handling
Part 2
#date
date = "12/04/1981"
Tasks
1. Type in the code and test it works
2. Modify the program to count uppercase and lowercase letters
3. Modify the program to count punctuation and spaces
4. Save and label your code
51
38. Advanced String Handling
Part 2
Extension
1. The split() function will not work if the number of splits does not match
the number of variables. For example:
date = "12/04"
day,month,year = date.split("/") #Won't work
52
39. Advanced String Handling
Part 3
▶ You can chop up strings and check individual parts when the input may be
multiple words or numbers separated by spaces or particular characters
such as full names or dates
▶ In the last example you split strings into an array but you can access
individual bits of them by number to save time
▶ Remember to use if statements to validate input!
#Date variable
date = input(“Enter the date (dd/mm/yyyy): ”)
Tasks
1. Type in the code and test it works
2. Save, print and label your code
53
40. Reading And Writing
Files
▶ Reading and writing files is fairly simple if you know what you want to load
and save
▶ There are simple techniques for reading and writing individual items of data
to and from a text file, a line at a time or all at once
▶ Reading multiple lines is usually done with a for loop and the contents are
loaded into a list within the program. Using a list means your program can
handle files containing different amounts of data.
▶ Depending on what you are using files for, it pays to have planned exactly
what you are loading and saving from your file. Questions to ask yourself:
▶ What am I actually storing on each line of the file?
▶ Is it an unorganised list or are the items in a particular order?
▶ Are there a set number of lines that will be used?
▶ Do you need to read/write each line individually?
▶ Do you need to add or delete individual items in the file?
▶ Do you need to store multiple items of information on each line? If so, how
will they be separated?
54
41. Read/Write A Single
Value
▶ The simplest thing you might need to do with files is to load or save a
single item of data
▶ The example below uses a text file called savedfile.txt to read/write a
number
▶ The program will produce an error if it does not exist so create it first (in the
same directory where your program is saved)
Tasks
1. Type in the code to test it works
2. Modify the code to accept user input of a new number to save
3. Try saving and loading strings, does it work?
4. Save and label your code
Extension
1. This technique was how early website counters worked. Each time the
code ran, it loads the number from the file, adds 1 and saves it back
to the file. Can you implement this technique?
55
42. Reading Multiple
Lines
▶ This example uses a file savedfile.txt with a list of names and reads in each
line at a time
▶ Each time readline() is called, the file advances by one line
▶ This is useful if you know exactly where you saved specific items in the
file, and you know how many lines there are in total
▶ However, it is no use if you don’t know how many lines are in the file
#Close file
file.close()
#Print the lines from the file that have been read in
print(line1)
print(line2)
print(line3)
56
42. Reading Multiple
Lines
Tasks
1. Type in the code and make sure it works
2. Modify the program to read the lines into a list and print the contents
3. Save and label your code
Extension
1. One technique to store more than one item per line, is to put a delimiter
between them, usually a comma (,) and you can use the split() function to
separate the parts of the line when you read it in. Add data into the text
file and try to get this technique to work
57
43. Writing Multiple
Lines
▶ When writing to files, you can either overwrite the information in the file
(w), or add to it as you go along (a). This is set as shown below. Choose
one or the other, not both
▶ There is a function called writeline() that you might assume is the
opposite of readline(). Using this is slightly different and we will simulate
the same effect by adding a line break \n each time we write a line to the
file
#Close file
file.close()
Tasks
1. Type in the code and make sure it works – append will add names
to the text file every time you run the code. Write will save over
the previous names in the file
2. Modify the program to accept user input to add 5 names to the file. There
are several ways to do this, the most efficient using a for loop that runs
5 times
3. Save and label your code
Extension
1. A while loop can be used to keep asking for names, and writing them to
the file until a specific letter or character is typed in, such as ‘X’. How
could you implement this feature? Can you make it work?
58
44. Reading Delimited
Files
59
44. Reading Delimited
Files
Tasks
1. Create a suitable .csv file with details of 5 people in it
2. Type in the code above and make sure it works
3. Save and label your code
Extension
1. This code is very basic and will break very easily if the file does not exist.
A function called exists() can be used to check for a file before trying
to open it. Do some research and try to implement a feature that
detects if the file exists
60
45. Writing Delimited
Files
▶ Writing delimited files is easy. You simply combine the items for each line,
separated by a comma, with a \n on the end and then write it to the file
#Close file
file.close()
Tasks
1. Type in the code above and make sure it works
2. Modify the program to accept user input
3. Save and label your code
Extension
1. You can implement a for or while loop in your program that will allow
you to enter details for multiple people, either until a specific character is
pressed or a set number of details have been entered. Can you make
this work?
61
46. Reading A File Into A
List
▶ A really important thing you will need to be able to do is read and write
text files with variable numbers of lines
▶ Because we don’t know how many lines there will be, we tend to read text
files into a list, make any changes, and then write the whole list back over
the file
#Define blank
list file_contents
= []
#Messy print
print(file_contents)
Tasks
1. Type in the code and make sure it works
2. Modify the code to allow you to choose a filename
3. Modify the code to print the list in a neater fashion
4. Save and label your code
62
46. Reading A File Into A
List
Extension
1. You can make this code more efficient by combining the splitting and
appending into one line (shown below). Implement this improvement:
file_contents.append(line.split(","))
63
47. Writing A List To A
File
▶ A really important thing you will need to be able to do is read and write
text files with variable numbers of lines
▶ Because we don’t know how many lines there will be, we tend to read text
files into a list, make any changes, and then write the whole list back over
the file
Tasks
1. Type in the code and make sure it works
2. Add two more people into the list (there are several ways to do this)
3. Modify the code to allow you to choose a filename
4. Save and label your code
Extension
1. Python can be buggy if it tries to write to a file that is open in another
64
47. Writing A List To A
File
program such as notepad. Try it and see what happens
65
48. Using
Pickle
▶ If you use lists to store the data from your program, there is a neat function
called pickle() that can be used to save the entire list rather than using
loops
▶ The example below saves a list to a file and then reloads it
▶ The data is not stored as text though, so you can’t edit it by hand
▶ You need to declare the pickle library at the start of your program
#Open file for write (binary), save list to file and close
file = open('savedfile.dat','wb')
pickle.dump(address_list,file)
file.close()
#Open file for reading (binary), read back into list and close
file = open('savedfile.dat','rb')
address_list = pickle.load(file)
file.close
66
48. Using
Pickle
Tasks
1. Type in the code and make sure it works
2. Open the .dat file in notepad. What do you see?
3. Save and label your code
Extension
1. You cannot create pickle data files using notepad, so you need to build
code to generate a list that you then save to the file. From that point on
you need to read into your list at the start of the program, and save it
back out at the end. Removing the list declaration at the top, and
swapping round the read and write sections in the program above will
make sure your program does this properly
67