Python Workbook Sm2012
Python Workbook Sm2012
Software
Development
Learning
Python 3
Units 3 & 4
Contents
What is Python? ...................................................................................................................................... 5
Who uses Python?. ................................................................................................................................. 5
What can you do with Python?............................................................................................................... 5
Starting Python ....................................................................................................................................... 6
Data Types............................................................................................................................................... 7
Pythons Shell ...................................................................................................................................... 7
Expressions.......................................................................................................................................... 7
Integers ................................................................................................................................................... 8
Floating Point Numbers .......................................................................................................................... 9
Strings and Characters .......................................................................................................................... 10
Booleans................................................................................................................................................ 11
Variables ............................................................................................................................................... 12
Adding to Variables ........................................................................................................................... 13
Changing Values ................................................................................................................................ 13
Evaluating Variables .......................................................................................................................... 13
More than one Variable .................................................................................................................... 14
Changing Variables............................................................................................................................ 14
input() ................................................................................................................................................... 15
Variables and input()......................................................................................................................... 15
Hello World ........................................................................................................................................... 16
Task 1: Inspector.py .............................................................................................................................. 17
Text based addition calculator .............................................................................................................. 18
Python is a strongly typed language ................................................................................................. 19
Languages Compared ........................................................................................................................ 20
What does this all mean?.................................................................................................................. 20
Changing Data Types......................................................................................................................... 21
How do you change a string to an integer? ...................................................................................... 21
IF Statements ........................................................................................................................................ 22
IF ELSE Statements ............................................................................................................................ 22
ELIF Statements................................................................................................................................. 23
Nested IF Statements ........................................................................................................................ 23
Task 2: Calculator.py ............................................................................................................................. 24
What is Python?
Python is a programming language that was first created by Guido von Rossum in 1990 and
was named after the British comedy Monty Python. Since then it has been developed by a
large team of volunteers around the world and released under the Creative Commons
License so that it is freely distributed and used without having to pay a license fee.
Python is a general purpose programming language that can be used on any computer with
any operating system. Computers with Unix, Linux, Sun, Oracle or Apple operating systems
have Python installed with the initial OS installation, computers with the Windows OS
installed must download and install Python from www.python.org.
Google uses Python in its web search system and employs Pythons creator.
Youtube video sharing is written in Python.
BitTorrent, the peer-to-peer file sharing system is written in Python.
Intel, Cisco, Hewlett-Packard, Seagate, Qualcomm and IBM use Python for
hardware testing.
Industrial Light & Magic, Pixar, Disney and others use Python in the production of
animated movies.
NASA, Los Alamos, Fermilab, JPL and other use Python for scientific programs.
New York Stock Exchange uses Python for financial marketing.
iRobot uses Python to program its robotic vacuum cleaners.
And plenty more
Starting Python
Once Python is installed open IDLE (Python GUI)
The information on the top line shows the version of Python that is installed, when IDLE was
built, the processor and the current operating system of the computer that is running IDLE.
The Python Shell is where you can explore Python syntax, get interactive help on
commands, and debug short programs. The graphical Python Shell (named IDLE) also
contains a text editor that supports Python syntax colouring and integrates with the Python
Shell.
Data Types
There are several different data types. Each store, behave or react in a particular way. In this
Pythons Shell
Pythons shell can be used as a calculator; on the following pages you will be using it to
calculate several mathematical expressions.
Expressions
value
operator
2+2
expression
value
Integers
Integers are whole numbers.
34 788
005
+ addition
- minus
* multiply
/ divide
% remainder
** power
In IDLE
Use IDLE to answer the following equations:
>>> 4+17
>>> 15*90*2
>>> -9+4-3
>>> 2*(3+4)
>>> 9*8 - -4
>>> 2+18/4
>>> 7+9*2
>>> 6+2*7/3+5
>>> 20%
>>> 7**3
>>> 64**4
>>> 6**10/5%4
8
56.03
44.9
- minus
0.99
* multiply
/ divide
% remainder
In IDLE
** power
The quote " " marks in the print statement mean that the information is read as a string.
Strings are text composed of any ASCII characters (alphabetic letters, numerals, punctuation
and control codes like carriage return, backspace, bell) up to about 2 billion characters.
While it can store numerals, it cannot interpret the value of numbers and instead treats
them as plain text. So if you add "1" and "2" you'll get "12" instead of 3!
In IDLE
Use IDLE to print the following string statements:
>>> print("hello")
>>> print(2*15)
>>> print("The quick brown fox jumped over the lazy dog")
>>> print("My birthday is : 00/00/00")
>>> print(I am learning to program in Python. I am studying Software Development)
10
Booleans
Booleans have two states, they are either True or False.
In IDLE
Use IDLE to print the following string statements:
>>> x = set(abcde)
>>> y= set(zyxwv)
>>> x
>>> e in x
type the around the letter you are searching for or youll get an error
>>> r in y
What does IDLE print?
11
Variables
Variables are some of the most important pieces of programming code.
12
Adding to Variables
Type
>>> box + 5
Press ENTER
So, that is like writing 15 + 5
What is the response IDLE prints?
>>>
Changing Values
The first time you store a value inside a variable, Python will create that variable. Each time
after that, the value will only be replaced.
>>> box = 15
>>> box + 5
20
>>> box = 3
>>> box + 5
8
>>>
Evaluating Variables
A variable is only a name for a value, we write expressions with variables like this:
>>> box = 15
>>> box + box
30
>>> box - box
0
>>>
13
>>> hamster = 10
>>> finch = 15
Changing Variables
Let's change the value in the box variable to:
>>> box = finch + hamster
>>> box
25
>>>
In IDLE
>>> tree = elm
>>> sky = blue
>>> animal = dog
>>> tree, sky, animal
If you place a comma between variable names it prints them on a single line.
>>> one = 1
>>> two = 2
>>> three = 3
>>> tree, one, sky, two, animal, three
>>>sum = one + two
>>> sum
>>>total = animal + sky + tree
>>> total
Explain what is happens in all four sections in the above script.
14
input()
input() is an inbuilt function* that lets the user input information into the program. Usually
input() is stored in a variable so the information can be stored.
input() is not a data type, but it used to store them.
After you press enter, the program will wait for input.
Type anything into IDLE, press enter, nothing will happen. You will get:
>>>
Python has now stored what you typed into the variable called word.
>>> print(word)
15
Hello World
Python has more functionality than just IDLE.
In the Python Shell, click on File> New Window (or press Ctrl+N)
This will open a script document.
Type this into the document:
print('Hello world!')
print('What is your name?')
myName = input()
print('It is good to meet you, ' + myName)
16
Task 1: Inspector.py
Turn this pseudocode into Python script:
17
So, youve said, the addition calculator will add two numbers together. Is it that simple?
Where do the numbers come from? How are they stored? What happens to them when
they are stored? How will it all be displayed? How do you ask for user input?
Think logically, how would you get your addition calculator to do this? Write pseudocode
to help you think through this problem.
HINT:
Step 1: User inputs one number
Step 2: User inputs second number
Step 3: Program adds numbers together
Step 4: Program displays answer
18
Test your theories in Python IDLE and see what you can do. Save it as calculator.py.
You will have something like:
print(Choose a number)
number1 = input()
print(Choose another number)
number2 = input()
print (Now they will be added together.)
answer = number1 + number 2
print(The answer is: + answer)
But it doesnt work, you will see that the two numbers are not added together.
19
Languages Compared
Java, C, C#, Pascal, Ada - require all variables to have a defined type and support the use of
explicit casts (deliberate conversions) of types.
Smalltalk, Ruby, Python, Lisp and Self are all strongly typed in that undeclared variables are
prevented at runtime and they allow little implicit type conversion.
Visual BASIC is a mixed bag. It supports statically typed variables, as well as the Variant data
type that can store data of any type. Its implicit casts are fairly liberal where, for example,
one can sum string variants and pass the result into an integer.
In general, weakly typed languages offer a faster development rate at the risk of accidental
improper data conversions (e.g. accidentally saying something like A=B + C and forgetting
that B is a date type, resulting in rubbish results.
Always declare variables first, before you call them in the code.
*Python reads code from the top to the bottom, so variables like answer are declared during the program, so
they can be utilised at the correct position. Python will not understand what you want it to do with answer if
you put it at the top because number1 and number2 do not have user input values yet.
IF Statements
If statements are one of the most used syntaxes in any programming language.
Basically an if statement says:
Like this:
if python == 6:
print('Python has 6 letters')
IF ELSE Statements
IF statements can be extended to perform an else.
IF this doesnt happen,
ELSE do this instead
Like this:
fish = 5
print(Type an amount of fish in the pond)
text = input()
if fish => 5:
print('There are heaps of fish in the pond.')
else:
print('There are not enough fish in the pond.')
22
ELIF Statements
Nested IF Statements
if trees == 12 and bugs == 100:
print ('There are lots of bugs today')
if worms == 3 and caterpillars == 5:
print ('The creepy bugs are out today')
elif worms == 2 and caterpillars == 4:
print ('There are some creepy crawlies today')
elif worms == 1 and caterpillars == 3:
print ('There aren\'t many creepy bugs')
else:
print('There are only caterpillars today')
elif trees <= 5 and bugs <=60:
print('There are not enough trees for the bugs to live in')
else:
print('You need more trees.')
23
Task 2: Calculator.py
Extending the addition calculator
You will need a menu system that selects between addition or multiplication options.
You will need to use IF, ELIF and ELSE statements.
You will need to put an error message in your code, if the user selects an incorrect menu
item.
You will need to create new variables to store the new inputted numbers.
EXTENSION TASK
Create a fully functioning calculator that adds, subtracts, multiplies and divides.
Get the last message to print the two selected numbers and the function, e.g:
2x4=8
not The answer is: 8
HINT: you will need to concatenate variables and strings together on one line, to do this use
+ symbols between the variables and the strings:
print(var1 + ' + ' + var2 + ' = ' + str(answer))
24
Arrays
Arrays are the same as Pythons Lists. In this documentation we will call them lists, but dont
get confused, because they are all the same thing.
Computers ALWAYS start counting at zero, so knowing this helps us tell the computer which
value we will be using in the list.
25
Open Python Shell and type the trees list into IDLE.
>>> trees = [elm, oak, gum, fir, pine+
To recall a list element type:
>>> trees[3]
This will print : fir
Remember that it starts counting from 0 not 1.
Remember how Python displays strings and integers? Strings have around them, integers
dont.
26
List Tasks
Convert the sentences into lists, following the example below:
Bob Smith is 42 years old, earns $30,000 a year and works in software.
bob=*Bob Smith, 42, 30000, Software+
Sue Jones is 45 years old and gets paid $40,000 a year, working in music.
John Black is 16years old and doesnt get paid anything. He wants to work in
Information Technology.
Hint: Use all three lists: Bob, Sue and John.
Splitting Records
Python allows you to split string records apart. This allows you to split records that have
more than one word in a string.
For example: things=*red matchbox car, orange and green spinning top+
I want to print the third word in the second record: green.
Remembering that when counting records, the first one is 0 and the second one is 1
To print green I use the split() function.
things[1].split() [-3]
list name
The [-3] means that it is splitting the third-last word out of the record. When splitting
records, Python counts from the last word and works backwards, thats why its a *-3+, its
taking 3 away from the last word.
What do you type to get Bobs last name to display? How about Sues first name?
27
Manipulating Records
It is important to note that when using integers in a list (array), it is difficult to change one
record for a period of time and then change it back while the program is running.
What is in the array stays in the array unless you physically type something else into it.
To add to an integer in the array you can do this:
>>>prices=[56, 30, 50, 800]
>>>prices[2] += 9
>>>print(prices)
[56, 30, 59, 800]
This adds 9 to record 3 in the list. This type of digit manipulation is stored for as long as the
program runs, but it doesnt update the record forever, you still have to do that if you want
to keep it at 59!
John finished school and went to uni, he gets paid $250 a fortnight. What do you put into
the list so that you can total his annual wages? What is the total of his wages?
28
Database Lists
When we have two separate lists, e.g., Sue and John, we can create a single list from them
by creating a new list.
people = [sue, john] note the lack of around the names, because we are calling the name of the list, not a string.
>>>print(people)
What displays when you print the two lists?
When dealing with many lists, we can collect specific records from them, to do this we type:
>>>people [1][0]
What displays when you type the above?
29
Python has three different types of arrays: lists, dictionaries and tuples.
value
element
Dictionary values have no restrictions. They can be made of any object (integer, string etc).
However, same is not true for the keys.
There are two important points to remember about dictionary keys:
(a) More than one entry per key not allowed. Which means no duplicate key is
allowed. When duplicate keys are encountered during assignment, the last
assignment wins.
(b) Keys must be unchangeable. Which means you can use strings, numbers, or
tuples as dictionary keys but something like ['key'] is not allowed --> because of
the square brackets [ ] around the key. This will cause an error.
Remember, if you try to access a key that is not in the dictionary, you will get an error.
30
This will only delete the Name record, including all information in the value.
Clearing Dictionaries
To clear all records in the dictionary:
>>>student.clear()
This will remove all records, but keep an empty student dictionary.
Deleting Dictionaries
To delete the entire dictionary:
>>> del(student)
31
32
Example:
>>>tup1 = (English, Maths, 2012, 2013)
>>>tup2 = (1, 2, 3, 4, 5, 6, 7)
>>>tup3 = (a, b, c, d, e)
Updating Tuples
You cannot change values inside tuple elements. But we are able to take portions of an
existing tuple to create new tuples.
Example:
>>>tup1 = (12, 34.56)
>>>tup2 = (abc, xyz)
>>>tup3 = tup1 + tup2
>>>print(tup3)
What is displayed when you print tup3?
33
Deleting Tuples
Removing individual tuple elements is not possible. There is, of course, nothing wrong with
putting together another tuple with the undesired elements discarded.
To explicitly remove an entire tuple, just use the del statement:
>>>tup = ('English', 'Maths', 2010, 2011)
>>>print (tup)
>>>del (tup)
>>>print ('After deleting tup : ')
>>>print (tup)
Tuple Concatenation
Concatenations is a fancy word for sticking something on the end of something else.
Tuple concatenation does exactly this.
>>>tupple3 = (1,2,3)
>>>tuple4 = (4,5,6)
>>>print(tuple3 + tuple4)
What displays on screen ?
34
What happens when you check for a string or character in the numbers list?
35
Task 3: timetable.py
Input your current timetable into Python. Get it to display three separate lists, day, period
and subject. Make sure it prints out similar to the timetable below.
Monday
1 Maths
2 English
3 Science
4 Science
5 Info Tech
6 History
Tuesday
1 History
2 History
3 Science
4 English
5 Maths
6 Geography
Wednesday 1 Science
2 English
3 Info Tech
4 Geography
5 Geography
6 History
Thursday
1 English
2 Science
3 Geography
4 History
5 Info Tech
6 Info Tech
Friday
1 English
2 Science
3 Maths
4 Maths
5 Info Tech
6 History
36
Loops
Loops are an important part of programming, they are used to repeat an action over and
over. There are two types of loops, while and for, both are used for separate purposes.
While Loops
While loops provide a way to code general loops, it repeatedly executes a block of indented
statements as long as the test at the top keeps evaluating to a true value. It is called a
loop because it keeps looping back to the start of the statement until the test becomes
false.
>>> b = 1
>>>while b <=10:
print(b)
b += 1
b is equal to 1
while b is less than or equal to 10
print b
add 1 to b
The computer will run through the loop until it gets to 10, then it stops.
37
For Loops
For loops step through items in any ordered sequence. A for statement works on strings,
lists, tuples and many other built-in objects.
>>> grocery=*bread, milk, cake, bikkies, custard, cereal+
>>>for food in grocery:
print(I want + food)
For statements loop through each item in the list and assign the element to a variable name.
So, in the example, the new variable called food stores each item in the list called grocery,
separately.
38
Counting from 1 to 5
By using the range() function, we are able to use for loops to count.
>>>for number in range (1, 6):
print (number)
The above code counts from 1 to 5. When declaring the range, always add 1 onto the last
number.
39
Task 4: forLoop.py
Create a list that has six different animals in it turkey, cow, horse, pig, dog and cat. Using a
for loop, get Python to print the following statement: A *animal+ is the best
Once you get the above task working, extend your script to have an IF statement. Look at
the pseudocode below and think carefully about how you will achieve the following:
IF *animal+ is a turkey, print Gobble gobble
ELSE IF *animal+ is a cow, print Moo Moo
ELSE IF *animal+ is a horse, print Neigh
ELSE IF *animal+ is a pig, print Oink oink
ELSE IF *animal+ is a dog, print Woof Woof
ELSE IF *animal+ is a cat, print Nom Nom
Create integer variables to use as counters, one for the pets and another for the farm
animals in the list.
For each animal in the IF statements, use the appropriate variable to add 1 onto the
counter.
Add some zoo animals into the list and include a new zoo variable.
Print the results of all counters at the end.
40
Task 5: whileLoop.py
Turn the following pseudocode into python script.
temperature 115
WHILE temperature is greater than or equal to 80:
PRINT temperature
temperature 1
END WHILE
PRINT The soup is cool enough
shop = list()
#creates an empty tuple to store the items in
items = input('Press y if you want to enter more items: ') # first message to print
while items == 'y':
#tests that while items is equal to y
line = input('Next item: ')
#ask for the next item if user entered y
shop.append(line)
#appends(joins) the tuple together
items = input('Press y if you want to enter more items:') # ask user if they want another input
print ('Your shopping list is:')
#if user types anything other than y this is printed
for line in shop:
#FOR LOOP to run through shop tuple
print(line)
#print the line variable
Use the code above to change your whileLoop.py to include the feature of typing in
temperatures of different foods and beverages.
41
Functions
Functions are chunks of executable code that can easily be used more than once in your
program. Functions are used to maximise code reuse and minimise code redundancy.
The first thing you have to do is to define a function. But before you start calling and using
your function you have to create one, to do this you type:
def functionName(x):
This creates the function
This names it
Not all functions do the same thing. They can create, store and return information. It is what
you get them to do that makes them different.
def myFunction():
print(This function doesn\t do anything.)
Defines the function
42
Functions as a variable
>>>b = times(3.14, 4)
>>>b
This creates a new variable called b that stores the times function.
>>> print(plusten(44))
What does this function do?
43
Modules
Modules are the highest-level program organisation unit. It packages code and data for
reuse, similar to functions, but in a unique way. They provide an easy way to organise
components into a system by serving as self-contained packages of variables known as
namespaces.
In simple terms, every file of Python source code whose name ends in a .py extension is a
module. Other files can access the items a module defines by importing that module; import
operations essentially load another file, and grant access to that files contents. The
contents of a module are made available to the outside world through its attributes.
b.py
Standard
library
modules
a.py
c.py
The image above sketches the structure of a Python program composed of three files: a.py, b.py, and c.py. The
file a.py is chosen to be the top-level file; it will be a simple text file of statements, which is executed from top
to bottom when launched. The files b.py and c.py are modules; they are simple text files of statements as well,
but they are not usually launched directly. Instead, they are imported by other files that wish to use the tools
they define.
44
Importing Modules
Python allows you to use custom modules. To import them into IDLE type:
import ModuleName
To put in action:
>>>import goldfish
>>>print(goldfish.title)
Create three new variables in the goldfish.py file and get them to print.
Functions in Modules
You can call functions within modules after you have imported them.
>>>def fish()
print(Fish live in water.)
In IDLE, type:
goldfish.fish()
module name
function name
45
About Modules
Importing modules is a delicate business. You can only import modules once each time you
run IDLE. Although you can keep typing import ModuleName into IDLE, it wont import the
same module twice. If you make changes to your module, you must reload IDLE before you
can import the changes.
random()
What is random?
Random is something that it not predictable or based on chance, like rolling a dice or
flipping a coin. Python has a built in module that you can import to give your programs the
functionality of random.
To use random in Python, first you have to import a module called random.
import random
variable = random.choice(array)
variable name to
store random
information
random module
called choice
Example:
import random
flavours = ['vanilla', 'triple chocolate', 'mint chock chip', 'rum and raisin', 'blueberry fudge']
picked = random.choice(flavours)
print (picked)
What does the above code do?
46
Task 6: ralf.py
Ralf has a gemstone washing machine. He has 40 dirty rocks. Inside each rock is a gem.
Some rocks dont have a gem, they will turn into mud, but Ralf will only know once the rock
has been cleaned. He wants to know how many opals, rubies, turquoise, emeralds and
diamonds there are in his bucket.
47
random.int()
random.int() is a function within the random module that calls a random integer.
random.randint(x, y)
x is the lowest value
Like random.choice() you can store the random.int() in a variable, so it is easier to call upon
the chosen integer throughout your program.
time()
time() is another built-in function that provides the ability to pause print statements. To use
it, you must first import time.
time.sleep(x)
module name
function name
48
amount in seconds
Task 7: dragon.py
Re-write this pseudocode into Python. Dont forget to write comments into your code.
import random, time
FUNCTION displayIntro
PRINT 'You are in a land full of dragons. In front of you, you see two caves. In one
cave, the dragon is friendly and will share his treasure with you. The other dragon is
greedy and hungry, and will eat you on sight.'
END displayIntro
FUNCTION chooseCave
cave empty string
WHILE cave <> 1 and cave <> 2
# <> means not equal to
PRINT Which cave will you go into? (1 or 2)
cave input
END WHILE
return cave
END chooseCave
FUNCTION checkCave(chosenCave):
PRINT You approach the cave
Sleep for 2 seconds
PRINT It is dark and spooky
Sleep for 2 seconds
PRINT A large dragon jumps in front of you! He opens his jaws and
Sleep for 2 seconds
friendlyCave random.randint(1, 2)
IF chosenCave is equal to str(friendlyCave)
PRINT Gives you his treasure!
ELSE
PRINT Gobbles you down in one bite!
END IF
END checkCave
playAgain yes
WHILE playAgain is equal to yes or playAgain is equal to y
displayIntro()
caveNumber chooseCave()
checkCave(caveNumber)
PRINT Do you want to play again? (yes or no)
playAgain input
END WHILE
49
str.maketrans()
str.maketrans adds a little bit of fun into your Python program, it can encrypt and decrypt
messages.
word = input('Type in a sentance: ')
table = str.maketrans(
"cdefghijklmnopqrstuvwxyzab" , "abcdefghijklmnopqrstuvwxyz"
)
encrypt = word.translate(table)
print(encrypt)
50
Task 8: translate.py
Using str.maketrans translate this message:
xqg eio nqfzy ioewwx poww aq yoa acfd uei pfac xqgi tiqyievvfzy. yqg cejo woeizon e wqa
dfzko xqg hoyez oeiwfoi acfd xoei. xqgi drfwwd pfww nojowqt ugiacoi ed xqg daeia aq pifao
xqgi qpz tiqyievd. kqzyieagweafqzd qz ojoixacfzy xqg cejo ekcfojon, xqg cejo aq ho joix tiqgn
qu xqgidowu.
51
Modulus %
Modulus finds the remainder.
>>>12%9
3
You can read the above as: 9, 10, 11, 12 there are three numbers left over after 9.
Modulus isnt only to find the remainder, it is used to input data into your program.
Modulus d (%d)
%d reads decimal integers.
>>>camels = 42
>>>print(%d camels % camels)
def times(number):
for chosenNumber in range(1, 13):
print ('%d x %d = %d' % (chosenNumber, number, chosenNumber*number))
times(5)
What does this code do?
52
Modulus s (%s)
%s reads strings.
>>>rabbits = bunnikins
>>>print(%s are rabbits % rabbits)
What does this code print?
>>>orange= goldfish
>>>brown=horse
>>>green=frog
>>>print(%s %s %s, (orange, brown, green))
What does this code print?
53
Modulus g (%g)
%g reads floating point numbers.
>>>num = 56.383
>>>print(The number is: %g % num)
What does this code do?
Using modulus d, s and g write some code that reads variables that stores appropriate
data. Write your code below:
54
Skill Building
Remember to write it in pseudocode first!
Skill 1: TrafficControl.py
Write a program that Police can use to check the speed of drivers. The Police input the
speed zone before the speed checks take place. As cars go past, the Police get the speed the
car was going, and displays a message saying whether they were going too fast, the correct
speed or slow. The program should issue a fine if the car is going too fast: 5km over the
limit: $120 fine, 10km over the limit: $230 fine, 20km over the limit: $450 fine, anything
above 20 km the Police issue an Immediate Cancellation of Licence.
Skill 2: Airport.py
A plane with 300 passengers has landed. Write a program that sorts the passengers out.
How many passengers have Australian passports and how many have International
passports. You should be able to tell how many passengers have filled in a Customs
Declaration Form and declared something to go through customs, and how many illegal
items were seized and what these illegal items were, e.g. a crate of chickens, dried figs,
wooden items with spiders, box of snakes, Asian fruits with bugs, beef jerky, drugs, fur coat
with teeth and a moose head.
Skill 3: fishing.py
The ASDF (Australias Special Department of Fishing) is checking the catches of recreational
fishermen. They are looking for the amount and sizes of particular fish:
Fish Type
Minimum Size
Limit
Shark
50cm
3
Whiting
25cm
30
Sea Bass
1 meter
15
Flathead
25cm
20
Bream
20cm
23
Orange Roughie
30cm
12
If the ASDF finds fish that are below the legal minimum size, the fisherman is issued a $230
fine per fish. If the fisherman has fish above the minimum size they can keep it as long as
they have a valid fishing license. If fishermen are caught with Abalone they are arrested and
go to gaol. Boats have to be registered, sea worthy (e.g. have life jackets and a flair) and
have a GPS, if they do not have any or all of these items they are issued with a warning and
a $678 fine.
55
Skill 4: election.py
Its election time in Roughead Region! Fred Ferris and Georgia Green are both hoping to win
the election, but its up to the people to decide. Within the Region are six electorates, each
with a different population:
Electorate
Harrison
Nimbottom
Goosehead
Davis
Ferdinand
Charles
Population
1023
34,870
23,452
530
67,001
10,080
Calculate the number of people who will vote for each candidate, and ultimately who is the
winner of the election. Keep in mind there are children below 16, and elderly above 80 do
not have to vote.
Skill 5: landcare.py
Landcare has three weeks to revegetate Erosion Point. They need 80 volunteers to
revegetate 100 acres. Each volunteer can plant 30 trees a day. Landcare is going to use two
types of tree; Spotted Gum and Stringy Bark. How many trees and what type do they need?
56
>>>count = 23
>>>print(count)
What displays in IDLE?
>>>count = 23
>>> print(str(count))
What prints now?
57
str.format()
The str.format() method works like this:
>>>print(We are at ,- and enjoy ,-).format(school, Software Development))
What does IDLE print?
The brackets and characters within them (called format fields) are replaced with the objects
passed into the .format() method.
A number in the brackets can be used to refer to the position of the object passed into the
.format() method, similar to an array.
58
Escape Characters
When you get Python to print a lot of text, sometimes you want to format it a bit, escape
characters let you do exactly that. An escape character is basically a \ (back slash),
sometimes with a letter after it to explain to the computer what is supposed to happen.
Type
\n
What it does
Line feed (or an ENTER)
Example
print(1\n2)
\
\
print(Don\t do that!)
print(He said \Yes\)
Result
1
2
Dont do that!
He said Yes!
When using the \n escape character be careful not to put a space between the \n and the
next word, because Python will read the space and push the words across by one character
on the next line.
Example:
>>>print(Software Development\n English\n French )
Software Development
English
French
Try the escape characters out and see what you can do!
59
Example:
>>> s = Software Development
>>>str(s)
What does IDLE PRINT?
>>>repr(s)
What does IDLE print?
>>>x = 4 *2
>>>y = 2 * 10
>>>s = The value of x is +repr(x) + , and y is + repr(y)
>>>print (s)
What does IDLE print?
60
>>>for x in range(1,11):
print(,0:2d- ,1:3d- ,2:4d-.format(x, x*x, x*x*x))
61
a opens the file for appending. Meaning any data written to the file is automatically
added to the end.
The mode is optional, but it is automatically assumed to be r if it has not been included at
the end.
Files are usually opened in text mode, meaning that you can read and write strings from and
to a file. Lets take a look.
Open Notepad and create a text file called: test.txt - this is the file we are going to be
working with. Close the text file.
The first thing we have to do when working with text files is to create file object which is
going to allow you to perform actions on the file. To do this we create a variable in IDLE.
Every time you use the name of the variable fob you care calling the file path.
To write data to the text file you use:
write function
close()
You must always close the file so that Python knows that you have finished writing to it.
>>>fob.close()
>>>fob2=open(C:/Documents/Python/test.txt, rz )
Use r instead of w
>>>fob2.read(3)
Read reads the bytes, 1 byte is usually a character or a number, so in the code above IDLE
will print the first three letters.
To read the remainder of the file:
>>>fob2.read()
The lack of parameters in the parenthesis means that IDLE will read the remaining bytes in
the file.
IDLE will print now brown cow, because it has already read the first three bytes.
63
>>>print(fob3.readlines())
Beware of the s on the end! Readlines does something different to readline.
Readlines reads the remaining text in the text file and displays it as a list.
64
>>>fob.close()
To modify a certain line in the list now you can call the list item, remembering that the first
list item is [0].
The change is not saved to the text document yet. We have to create a new file object to do
this.
>>>fob=open(C:/Documents/Python/test.txt, w)
>>>fob.writelines(readlist)
>>>fob.close()
This writes the new data into the text file.
>>>print(readlist)
What does IDLE print?
65
Advanced Python
2D arrays
In math you would have been introduced to matrices. 2D arrays and matrices are the same
thing; they just look a little different.
Example:
m=
[[3, 5, 7],
[4, 0, 2],
[1, 2, 5]]
Maths matrix
Python matrix
m=
10
[[3, 5, 7],
[4, 0, 2],
[1, 2, 5]]
m2 = [[1, 2, 3],
[3, 1, 2],
[2, 3, 6]]
66
The only problem with working with 2D arrays, is that they have to be the same size if you
want to perform any mathematical function on them.
67