0 ratings0% found this document useful (0 votes) 338 views26 pagesUnit 4-Programming (It All Adds Up)
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
Programming: It all adds up
You will learn
> how to use conditional (if) structuresin Python
> how to make Python programs with loops
> how to find and fix errorsin programs
> how to make your programs user friendly
and readable.
In this unit you will make a program which adds up the number
of birds visiting a bird feeder. This program will be useful ‘
for scientists and nature reporters. As you work through the
lessons in this unit you will make the program. You will use
programming structures such as loops and ‘if... else: You
will learn to read error messages and to improve your
program by removing errors.
Work in a group of four. In this activity you will act out a
computer program.
(a \
other container. You can write any numbers you like. Make sure at
least one of the numbers is 0 (zero). You also need a blank piece of paper and a pen.
Write numbers on slips of paper and put them ina box or
Team roles: Each person in the team will play the role of part of the program. There
are four roles:
> Program. > Total
> Input > Logical test.
The person whois the ‘Program’ reads out the instructions on the next page, one at
atime. As ‘Program’ reads each instruction, they point to the person named, That
person then carries out the instruction. If the person who is the ‘Logical test’ shouts
“Stop!”, the program stops.
PE Rance a a range of errors to improve a program
©Instructions: Stop!
1 Total: record the value 0.
2. Input: take a number from the box and read it out.
3. Logical test: shout “Stop!” ifyou hear the number zero. ‘
4. Total: add the input number to ‘total’
5 Program: go back to ine2 and continue from there.
When the program stops, check the value of ‘total’ That is the final output, Logical test
of the program.
S
‘Ro
%
a
Program,
Pete Ra Carolee
The software you make in this unit will count the number of bird
visitors. But you might also want to know what types of birds the
visitors are. You can download apps onto your phone that help you
identify bird species. Some apps ask you a few questions about the
bird (size, colour, etc.) You input the answers and the app outputs
photos of possible bird species. Other apps, such as ChirpOMatic,
accept sound input. You input a sound recording of birdsong and
the app outputs the name of the species.
Talk about...
In this unit you will make a program to record the
number of bird visitors to a bird feeder. Helping reroll tear Eire oL
scientists to study nature is one way that f
computers can help protect the environment. bs
Overall, do you think computers have had a positive OCLC ao caced
ornegative impact on nature? Think of as many
‘examples as you can on both sides of the debate. logicalerror user friendly
indent for loop
al lar co cL}
@) Coe nae neLogical tests and choice
In this lesson
Youwilllea In previous books you made
2 programs using the ‘if... else”
block in Scratch. Actions inside
the ‘if... else’ block are controlled by a
logical test. In this lesson you will
make programs in Scratch and Python
using the if... else’ structure. Look
back at previous books to refresh
your understanding of Scratch.
> how to create an ‘if structure in Python and Scratch
> how to make logical tests with relational operators.
Conditional structure
In Unit 3 you created a Scratch program that added two
numbers together. The program always did the same
thing. Now you will adapt the program so that itcan add
or subtract. The user’s choice will change what it does.
To vary what a program does, youuse a conditional
structure. This type of structure is also called an ‘if?
structure, The structure begins with the word ‘if’ and
then has a logical test. The commands inside the if
structure are only carried out ifthe test is True.
Logical test
The result of a logical test can be True or False. A logical
test usually compares two values. It uses a relational
operator to compare the two values.
Relational operators
In Scratch the relational operators are three green blocks.
668
The table shows the meaning of the three relational operatorsin Scratch.
| __ Operator | What itmeans |
5 greater than
< less than
= equal toComparing values
‘To make a logical test you compare two values. The comparison can be either
True or False. Here is an example:
4>8
‘This means ‘4 is greater than 8: This comparison is FALSE, so the logical test has
the value False.
Here is another one.
34427
This means ‘3 plus 4 is equal to 7°. This comparison is TRUE so the logical test has
the value True.
@Lma
Here are some examples of logical tests. One of the values is missing. Copy the
logical tests into your book and fill n a missing value that makes each test True.
a (7*e< © 400/50>C) e 1234=()
b 2343-0] @_99.999<[]
Make a Scratch program
Here is an example of a Scratch program that includes a
conditional structure. Dain
The user has to choose whether to add two numbers. =e
Ifthe user types ‘Y, the program will add the numbers. =
This program includes the conditional ‘if’ block. ak Early
eee
This block starts with the logical test:
‘answer=Y"
Ifthe user enters the letter‘, the test is True. The computer carties out the
commands inside the ‘if’ block. Ifthe user does not enter the letter Y, the testis
False. The computer does not catry out any commands.
@Lxza
Make the Scratch program shown in the image above. Run the program to see
what happens when you enter Y’ and when you enter anything else.
e dn sppe je 3] :6uruiwesBoidPe keke
Make a Python program
Now you will make the same program using Python. You can use ‘if... else”
structures in Python programs. But Python does not use blocks. Instead you type
the commandsas text,
Set variables
The Scratch program has three variables: ‘number! ‘number2’ and ‘answer. The
values of ‘number!’ and ‘number2' are set in the program. The user inputs the
value of ‘answer’
You already know how to do these commands in Python:
number] = 70
number2 = 80
answer = input("do you want to add? (¥/N) ")
Make the logical test
Python has more relational operators than Scratch. Here equal to
are the main relational operators that you might use. not equal to
For this program you will use the ‘equal to’ operator. The greater than
logical test compares the user answer to the text string Y. lessthan
Ifthey match, the testis True. greater than or equal to
if anewer == "y less than or equal to
Inside the conditional structure
Now you must put commands inside the conditional structure. The computer will
carry out these commands if the test is True.
1 sine ae NY Puta colon (:) at the end of the logical test.
All the commands that follow the colon will be indented, That means they will be
set in from the left of the file window.
if answer
yn
result = numberl + number?
print (result)
‘The computer will only carry out the indented commands if the test is True.
The picture on the right shows what the code lookslike —munsert = 70
in the Python window. The Python IDE uses a range of
colours for different types of word and symbol.
The word i£ is a Python key word. Key words are
used to build program structures in Python.
number? = 80
answer = input (* wa a ”
result = nurberl + nunber?
print (result)
In the Python IDE, key words are displayed in gold (dark yellow) font.
OI
eo Make a Python program by putting together all the commands shown above.If and else in Scratch
In Scratch, the ‘if... else’ block has two spaces init.
> The commands in the top space are carried out ifthe
testis True.
> Thecommands inthelowerspace are carried outif [umes °°)
the test is False.
The picture on the right shows an example of a Scratch
program that uses ‘if... else. arava) = QD ve
Ifthe testis True, the two numbers are added together. If
the test is False, ‘number2’is subtracted from ‘number?’
If and else in Python
To do the same thing in Python you enter the word else
followed bya colon.
Sete ee Rom
if answer
result = numberl + number?
else:
result = numberl - number?
print(result)
Notice which commands are indented. These are the commands inside the
conditional structure.
@ESIID or
Make the Scratch program that uses the 1 Here are some logical tests using Python
‘if,.. else’ block. relational operators. Which are True and
which are False?
5-1
1 *5
Make the Python program thatuses if... else. :
a
b 55
€ 22 1= 23-1
oO Extra challenge 2. Here is a Python program.
program? When will you see this output?
rs
In the example in this lesson, the values of the in pee a pee ?
variables ‘number1’ and ‘number?’ are set by a aca &
the program. vi 3
print ("you can make another menu chose’ 3
> Make a version of the Scratch program where 3
i 3
the user inputs the values of the two numbers. a The user entered the letter “x? What is the =
> Make a Python program that does the same output of the program? a
thing. b What other output can there be from this &
£
$Add up a total
In this lesson
You will lear:
> how to increase the value of a variable
In previous books
you made programs
Scratch that used
loop. Actions inside a
loop are repeated. In this,
lesson you will discover
how to use loop structure
in Python programs.
> how to use counter loops in Python and Scratch.
Loops
Most programming languages allow you to put program commands
inside a loop. Commands inside a loop are carried out many times. In
Scratch there isa ‘forever’ loop. Commands inside the ‘forever’ loop
will repeat until the program stops.
Most programming languages do not use ‘forever’ loops. In most programming
languages, every loop has an exit condition. The exit condition is how you stop
the loop. There are two types of loop. They have different exit conditions.
> Acounter loop (or fixed loop) repeats a set number of times then stops.
> Aconditional loop (or condition-controlled loop) is controlled by
alogical test.
In this lesson you will make a program with a counter loop.
Scratch program with counter loop
Scratch program 1s simple calculator. It asks the userto input two numbers.
The program outputs the result of adding them together.
Scratch program 2is the same program. But in this version, all the commands are
inside a counter loop. The number at the top of the loop tells you how many times
the commands will be repeated.
When you run this program, the calculation will repeat 10 times. If you change the
number, you change the number of repeats.Python program with counter loop
In Python a counter loops called a for loop. To make a loop that repeats
10 times the command is:
for i in range (10):
To make a loop that repeats 20 times the command is:
for i in range (20):
The lower-case letter i is the counter. You don’t have to use the letter ‘i’ - you can
use any name. But itis common for programmers to use the letter ‘i! The number
in brackets sets the number of times the loop will repeat.
Python program 1 adds two numbers together.
1 numberi = input ("enter a number ") 2 for 4 in range (10):
nurberl = int (number1) punberl = input ("enter a
punber1 = int (nunberl)
nber *)
number? = input ("enter a number ")
number2 = int (nunber2) nunber2 = input ("enter a number *)
number? = int (number?)
result = numberl + number?
result = number + number?
print (result) print (result)
Python program 2 is the same program with a counter loop.
The commands inside the loop are indented. The indented commands will repeat.
@LIa
Make the Scratch program and the Python program shown
above. In each program, use a counter loop to repeat the a
commands.
Increase the value of a variable
Inthe programs you have just made, the user enters two,
numbers with each repeat of the loop. Each time, the program
outputs the result of adding those two numbers.
But quite often in programming you will want to add to the
previous total each time the commands repeat. To do this you B
need to create a new variable called ‘total’
Scratch program A sets ‘total’ to 0. Then
‘total’ by 1.
increases the value of
‘Scratch program B sets ‘total’ to 0. Then it increases the value of
‘total’ by adding a number that the user inputs,
8 dn sppe je 31 :6unmwesBoudero
Plan to add up a total
Youcan usethecommand total = total + number tomakea program that
adds together 10 numbers.
Here isa plan for that program:
Set the total to 0 at the start of the program.
Loop 10 times:
Inputa value.
‘Add the input value to the total.
‘Output the total at the end of the program.
Add up a total in Scratch
Look at the program planin the table. For each line of the program you should
know the matching Scratch command.
Greene Erne
Settotal to0
Loop 10 times
Input a value
‘Add the input value to the total
Output the total
OI
You can do either or both of these activities.
1 Copy and complete the table shown above. Note the Scratch block you would
use to match each action.
2 Make a Scratch program to match the plan.
Increase a variable in Python
You have used the Scratch command to increase a variable. You can do the same
thing in Python. This Python program sets total to. Then it increases the value
of total by 1
total = 0
total = total +1
print (total)
This Python program sets ‘total’ to 0. Then it increase the value of ‘total’ by
adding a number that the user inputs.
total = 0
number = input ("enter a number “) |
number = int (number)
total = total + number
° print (total)Remember in Python you need to convert user input toa number value before
you doa calculation. That is the purpose of this command.
number = int (number)
Python program to add up a total
In Seratch you put the adding commands inside a loop. You can use Python to
make the same program that you made in Scratch. You already know the Python.
commands that match each line of the plan.
Ginekol Python command
Settotal to0 total = 0
Loop 10 times for i in range (10
Input avalue number = input("enter a number ")
number = int (number)
‘Add the input value to the total total
Output the total print (total)
total + number
lfyou fit these commands together, you will make a working program. Remember
that Python will indent the commands inside the loop.
Om
Make a Python program to match the plan shown above. The program will use
a counter loop. It will add 10 numbers to make a total.
Inthe last lesson you learned that i¢ is a Python key word. The colour of key
words in Python programs is gold. What other key words have you used in
this program?
@O Brena
This Scratch program sets the variable ‘total’ to 100. Then it uses a
counter loop to subtract 10 values from ‘total’
Make a Python program that does the same thing.
ors
1. What does ‘exit condition’ mean?
2. Whatare the two types of loop? Pe ye
3. Write the first line of a Python loop that repeats 100 times. ‘
4 APython program includes a variable called po ints. Write the
command to increase point s by 10.
8 dn sppe je 3] :6uruiwesBoidConditional loop
In this lesson
You will lear:
> how to use a conditional loop in Scratch and Python.
What is a conditional loop?
Inthe last lesson you learned how to use a counter loop. Another name for a
counter loop is a fixed loop, because the commands inside the fixed loop repeat a
fixed number of times. You set the number of repeats at the top of the loop.
conditional loop is different. itis controlled by a logical test. Every time the loop
repeats, the computer tries the logical test again. The result of the logical test
tells the computer whether to repeat the loop or stop.
Conditional loop in Scratch
This Scratch block makes a conditional loop.
The loop starts with the words ‘repeat until! Then there is a diamond-shaped
space. A logical test block will fit into this space. The logical test will control
the loop.
The loop will repeat until the test is True. Here is an example. Any commands
that you insert inside the loop will repeat until the user enters ‘0’
Adding up with a conditional loop
(On the right is the finished Scratch program. Itadds each
new number that the user enters to the total. The loop
will repeat until the user enters the value ‘0:
The logical test in this program is:
“answer =
The computer will check the logical test every time the
loop repeats. The loop will repeat until the condition
is True:
> Ifthe condition is FALSE, the loop will CONTINUE.
> Ifthe condition is TRUE, the loop will STOP.When to use a conditional loop
Use a loop when you want to repeat commands inside a program.
> Ifyou know exactly how many times you want to repeat the commands, use a
counter loop.
> Ifyou don’t know exactly how many times you want to repeat the commands,
use a conditional loop.
em
Make a Scratch program to add each number that the user inputs to the total. Use
a conditional loop. You can choose your own logical test for the conditional loop.
Save and run the program. Correct any errors.
In Python a conditional loop is called a while loop. The first line of a while loop
has these features:
> the word while
> allogical test
> acolon.
The computer will check the logical test every time the loop repeats. The loop will
repeat while the condition is True:
> Ifthe condition is TRUE, the loop will CONTINUE.
> Ifthe condition is FALSE, the loop will STOP.
Thisis the other way round from Scratch.
What logical test?
You have to choose the logical test carefully.
In Scratch the loop stops when the test is True, The example program used
this test:
‘answer= 0"
In Python the loop stops when the test is False. You will use this test:
=o
means ‘does not equal’.
> Ifthe answer does not equal 0, the test is True. The loop will continue.
> Ifthe answer equals 0, the testis False. The loop will stop.
The complete Python command to begin the conditional loop is:
while answer I= 0:
8 dn sppe je 31 :6unmwesBoudCorner)
Sully’s program goes wrong
Sully made a Python program to add up a total. He used a conditional loop.
Here is Sully’s program:
total = 0
while number t=
number = input ("enter a number ")
number = int (number)
total = total + number
print (total)
Sully’s program did not work properly. Sully saw this error message:
File *C:\temp.py", Line 2
while number t= 0:
NameError: name ‘nunber' ix not defined
What has caused the problem? The error message told Sully the mistake isin
line 2:
while number I= 0:
‘The error message says: name ‘number! is not defined.
‘The computer does not know what number means. This variable has not been
given a value yet. In Python, the computer cannot use a variable unless you have
given it a value. That means the computer cannot do the logical test.
Sully’s program is still not right!
Sully decided to change the program. He found the command that assigns a value
to the variable nunber and the command that makes the variable into an integer.
number = input("enter a number ")
number = int(number)
He moved these commands to before the loop. Here is the new program:
total = 0
number = input ("enter a number *)
nunber = int (number)
while number l= 0:
total = total + number
print (total)
When Sully ran the program, it started and asked him to enter a number. He
entered one value. But then the program stopped working, Nothing appeared on
the screen. Eventually Sully tried to close the Python Shell. He saw the message
shown on the right.
The message says the program is still running! Sully clicked OK to {@ xi x
‘kill the program. (‘Kill’ means stop the program running.) But what
went wrong? |
In this program there is no input inside the loop. The user cannot
enter a new number value. So there is no way to stop the loop.
® The loop continues forever (until Sully closes the program).Sully got it right
Inthe end, Sully changed the program again. He put input commands before
the loop and inside the loop. This time, the program worked as planned. Hereis
Sully's new program:
total = 0
number = input ("enter a number ")
number = int (number)
while munber = 0:
total = total + nunber
number = input ("enter a number ")
number = int (number)
print (totaly
What Sully learned
To make a Python program with a conditional loop you have to do three things:
1 Start the loop with a logical test.
2 Assign a starting value to the test variable before the loop begins.
3. Givethe user a chance to change the test variable inside the loop.
Because Sully did all three things, his program worked fine.
OL
Make the Python program shown in this lesson, Save and run the program.
Correct any errors.
(>) Extra challenge
> Make a Python program that adds each number that the user enters to the
total until the user enters a value smaller than 0.
> Make a Python program that sets the variable tot.a1 to 100 and subtracts
numbers until the user enters a value greater than 99.
om
1 Inyour own words, explain when to use a conditional loop in your program.
2 Here isa line from a Python program. What value of the variable username
will cause the loop to stop?
while username x"
3. Here isa Python program. It has an errorin it. Explain what the error is.
print("Start program")
while username x
username = input("enter your name
print("hello”, username)
4 Write the program without the error.
e dn sppe je 31 :6unmwesBoudA class project
In this lesson
Youwill learn:
> how to apply Python skills to solve a problem
> how to spot syntax errors and fix them.
Counting up
Mr Shakir is a science teacher. His students are doing a biology project about bird
populations. They have to count how many birds visit the school bird feeder.
Mr Shakir has asked his students to write a Python program to count the number
of bird visitors,
Here is the program requirement:
The user will input a every time they see. bird at the table. When the program is
finished it will output the total number of birds that visited the table.
‘The program will be called Bird Counter.
Class discussion
The class discussed what they needed to include in the Bird Counter program.
Here are some of the students’ ideas from their discussion:
> “Weneed a variable to store the number of birds.”
> “Yes, and that number must start at 0.”
> “Wemust havea loop, of course.”
> “The loop must be a conditional loop because we don’t know in advance how
many birds we will see.”
> “Ifitisa conditional loop, we have to think about the logical test. How do we
stop the loop?”
Mr Shakir agreed with the students’ ideas. He said, “Your ideas will help us make
the program.”
Om
Before you read any more of this lesson, try to make the Bird Counter program.
Use the clues in the class discussion and the commands you learned in
Lessons 4.1, 4.2 and 4.3 to help you make the program.
Program problems
Each student in Mr Shakir’s class tried to write the Bird Counter program. But the
students made some errors.All programmers make errors when they write programs. A good programmer can
recognise errors and fix them. Then their programs work the way they planned,
The Python IDE has features to help you find and fix errors:
> colour and layout when you write the program
> error messages when you run the program.
In this lesson you will learn to recognise and fix common program errors
in Python,
Syntax errors
Every programming language has rules. The rules of a language are called
syntax. Ifyou break the rules of a programming language, you make
a syntax error.
In Unit 3you learned what happens when you run a program:
1 Translating: The computer turns the commands into machine code.
2. Running: The computer executes the machine code commands.
If there is a syntax error, the computer cannot understand the commands.
It cannot translate them into machine code. The computer will stop.
Itwill show you an error message.
Fixing the problems
Mr Shakir checked the programs
is students made.
He wrote this note for his students. It lists the most,
common syntax errors that he found.
Using the wrong word
lot using indent
Leaving out the : si
Single = instead of double ==
Using the wrong word
Abdel is one of Mr Shakir’ students. He mixed up
Scratch and Python
In Scratch a conditional loop begins ‘repeat until:
In Python a conditional loop begins while.
Abdel typed ‘repeat until’ in a Python program.
Here is the error message he saw.
‘The message says there isa syntax error. It has
highlighted the line where the erroris. This helped
‘Abdel to fix the problem.
Python makes it easy to spot where the
error is. it marks the error with a red bloc!
visitor Winput (*rype ¥ it
repeat GHEE visiror =":
input ("type you see a bird *)
total = total = 1
print (total) [demas
enn
oa
e dn sppe jie 3] :SurmiuesBoigNot using indent
In Python, commands inside a loop are indented. Python adds the indentation
automatically. But Stefan made a mistake - he removed the indentation
Here is the error message he saw:
total = 0
The error message says ‘expected an indented visitor = input("type ¥ if you sed
block. That helped Stefan to understand what was while visitor
wrong with his program. input (" 1
total = total + 1
Leaving out the colon print (total)
Lots of Python commands end with a colon (two
dots). Here are some examples.
if answer == 12:
for i in range (15):
while answer > 9:
Ifyou leave out the colon the program will ial =
.g0 wrong. Kamal made this mistake. Here is
the error message that he saw. The red block
shows where the errors. Kamal could see
what was wrong and fix the problem.
visitor = input ("type ¥ if you see ab
while visitor == "Y"
visitor = input ("typq See
total = total + 1
print (total)
Using a single equals sign
The equals sign is used in Python for two
different things:
> To assign a value to a variable use a single equals sign =.
> Tomakea logical test use a double equals sign ==.
Milan decided to make a variable called visitor. The user of the program will
type'Y’ every time they see a bird visitor to the bird feeder.
‘The next command includes a logical test. It tests whether the variable visitor
holds the value 'Y’
while visitor == "y"
Milan forgot to use the double equals sign in his
logical test. This is the error message he saw.
Milan wasn’t sure what had gone wrong, He
total = 0
visitor = input("type Y¥ if
while visitor "Y":
you see a
had used the equals signin other parts of the visitor = input ("t|?°™" “1 se
program. Why was that equals sign wrong, but ~ tabal ~ fared 410 i ae
all the others were correct? Mr Shakirreminded Print (total)
Milan about how to use the equals sign in c=
Python. Then Milan was able to fix the error.OI
1 Here isa plan for the completed Bird Counter program. Copy and complete the
table. Fillin the correct Python code for every line of the plan, Watch out for
syntax errors.
on a
Set the total to 0
Input the variable visitor
Loop while visitor holds the value ‘Y”
‘Add one to the total
Input the variable visitor again
Print out the total
2 you have not done it already, make the Bird Counter program in Python.
The program will count the number of bird visitors to a bird feeder.
3. Write a note to users of the Bird Counter program. You can use a word
processor or write the note by hand. Your note must explain:
a what the program does
b what to type if you see a bird visitor to the bird feeder
€ what to type when you wantto stop recording bird visitors and see
the result.
(>) Extra challenge
In Activity 3, you wrote a note to users of your program. Now change your
program so it will display this information on the screen. Add print commands
to do this.
Why is showing this information within the program better than putting it in
a separate note?
n=
Make a resource to teach students about syntax errors. You could createa
poster, a presentation or even a video.
orm
1 Syntax errors stop the computer from translating the program. What does
‘translating the program’ mean?
2. Name one place in a Python program where you mustinclude a colon.
3 Text colour can help you find errors in your Python programs. Give one example.
4 Inyour own words, explain the difference between a single equals sign and a
double equals sign in Python,
e dn sppe je 31 :6unmwesBoudExtend the project
In this lesson
You will lear:
> how to spot logical errorsin a program
> how to check that a program works as you intended.
Logical errors
In the last lesson you learned about syntax errors. Ifa program has syntax errors
the computer cannot translate the program into machine code. The program will
not run. The computer will show you an error message.
Intthis lesson you wi
logic of the program is wrong, The program works but it does the
wrong thing. it does not meet the requirement.
It can be hard to spot.a logical error because:
> Youcan run the program.
> The computer executes all the commands.
> Youdon't see an error message.
Anew purpose
Inthe last lesson, some students made a Bird
Counter program to count the number of birds
visiting a bird feeder. The program works like this:
> Ifa bird visits the bird feeder, type the letter "
> The count goes up by one.
Mr Shakir's students shared the Bird Counter program with
‘students in another school called North Mountain School. This
schoolis in a colder country. In that country lots of birds visit the
school bird feeder, especially during the winter.
‘The students at North Mountain School found it difficult to use
the Bird Counter program made by Mr Shakir’s students. The Bird
Counter program records bird visitors one ata time. But at North
Mountain School the birds arrive at the feeder in groups. The
students decided to make a new program,
Discuss and plan
The students discussed how they wanted the new program to
work. They wrote the requirement for their program:
The students decided to call their program the Bird Addition
program,
learn about logical errors. A logical error means that the
Program requirement
> Each student will watch
the bird feeder for one
minute.
> They will count how many
birds visit the feeder in
one minute
> They will enter that value
as a number.
> When all the students
have entered a value, the
program will output the
total.OI
Before you go any further, try to make the Bird Addition program to meet the
program requirement.
Input a number
In the old Bird Counter program, the user enters the value
the new Bird Addition program, the user enters a number.
they see abird. In
The students at North Mountain School made several changes to the program:
> Instead of havinga variable called visitor, the variable is now called
visits. The visits variable will store the number of visits to the bird feeder.
> Theuser promptis different - it reminds the user to enter a number.
> The input that the user enters must be changed to integer data type so it can
be used in calculations.
Here is the program with these changes made. total = 0
Visits = toput (renter the nukber iter)
‘The program dossnokwmorkyst visits = inttvisits)
This program has several problems. Canyouseethe —.¥ieHS To me
problems? If you are not sure, enter this code in a Visits = int(visite)
Python file and run the program. Does the program an
run? Does the program meet the requirement?
Exit condition
The program has a while loop. The logical testis:
visits == "y"
This does not work. In the new program, the variable visits stores a number
not a letter so the logical test is never True. The commands inside the loop never
happen.
The students decided to change the exit condition. The loop will continue if the
number of visits is anything but 0. Ifthe user enters the number 0 the loop will
stop. The new testis:
visits I= 0
The students ran the Bird Addition program. The total = 0
program started and the commands inside the loop oe oe "
were repeated. But when the students used the ville visits I= 0: .
program to record visits to their bird feeder, they icmia€, ai)
founda problem. Sometimes no birds visited the bird total = total +1
feeder. The userhad to input the number 0. But when (E84)
they entered 0 the program stopped.
That is because when the value of visits is0 the testis False, so the loop stops.
Inthe next activity you will ind out how to solve this problem.
=) dn sppe je 3] :6urmiuesBoigBee husd aeGead
Change the exit condition
The students need to change the logical test:
> The logical test has to be a number comparison.
> The number has to be one that will never be a real number of birds.
For example, the students could choose a
negative number. Instead, they chose the
number 99. If the user types 99° the loop
will stop. The students know there will
never be 99 birds at the feeder.
But the Bird Addition program is sill not
ready. Can you see why?
Add up the visitors
The program has to add up the total
number of birds. At the moment the
program adds just one to the total every
time the user enters a number.
‘The students changed the Bird Addition
program so that it adds the number of
Visitors to the total.
total = 0
visits = input ("enter the number of visits")
visits = int (visits)
while visits != 99:
visits = input ("enter nunbe
visits = int (visits)
total = total +1
print (total)
x of visits")
total = 0
visits = input ("enter
visits = int (visits)
while visits != 99
visits = input ("ente
visits = int (visits)
total = total + visits
print (total)
he number of
number of visit
But this program is still wrong! Can you see why? If you are not sure, enter this,
code in a Python file, then run the program, What goes wrong?
Change the order of commands
There are two problems:
> The first input value is NOT added to the total (the one that is input before
the loop starts).
> The final input value IS added to the total (the value 99).
‘To avoid these problems the students reversed the order of commands inside
the loop:
First add the input number to the total.
Then enter a new number.
When the user enters the exit value (99),
the program stops right away. Here is the
program with that change made.
This program works! The students have
found and fixed all the logical errors.
total = 0
visits = input ("enter the number
visits = int(visits)
while visits != 99:
total = total + visits
visite = input ("enter number of visits")
visits = int (visits)
print (total)
of visitOI
Ifyou have not done italready, make the Bird Addition program. It should add up
the total number of birds that visita bird feeder.
[) Extra challenge
‘Some students chose to make a different program, with a counter loop. There
were 20 students in the class so they used a counter loop that counted up to 20.
Write a Python program that does this.
or
1. Whyisit harder for a programmer to spot a logical error than a syntax error?
2 Lookat the addition program you made. What would happenif the li
‘otal = 0 were included inside the loop?
3. Write a Python program that adds together five numbers input by the user.
ORES
Errors that stop programs working properly are called ‘bugs? Software companies
test their programs for bugs before they offer them for sale. Ifa program is used
for fun — for example, a game — a few bugs in the code don’t matter so much.
But some software programs are very important - for example: software in a
hospital that measures a patient’s heart rate; software in a factory that controls,
a dangerous chemical reaction; software
ina bank that looks after the customers’
money. These programs must not include
any mistakes.
One day you may be a programmer who
writes important software. Or youmay
work ina hospital, factory or bank and use
important software. You will need to make
sure that the software program has been
thoroughly tested so that the software
is reliable.
e dn sppe je 31 :6unmwesBoud®
Readable and user friendly
In this lesson
You will lear:
> how to make your programs user friendly
> how to make your programs readable.
Make user-friendly programs
Users like programs that are user friendly. That means the programs are easy to
use. Some things that make a program easy to use are:
> simple inputs with prompts
> clear outputs ‘pe the numberof bra
> other messages to explain the program. +
‘The program commands that handle inputs and outputs we SF
are called th terface. The user enters inputs through the
interface. The user sees the outputs displayed in the interface.
When you program in Scratch itis it easy to make a
user friendly interface. On the right is an example.
The Scratch interface includes colourful backdrops and sprites. But Python only
has plain text. The interface isnot so user friendly. In this lesson you will learn to
make a Python program with a more user-friendly interface.
The interface of your program
You made a program to count visitors to a bird feeder. This iswhatthe enter number of visits?
user sees when they use the program. enter number of visitsS
enter nunber of visits?
This program is not very user friendly. itis notclearwhat inputs are enter number of visits99
needed or what the output means. Now you will improvethe program. 16
Simple inputs and prompts
You need to make it easy for your user to enter the right inputs. Here are
some tips:
> Make the input short and simple to enter. For example, ask the user
to input °Y’ instead of ‘Yes’. This is less work for the user. There is less
chance of an error.
> Add a prompt. The prompt is the text inside the brackets. It tells the
user exactly what they should enter. This means the user feels less.
stressed. It will help the user to avoid making an error.
> Ifyou include a space at the end of the prompt, the interface looks
better. There isa space between the prompt and what the user enters.Here isa bad input command:
continue = input("continue?")
Here isa better version:
continue = input("do you want to continue? (Y/N) ")
Which makes itclearer what you have to do?
Clear outputs
Most programs end with an output. It might be a number, such as the total
number of birds seen. To make your programs user friendly, add some text to the
print command. That helps the user to know what the output is.
Here is a bad output command:
print(total)
Here isa better version:
print("we saw this many birds", total)
‘The explanation and the variable are separated by commas.
Other on-screen messages
Use the print command to add messages Count tho nunbor of visits to the feoder, Time yo
toyour program.Forexample,youcanadda | {0"you"eype 135" the prooram wil stop.
title and explain what the program does.
The students changed their program to make Gat ae eee
2
Visits in one mimte:
3
the interface more user friendly. Visits dn one ainute:
Vieits in one mimite: 99
Other useful print commands The total number of visits was: 16
Here are some other print commands that
are useful for this activity.
Include "\n" in a print command to make a new line:
print("\n")
Use the multiplication’ operator to repeat a symbol. This command will print
ten dashes:
print("-"* 10)
OI CEI
Open the Bird Addition program. Add extra Talk to family and friends about what apps and
features to make it more user friendly. programs they find easiest to use. What makes a
program ‘user friendly’? You might find that different
people want different types of software. f you have
time, write a report on what you have found.
8 dn sppe je 31 :6unmwesBoudCee iC ear
Make readable programs
Programmers like programs that are readable, That
means the program itselfis easy to read and understand.
Often, more than one programmer works on the same
program. Making readable programs is good for teamwork.
Making your programs readable will help you to be a better
programmer. When you come back to your work, you will
find iteasy to remember what you did. You wil find iteasy
to improve and change your program. Creating readable
programs helps everyone.
Two things that make a program easy to read are:
> well-chosen variable names > comments.
Variable names
You have learned how to make good variable names. The name of a variable
should tell you what value the variable stores. When other programmers look at
your program they will understand your work.
This code is not readable because we don’t know what the variable x stores:
input ("value")
This code is much more readable because itis clear what the variable
cost stores:
cost = input("enter the item cost ")
Comments
Comments are messages you add toyour this program xecords totel visits to « bird feeder
program. In Python you mark a comment fora
with the hash symbol #. 4 auenay she vor Antertace,
‘Any text that you enterafter the # symbol is
not part of the program. The computer will
see the # symbol in your code. It will ignore _ =
the rest of the line. But other programmers
will be able to read the comment. You can =a
use comments to add explanations and Se
other messages about your program. That sn. vette to gor
will make the program more readable. wise et Vt = cimter *)
Some students decided to make the Bird
Addition program more readable. This is oe ee cass peony
what the program looked like.
OI
‘Add features to improve the readability of your program.Take the program to a new level
Mrs LI is a new biology teacher at North Mountain
‘School. Sheis very keen on studying birds. She
wants to use the program the students had made.
But she asks for an extra feature:
> “Can the program tell me the average number of
birds that arrive in one minute?”
The students adapt their program to meet Mrs Li's
requirement.
Calculate an average
The program has to calculate the average of a series of numbers. To calculate an
average you need to know two things:
> the total of all the numbers added together
> the count of how many numbers there were in the series.
The averageis the total divided by the count.
Discuss and plan
‘The students were confident they could do this task. They hada discussion to
plan the program. Here are some things they sai
> “Weneed a new variable called count or counter that starts at 0.”
> “This variable will go up by one every time the user enters a number.”
> “Atthe end, we can use this variable to calculate the average.”
oO Extra challenge
1 Adapt the program to calculate the average number of bird visitors. Use the
students’ comments to help you make these changes.
2. Make sure the program is readable and usable.
or
1. Say one way that Scratch is more user friendly than Python.
2. Hayley wrote a command to print a variable. How can she change the print
command to make it more user friendly?
3. Why do well-chosen variable names make your programs more readable?
4. Explain how adding comments to a program might help you next time you
work on the program.
8 dn sppe je 3] :6urmiuesBoig