Introduction To Programming Using Python
Introduction To Programming Using Python
using
PYTHON
written by
Joe English
Preface
These notes have been compiled over the past number of years in response to the
need for a textbook that meets the requirements of the QQI level 5 award in
Programming and Design Principles.
The content is inspired by past students – who, just like yourself were total beginners
when they started. From experience, I can tell you that if you work at this subject
you can do very well and open up many doors for yourself in terms of career
opportunities and progression towards a degree and beyond.
Learning to program is not too difficult but does require a fair deal of commitment on
your part. You are expected to attend all classes on this course and most importantly
you are also expected to spend a good deal of time working on this subject outside
class contact time. Programming is a very time consuming activity. As a general guide
I would suggest an hour outside class for every hour you spend in class.
Throughout these notes there are lots of examples followed by related exercises.
Many students will find it helpful if they read the examples first before attempting
the exercises.
The best way to learn is by ‘doing’. Try the examples and exercises. If something
doesn’t work or you cannot complete an exercise ask someone (e.g. classmate, tutor)
for help. Do not worry if you don’t understand everything completely the first time
you try something or if you make mistakes. The important thing is to learn from your
mistakes and move on.
Finally, I would like to take this opportunity to wish you the very best of luck in the
year ahead. Seize the day and remember practice, practice, practice!
Joe English.
Computer programming is the activity of writing computer programs. Programs are written
using a special language called a programming language. There are hundreds of different
programming languages - examples include Java, C, C++ (pronounced C plus plus), Python,
Ruby, COBOL and Visual Basic.
It is very important to bear in mind that the purpose of programs is to solve problems – specific
problems such as a payroll, word processing, airline reservation, book lending (as used by
libraries), accounting, games, Automated Teller Machine (as operated by banks), patient
tracking (as used by hospitals), social networks (e.g. Facebook) and so on. These are all
examples are of real world systems. The list of problems that have been solved by computer
programs is long and varied.
In reality a computer system is made up of many computer programs. Each program does a
specific task and together all these programs make up the system (i.e. the solution to the
original problem).
Before a computer system can be written the problem to be solved must first be fully
understood. This task of getting to understand a problem is called system’s analysis. The
exact details of what the system will do are decided during the analysis phase of software
development. Once we know what the system will do, we then must decide how the system
will work. This is called system design. It is during the design phase of a project that the data
to be input into the system, screen layouts, data to be generated by the system, reports,
database and data processing are all decided. Programming (i.e. coding) can begin when (and
only when) the system has been fully designed.
Clearly, one must learn a programming language before they can write code. The best way to
learn a language is to practice using it. Once a person has mastered a programming language
they can use that language to solve problems. In other words, the programming language is
just a tool used to write computer systems that do something useful.
Learning a new programming language is not difficult. In fact, it’s much easier to learn a
programming language such as Python or Java than it is to learn a natural language such as
French, Spanish or even English. For a start the vocabulary of a natural language is much,
much larger than that of a programming language – most programming languages have fewer
than 50 words. Compare this to the number of English words you know. When we construct
sentences using the vocabulary of a natural languages there are certain rules we have to
follow. These rules make up the grammar or syntax of the language. Every language
including programming languages have their own syntax. One of the main differences between
learning natural languages and programming languages it that once you have mastered one
programming language it is easier to learn another. This is not to say that all programming
languages are the same. However, there are more similarities between Python and Java for
example, than there would be between English and Irish.
The main aim of this course is to provide the knowledge necessary to develop small computer
programs. Hopefully, you will learn how to:
A. analyse problems
B. design solutions
C. implement (write code) solutions using the Python programming language
D. test these solutions
An end-user is the person (or organisation) for whom a software system is developed.
Certain software systems such as games, operating systems, office applications etc., are
developed with the general public in mind as the end-user. These systems are sold as ‘off
the shelf’ packages in computer stores. Other software systems – called bespoke systems
– are developed specifically for a client company.
It should be clear that there is no need for a typical end-user to understand how to write
computer programs to solve problems. End-users with an understanding of computers,
however, may be well positioned to explain their requirements to a computer programmer.
A programmer is a person that writes the code that make up a computer system.
Programmers are usually employed by software houses i.e. a company whose primary
activity is software development. The business of a software house in the production of
software whereas the business of an end-user is related to the area which the software is
aimed at e.g. banking, insurance, finance, travel, health etc. It is worth noting that some
organisations (usually large) employ software professionals to develop their own in house
software. In any case, programmers can be employed on a permanent or contract basis.
Throughout this course you will have to alternate your role between that of programmer and
end-user. As a programmer you will solve problems with Python code and as an end-user
you will verify that the program works by using it.
Finally, it is worth providing a cautionary note before diving into the world of Python. As a
novice programmer, it is necessary to build up experience by using Python to solve small
problems that are sometimes academic in nature i.e. problems for the sake of learning.
Many of the examples and exercises contained in this text are for educational purposes.
They are designed so that you can improve your problem solving skills and learn certain
aspects of Python. In reality, most commercial computer systems are complicated in nature
and can take months and even years to write (so be patient – you’re just beginning and here
to learn!)
This is the software that you will use to type in and run your Python programs….
Download version 2.6 from https://sourceforge.net/projects/pyscripter/
IDEs themselves are a software application (tool) and as such there are many available –
both free and to purchase - on the market. Some IDEs are designed to work with specific
programming languages and some are more general. Microsoft Visual Studio is an example
of a general IDE. It is used by professional programmers to develop applications in Visual
Basic, C and C++ among others. Eclipse and NetBeans are other examples of IDEs
commonly used to develop Java applications.
Summary
Programmers write code. End-users use the system.
End-users come up with problems that sometimes can be solved by computer systems.
Programmers develop these systems.
Programmers work for the end-users. This is because the end-user is the programmer’s
customer and therefore pay master.
The first thing we do is start PyScripter. The following screen is displayed - the most
important parts of the window are highlighted.
Before keying in any code I usually start off by clearing the code area. This can be done by
using the ‘Backspace’ or ‘Delete’ keys but I usually press Ctrl+A and then Delete.
It is also useful to turn on line numbers. The option to do this is on the top line.
When you have the program area cleared and line numbers turned on the screen should
look something like the one below – a programmer’s blank canvas!
print("Hello World")
Recall, the objective is to display the message “Hello World”. The program area should now
look something like this:
Run the program by clicking on the green arrow ( ) to see what it does. You should see
the message appear on the bottom of the screen.
Congratulations! You have just written and run your first Python program.
The next thing to do is to save the program. To do this choose the File->Save option. Use
the dialog displayed below to browse to the destination folder. (I usually place my files in a
folder called ‘src’ for source.). Choose an appropriate name for your programs.
It is important to keep your source files well organised on disk (I recommend using Cloud)
and save your programs (by pressing the control key and S at the same time i.e. Ctrl+S)
frequently as you work.
After you have saved your program close PyScripter. As a test to yourself see if you can re-
launch PyScripter, Open (using File->Open) and run the “Hello World” program. Once you
can do this confidently you are ready to start writing more programs.
print("Hello World")
Python – like every programming language - is very fussy about the way you type in your
code. You need to be careful. If you make a mistake Python will not understand and display
a syntax error.
Syntax Errors
The syntax of any language (including natural languages) refers to rules regarding how
statements and expressions (sentences) in that language can be correctly constructed.
When you try to run a program that has a syntax error Python displays an error in a
message box. Sometimes these messages are difficult for programmers to understand but
with time and practice you will get used to them.
KEY POINT: When you see a syntax error you need read it carefully and then click ok to
make the message box ‘go away’ and then correct your code so that the error won’t appear
when you try to run it again.
We will now take a look at some of the basic syntax rules of Python and illustrate what
happens when these rules are broken.
Rule 1: Python is case sensitive. Upper and lower case letters are different. Lowercase
letters must be used for Python commands. Try running the following:
Print("Hello World")
The code contains an error and so when you try to run it the following error message is
displayed.
Read the error text carefully. This error is caused because Python does not understand the
name ‘Print’. To correct the error you would need to type print using lowercase only.
print("Hello World")
Notice that Python does not care too much about what we put between the quotation marks.
print(Hello World)
To correct the error you would need to insert the quotation marks.
Rule 3: You should always use brackets after the print command. Furthermore, for every
opening bracket there needs to be a matching closing bracket. The following line causes a
syntax error to be displayed
For the moment it is best to assume that there should be no spaces before any line of code.
Notice in the code below that there is a space before the print command. This causes an
error to be displayed when you try to run the program.
To correct the error you would need to remove the space from the start of the line.
As a final point it is worth noting that just because a program does not contain syntax errors
is no guarantee that it will run properly. Syntactically correct programs can contain errors
(sometimes called bugs). Programs that contain bugs do not work in the way they are meant
to work. Such programs are called semantically incorrect.
a) PRINT("Hello World")
b) print("HELLO WORLD")
c) print("Python is fun!")
d) print"(Hello World)"
e) display("Hello World")
f) print(My name is Sam)
g) print(("Hello World")
h) print("This text has plenty of spaces")
i) pint("Hello World")
j) print("99 red balloons")
k) print(99 red balloons)
And finally,
Python is not too fussy about what you type inside quotation marks. Outside quotation marks
Python is very limited in what it understands. One of the things Python understands outside
quotation marks is numbers. Numbers do not have to be enclosed inside quotations.
KEY POINT: The technical word for text is string. A string is a sequence of characters
enclosed inside quotation marks.
Notice from the last two examples how multiple strings can be separated by commas.
As before we open PyScripter and clear the code area. You should see a screen like this.
The code area on the screen should now look something like this.
Now run your program (remember, use the green arrow ) and you should see the poem
displayed in the output area of the screen.
Programmers must train their brain to run their programs in the same way as the computer.
The flow of control means the order in which the lines of a computer program are run by the
computer. For the moment we will assume that the flow of control is sequential. This means
that program execution begins at the first line and ends at the last line. Every line in between
is executed in the same sequence as they appear in the program.
To illustrate this we will ‘step through’ the execution of our ‘display poem’ program:
When this line is executed the output console displays the string As I was going out one day
Program execution continues in a sequential manner until finally the last line (in this case
line 4) is executed.
Recall, that this was what we wanted the program to do (i.e. display the poem). We can
verify that the program works by comparing the actual output to what we expected.
It is very important to realise that although the programs run very quickly by the computer.
This gives the illusion that the output is displayed in one step. The reality however is that the
output is built up on a line by line basis as each individual line of code is executed.
Challenge
Extend the ‘display poem’ program to show the following 2nd verse
print("Knock knock.")
input()
print("Who's there?")
input()
print("Doctor.")
input()
print("Doctor who?")
input()
print("How did ya guess!")
Don’t forget to save your program somewhere you will be able to find it later. Call it
something relevant e.g. KnockKnock.py.
Notice that the input() command causes the following screen to appear in PyScripter.
You need to press enter (or click the OK button) to make this screen disappear. Program
execution continues each time at the next line of code.
Take a careful look at the output console each time the above screen is displayed. What do
you notice?
1. print(" #")
2. print(" ###")
3. print("#####")
4. print(" ###")
5. print(" #")
Answer. Line 1 causes two spaces followed by the "#" (often called the hash or pound
character) to be displayed. Line 2 displays a space followed by three hash characters. Line 3
displays five hash characters. Line 4 does the same as line 2 and line 5 the same as line 1.
The overall effect is to display the following pattern on the output screen:
KEY POINT: You will learn Python faster if – every time you come across a program listing
you haven’t seen before - you take some time to study it and try to figure out what the
program does.
1. print("####") 1. print("####")
2. print("# #") 2. print("# #")
3. print("# #") 3. print("####")
4. print("####") 4. print("#")
5. print("#")
2. Can you spot the syntax error(s) in each of the following code snippets?
Hint: you should start by typing the code into PyScripter, and you will see the syntax
error highlighted when you run the code. Can you correct the errors?
PROGRAM 1
1. print["Knock knock."]
2. print("Who's there?")
3. print["Doctor.")
4. print "Doctor Who?"
5. print("How did ya guess!"]
PROGRAM 2
PROGRAM 3
1. print("Knock knock.")
2. input
3. input
4. input
5. input
6. print("Sorry for delay!")
6. Re-arrange the lines of code below into a program that displays the pattern shown on the
right. Note that you can use any line as often as you like but you won’t need to use every
line.
a) b) c) d)
###### ###### ###### # #
# # # # #
# ###### ###### ######
# # # # #
###### ###### # # #
e) f) g) h)
# ####### ####### # #
# # # # # #
# # # # # #
# # # # # #
####### ####### # ######
8. By using the code you just wrote, write a program that outputs the letters LOFT (one
letter underneath the next).
9. The following three programs all result in the same output being displayed. What does
this tell you about the print command?
Functions (Part I)
A function can be thought of a sub-program that does a specific job for the programmer.
Computer programs typically contain many functions. Functions are important and useful
because they are re-usable. Every function definition is made up of a header and a body.
The header is always the first line – it always starts with the word def followed by some
name chosen by the programmer followed by brackets and a colon.
The name of the function shown below is displayPoem. The body of this function contains
four print statements. Notice that the statements appear further to the right than the
header line. This is called indentation. In Python, the statements inside a function body
must always be indented.
def displayPoem():
print("One fine day in the middle of the night,")
print("Two dead men got up to fight,")
print("Back to back they faced each other,")
print("Drew their swords and shot each other.")
To execute the code inside a function body, a programmer must write a line of code to call
the function. To call a function just type the name of the function followed by brackets.
displayPoem()
In a Python program the code to define a function must appear before the code to call it.
When a call is made, the flow of control jumps to the first line of the function body and
execution continues from that point until the last line of the function body has been executed.
At this point the flow jumps back to the point from which the call to the function was made.
The screenshots on the next pages illustrate the flow of control as this simple program is
executed. Whatever line is being executed by Python is highlighted in red in the
screenshots.
Line 8 calls the function displayPoem. Note the use of brackets. The flow of control jumps
to line 2.
The change in indentation tells Python that line 5 is the last line of the function. Once line 5
has been executed the flow of control returns to the point from where the original function
was called i.e. line 9.
Line 9 is executed and the program terminates as there are no more lines left to execute.
The final message displayed is:
Key the code in to make sure it does what it is meant to do. (Be careful to get the number of
spaces correct on lines 3 and 5!)
The program is quite simple. Five calls to print()and voila – job done!
Let’s look at an alternative solution – this time using a function called draw365.
This solution is better than the first because it is more modular. Recall, a function is a sub-
program that does a specific task. In this case, the task is to display the ‘365’ pattern, and
so, by writing a function to do this we are making the system more modular.
A modular system is one in which there is a separate function defined for each separate task
system performs. Writing modular code is considered good programming practice. It is
achieved by breaking larger blocks of code into smaller blocks of related code through the
use of functions. The initial solution is said to lack modularity.
The advantage of the second solution is that it just takes a single line of code (i.e. a call to
the function draw365) to draw another ‘365’ pattern. In effect, we are re-using existing code.
We will return to the important topic of code reuse at a later stage.
Finally, it is worth noting that print is a special type of function called a built in function.
This is because it is built into the Python language. In contrast, functions we define
ourselves are called user-defined functions.
PROGRAM 1 PROGRAM 2
What logical difference, if any, exists between the two listings? Explain your answer.
Explain the syntax error you get. How can the error be fixed?
7. What happens when you run the code below? How can the problem be fixed?
8. The program below displays a little known limerick written by Edward Lear entitled There
was an old man of Nepaul.
Write a function called nepaul to display
the limerick. Don’t forget to call the function.
Let us say we were asked to write a program to display the poem shown below (adapted
from Dr Seuss’s classic Green Eggs and Ham)
1. def showChorus():
2. print("I do not like green eggs and ham.")
3. print("I do not like them Sam-I-am.")
4. return
5.
6. showChorus()
7. print()
8. print("I do not like them here or there.")
9. print("I do not like them anywhere.")
10. print("I do not like them in a house")
11. print("I do not like them with a mouse")
12. print()
13. showChorus()
14. print()
15. print("I do not like them in a box")
16. print("I do not like them with a fox")
17. print("I will not eat them in the rain.")
18. print("I will not eat them on a train")
19. print()
20. showChorus()
Hopefully, you can see that this program displays the same output. Execution starts at line 6.
The function showChorus is useful because it is re-used.
However, the above program still lacks modularity. A more modular solution is shown below:
1. def showChorus():
2. print("I do not like green eggs and ham.")
3. print("I do not like them Sam-I-am.")
4. return
5.
6. def showVerse1():
7. print()
8. print("I do not like them here or there.")
9. print("I do not like them anywhere.")
10. print("I do not like them in a house")
11. print("I do not like them with a mouse")
12. print()
13. return
14.
15. def showVerse2():
16. print()
17. print("I do not like them in a box")
18. print("I do not like them with a fox")
19. print("I will not eat them in the rain.")
20. print("I will not eat them on a train")
21. print()
22. return
23.
24. showChorus()
25. showVerse1()
26. showChorus()
27. showVerse2()
28. showChorus()
The use of functions to do specific tasks make the program more modular. Modular code is
the result of good design.
a) Write a three line program (without using functions) that displays following output.
c) How would you modify both programs so that the output displayed is as follows?
2. Design and write two functions to display the verses below. (Call them verse1 and
verse2).
The cabbage is a funny veg.
All crisp and, green and, brainy.
I sometimes wear one on my head
When it’s cold and rainy.
Now design and write a single function (call it displayVerses) that calls the functions
you have just written. Call displayVerses. Explain why the program is modular.
4. Fill in the blanks below so that the program will display the same output (as the program
in the previous question)
6. Design and write a modular program to display the following 2 verses of the well known
poem Humpty Dumpty. Your solution should not have any duplication.
Note
The # symbol tells Python to ignore the text that comes after it. It is called a comment.
Explain the main benefit of the function printChorus in the above program.
Now, use the space provided to the right below to write the code necessary to produce the
outputs shown on the left.
Code
Desired Output
(write your code here)
a)
b)
c)
d)
a) Now key the program in and run it. Compare the expected output with the actual
output. Is the actual output the same as the expected output? What does your answer
mean? If the actual and expected output were different what would it mean?
b) How would the output of the program be altered if lines 7 and 12 were removed? Try it.
c) What do you think it would be a bad idea to insert a call to the function bar() inside
the function foo()? Don’t try this!
d) Make the changes necessary so that following outputs are generated. Answer each part
separately and in turn.
365 Solution 1
The first implementation is the simplest. Five calls the print() function and voila! However
this solution lacks modularity. If (for some reason) we need to have the ‘365’ pattern
displayed more than once then we would need to duplicate these lines elsewhere in the
program. By now we should know that duplication of code is bad practice and should be
avoided. The best way to avoid this situation is to use a function.
365 Solution 2
The above implementation has the advantage that the functionality to display the pattern is
now contained in a user defined function called, draw365. Anytime, the programmer needs
to have the ‘365’ pattern displayed he/she just needs to call this function.
At this stage there would appear to be little room for improvement on this solution. However,
if you look closely you should notice that three of the lines (lines 3, 5, and 7) are identical.
These lines all do the same thing i.e. display a line of hash tags. This is code duplication
and, as before can be avoided through clever use of functions.
Our third and final implementation includes a new user-defined function called
displayLine. This simple little function just displays a horizontal line of # symbols and is
called three times inside the other user-defined function draw365.
Although, this solution does not seem to be as obvious or simple as the earlier
implementations, it does incorporate better design techniques. Better design techniques lead
to better code because the resulting systems are easier (and cheaper) to maintain. Such
systems are said to be robust and extensible.
We now write our own user defined functions to display these patterns.
Our next task is to use the above functions to draw the actual digits. We define our own user
defined functions to draw the digits themselves. As an example the following code draws the
digit zero when called.
Finally, to display zero as output we just call the function drawZero() as follows:
Exercise 3:
1. Key in the above code (all 26 lines) and run the program. What does it do?
2. Now, write additional functions to display the other 9 digits.
(Hint: You will need to define and call one function per digit. Do them one at a time. Each
function will contain 5 lines followed by return.)
Imagine each block was represented by a ‘#’ character. Now key in and run the code below.
1. def hash():
2. print("#")
3.
4. def blankHash():
5. print(" #")
6.
7. def hashHash():
8. print("##")
9.
10. def blankHashHash():
11. print(" ##")
12.
13. blankHashHash()
14. hashHash()
15. blankHash()
Hopefully, you see that the output displayed is meant to be shape labelled F. How could the
code shown be made more modular? (Hint: put lines 13-15 in a separate function.)
Is there any shape you cannot draw? If so, write the code!
i) j) k) l)
####### ####### ####### # #
# # # # #
# ####### ####### #######
# # # # #
####### ####### # # #
m) n) o) p)
# ####### ####### # #
# # # # # #
# # # # # #
# # # # # #
####### ####### # #######
By using the code you just wrote, write a program that outputs the letters LOFT (one letter
underneath the next).
Read the notes below and then type the above program in. Make sure to save (call it
Shapes1.py) and test as you go.
Notes:
i. You need to be careful with the amount of leading spaces you use on lines 1, 2, 5
and 6
ii. The character used in the print statement on line 1 is an underscore
iii. In order to print a single backslash (‘\’) character you must precede it with another
backslash inside the string (i.e. ‘\\’). This is known as an escape sequence.
Once you have the above program working improve the design as follows:
b) Remove duplication.
Hint: You will need to examine the shapes very closely and look for patterns that occur more
than once. Write a separate function to display each re-usable part. Your functions to display
the actual shapes will call the functions that display the parts of the shape. Call this program
Shapes3.py.
Diagram 1 Diagram 2
Diagram 3 Diagram 4
Diagram 5 Diagram 6
Diagram 7
1. A function is a piece of re-usable code that performs a specific task (as such they do not
normally contain too many lines)
2. Functions are the building blocks of programs. A modular program is usually made up of
many functions. If used properly, programmers can use functions to avoid code
duplication.
3. When you write more than one function in your program use blank lines to separate them
from each other. This makes your program more attractive and easier to read.
4. The code to define a function must appear before the code that calls it.
5. A function definition is made up of a function header (aka signature) and function body.
6. The function header must start with the Python reserved word, def followed by the name
of the function, followed by brackets and finally a colon
8. Function names must be unique i.e. no two functions can have the same name
9. Function names should be meaningful i.e. they should in some way describe what the
function does
10. As a matter of style I usually use a lower case letter for the first letter in a function name.
Any full words contained in the function name should start with a capital letter
11. In Python, the lines of code in the function body must be indented.
12. A function is called (invoked) in a program simply by using its name (followed by
brackets)
13. When a function is called the flow of control jumps to the first line of the function.
Execution continues by running the function body. Once the body has been executed,
the flow of control is returned to the line where the function was called in the first place
15. Some functions are built-in as part of Python (e.g. print and input) and some
functions are defined by the programmer. User-defined functions can be thought of as
special commands developed by programmers for use in their programs.
16. There’s a lot more to learn about functions but that’s enough for the moment!
1. firstNumber = 1
2. secondNumber = 2
3. sum = firstNumber + secondNumber
4. print("The answer is", sum)
Answer: The program adds the numbers 1 and 2 and displays the result in a message.
We will now walk through the program - line by line. We start with line 1.
The variable secondNumber is declared and initialised to 2. After executing line 2 the
computer’s memory looks like this:
At this stage the programmer has declared and initialised two variables - firstNumber and
secondNumber.
Both variables are now know to Python and therefore can be used in subsequent lines of the
program.
Python always evaluates the right hand side of an assignment statement first
In this case Python evaluates firstNumber + secondNumber and gets 3.
The result of the evaluation is stored in the variable named on the left hand side
So, 3 is stored in sum.
The right hand part of an assignment is called an expression. Some expressions are literal
values (as in lines 1 and 2) and some expressions are arithmetic (as in line 3).
Operator Operation
+ Addition
− Subtraction
∗ Multiplication
/ Division
This line is a print statement and it causes the message, The answer is 3 to be displayed.
Notice that the variable sum is not included between the quotes and that the value of the
variable (i.e. 3) is displayed, in place of the variable name, in the output.
1. firstNumber = 1
2. secondNumber = 2
3. sum = firstNumber + secondNumber
4. print("The answer is", sum)
The program is useful – not because it adds 1 and 2 (we already know how to do that!) –
but, because it teaches us the concepts of variables, assignments and expressions.
Finally, it is worth noting that the following four programs do exactly the same thing. In other
words, these programs are logically equivalent.
PROGRAM 1 PROGRAM 2
PROGRAM 3 PROGRAM 4
1.
2.
The second example uses 4 variables – days, hours, mins and totalMins – and 4
assignment statements. Line 5 is a print statement.
A variable cannot be a word already reserved by Python (e.g. “print” “def”, etc.)
Variable names must contain only letters, digits, and the underscore character, _.
Variable names cannot have a digit for the first character.
Spaces or dots are not allowed in a variable name
The following syntax error appears when Python comes across a variable it does not
understand. (In this case, the name of the unknown variable is ‘message’.)
Remember that Python is case-sensitive. For example, the variable names ‘ISBN’ and ‘isbn’
are different to Python even though both names are made up of the same letters (in the
same order). Forgetting that variable names are case sensitive is a very common cause of
error to the novice programmer.
Programmer Tips
1. Choose meaningful names for your variables. A meaningful name is one that tells
something about what the variable is used for.
2. Capitalise interior words in multi-word variable names, e.g. lastName, firstName,
stockCount, barCode, and payRate are all good variable names.
Review Exercise
Which of the following are legal variable names?
a) student.Number
b) x
c) 1x
d) x1
e) input
f) number
g) 21
h) h21
i) PPSN
j) ppsn
k) person name
l) address
m) date_of_birth
n) 2+4
1. It is up to the programmer to decide when a variable is needed and what to call it. It is
important that variables are given meaningful names. Take a look at the scenarios below
and suggest an appropriate variable name for each scenario. A variable that stores….
2. A variable is used to store data. As a programmer you need to understand what data
your program needs to process and what variables you need to use.
Identify some data/variables that might be needed by the systems listed below
Choose any variable you identified and explain a situation that might necessitate the value
for the variable to change?
8. Read carefully the following block of code and answer the questions which follow:
1. goals = 0
2. goals = goals + 1
3. print("The value of goals is", goals)
10. Read carefully the following block of code and answer the questions which follow:
1. a=10
2. b=5
3. temp=a
4. a=b
5. b=temp
Now write the code to display the values of sum, difference, product and
quotient
12. Imagine a small banking application. What effect do you think the following fragment of
code has on the value held in the variable accountBalance?
1. accountBalance=1000
2. withdrawalAmount=600
3. accountBalance=accountBalance-withdrawalAmount
13. Let us say a banking application contains a variable called accountBalance which
has a value of €1000. Write a statement (i.e. a line of code) to do the following:
The first rule of thumb is that Python evaluates expressions using the normal rules of
precedence. (Recall BIRDMAS?). Consider the following code snippet.
1. x = 2+3*4
2. print(x)
3. y = (2+3)*4
4. print(y)
Line 2 displays 14 because multiplication is carried out before addition. Line 4 displays 20
because the brackets forces the addition to be carried out before the multiplication.
Variable Substitution
Given two variables, x=2, and y=8 what do the Python expressions shown below evaluate
to?
1. x+y
2. x-y
3. 5*y
4. 5*x+y
5. 3*(x+y)
6. x*y+4
7. y/x+1
8. y/x+y
9. (x*y)+(y/x)
Simply substitute 2 in for x and 8 in for y. Once we do this and follow the normal precedence
rules of arithmetic we can be confident of arriving at the correct answer.
Solution
1. This is just a simple addition, 2 + 8. The answer is 10.
2. This is a subtraction, 2 − 8. We just need to be careful about the sign. The answer is −6.
3. 5 times 8. The answer is 40.
4. This line contains two operations – multiplication and addition. Since the multiplication
has a higher precedence than addition we multiply 5 by 2 first. This gives 10 which we
can now add to 8. The answer is 18.
5. The brackets here forces the addition to be done first. We get 10. This is then multiplied
by 3 to give an answer of 30.
6. This line is evaluated from left to right. 2 is multiplied by 8 to give 16. This is then added
to 4 to give an answer of 20.
7. Here 2 to be divided into 8 first. This gives 4 which is then added with 1. The answer is 5.
8. Again 8 is divided by 2 to give 4, which is then added with 8. The answer is 12.
9. The expressions inside the brackets are evaluated first. The multiplication evaluates to
16 and the division evaluates to 4. Both results are added to give an answer of 20.
9
𝑓 = 𝑐 + 32
5
where, 𝑐 stands for the temperature in Centigrade and 𝑓 stands for the converted value in
Fahrenheit.
We can now design our solution around this formula using the following pseudo-code:
1. c=20
2. f=9/5*c+32
3. print("There are ", f, "degrees Fahrenheit in", c, "degrees Centigrade")
As an exercise modify the above program so that it converts 100° Centigrade into
Fahrenheit.
For example, the following line has the effect of increasing the value stored in variable
score by one.
score = score+1
Therefore, if the value of score before the line was executed was 6, it would be 7
afterwards. Notice that the variable appears on both sides of the assignment statement.
Similarly, the following line reduces the value stored in the variable livesLeft by 1.
livesLeft = livesLeft-1
# CODE FRAGMENT 1
print(2+3)
# CODE FRAGMENT 2
print ("2+3 =",2+3)
# CODE FRAGMENT 3
print ("2+3 =",23)
# CODE FRAGMENT 4
a = 2
b = 3
print(a,"+",b,"=",a+b)
# CODE FRAGMENT 5
num1 = 2
num2 = 3
print(num1,"+",num2,"=",num1+num2)
2. Given the variables x=2, and y=6 what do the Python expressions shown below evaluate
to?
a) x+y
b) x-y
c) 5*y
d) 5*x+y
e) 3*(x+y)
f) x*y+4
g) y/x+1
h) y/x+y
i) (x*y)+(y/x)
In all cases you should store your answer in an appropriately named variable and then
display the value of the variable in a meaningful message on a separate line. So for example
the answer to part a) would be:
1. answer=74*64
2. print("74*64=",answer)
4. Write a single line of code that adds the numbers 62 and 47 and displays the result.
7. Given the following code fragment that initialises three variables - x, y and z – insert a
line of code (at the end) that calculates and prints out their average.
1. x=27
2. y=15
3. z=18
4.
9. What (if anything) is wrong with the following? (Answer on a line by line basis.)
a) x=1+2
b) 3=1+2
c) 10/2=5
d) sum=a+b+c
e) print(a, b, c, sum)
f) a=8*2
g) b=8(+2)
h) c=4*a
i) c=4a
10. The area of a rectangle can be computed by multiplying its width by its height. Given the
following two lines of code to initialise these two variables write a third line that computes
the rectangle’s area. (Write a 4th line to display the answer.)
1. width=7
2. height=5
3.
11. The perimeter of a rectangle can be computed by adding twice the width to twice its
height. Given the following two lines of code which initialise these two variables, write a
third line that computes the rectangle’s perimeter. (Write a 4th line to display the answer.)
1. width=7
2. height=5
3.
12. Given that a person’s pay is calculated by multiplying the number of hours they work by
their hourly rate, write a program to calculate how much a person on €13.50 an hour
would earn for working a 40 hour week. Use appropriate variable names and display the
result.
13. Extend the program just developed to deduct 20% PAYE, and 5% PRSI. Again, use
appropriate variable names and display the result (i.e. net wage).
15. Read the following code carefully (the values are in cents) and answer the questions that
follow:
1. fifties=4
2. twenties=5
3. tens =7
4. total=fifties*.5 + twenties*.2 +tens*.1
5. print(total)
16. Let us say I have 18 fifty cent coins, 14 twenty cent coins and 15 ten cents. Write a
program to calculate the total number of euros I have.
17. Now modify the above program to calculate the number of euros given that I have a five
euro note, 22 fifty cent coins, 17 twenty cent coins, 25 ten cents and 13, 2 cent pieces.
18. Write a program to calculate and display the total from the bill below. Hint: Just re-
arrange the lines of code shown below:
And finally, can you write programs to solve the following problems?
1. The life expectancy for a man is 78 years and the life expectancy for a woman is 82
years. Write a program to compute and display the average life expectancy.
2. Jim was born in 1997. Write a program to display what year it will be when he turns 19.
3. Jack was born in 2002. Write a program to display what age he will be in 2064
4. The year is 2053. Mary has just celebrated her 87th birthday. Write a program to display
Mary’s year of birth.
5. The sum of the first n numbers can be calculated using the formula 𝒏(𝒏 + 𝟏)/𝟐. Write a
program that computes the sum of the first 100 numbers.
This lesson examines how variables can also be assigned values from the end-user.
This is called user input. The Python input command allows us to do just that.
The input command allows a user to enter a value into a running program and have that
value stored in a variable.
Consider the following short program that asks a user to enter their name and then prints out
a greeting message using whatever name the user enters.
Line 1 causes the message box shown below to be displayed as a prompt to the end-user.
Notice that the string used in the input command appears as a prompt in the message box.
Once the user enters a value and presses <OK> the value entered is assigned to the
variable personName. So, for example, if the user enters Joe, the value Joe will be
assigned to the variable personName.
Line 2 is very straightforward – it just prints a message Nice to meet you followed by the
person’s name e.g. Nice to meet you Joe.
Notice how the value stored in the variable is substituted for the variable name used in the
print command.
KEY POINT: Use the input command to assign text entered by a user to a variable
3. Modify the code in the previous question so that it asks the user for their surname as
well as their first name.
Imagine if our program could ask the user to enter any Centigrade value that they would like
to convert. The user could enter any number and the program would output the Fahrenheit
equivalent.
The above solution is known as a general solution because it would work for any number.
General solutions are much more useful than solutions that only work for specific values.
Line 2 is important because it converts the value entered by the end-user from text into a
whole number. In Python, whole numbers are called integers.
A slightly better solution would be to make one change so that the user can enter numbers
with decimal points. In Python, these are called floating point numbers.
The following syntax error is displayed if you attempt to use a text value in an arithmetic
expressions.
This is called a type error. To correct this error you will need to use the int or float
commands to convert the text to a numeric type.
The concept of datatype is very important in computer programming. The basic idea is that
programmers need to be aware of the type of data their program is dealing with. The most
common types are – strings (text), integers (int), floating point numbers (float) and Boolean
(true/false).
A note on testing
Testing is an important aspect of developing software. Simply put testing means to check or
verify that the program does what it is meant to do. Before you commence testing your
program you should always devise a number of test cases. Each test case is made up of an
input and an expected output. When the test case is run the actual output should be
recorded. If there is a difference between the expected and actual output then your program
contains an error (or bug) that you need to fix. A comprehensive test will ensure that every
line of code is executed. It will also take ‘abnormal’ scenarios into consideration
The table below provides a good basis for testing the Centigrade to Fahrenheit functionality
in the above program. Each row in the table is known as a test case.
Note that the values in the sample input column are arbitrarily chosen. The expected output
values are calculated by hand/using a calculator or come from some other source e.g.
internet. The values in the actual output column should be recorded by running the program
(see exercise). Any deviations between expected and actual output is an indication of an
error (bug) and usually necessitates some change to the source code. Once the change(s)
have been made the all test cases should be run again. When the program passes all test
cases it is said to be unit tested.
Extend the above simple interest calculation program to calculate and display the new
principle. (Hint: You will need to add the interest earned to the original principal.)
How might you test the above program? (see exercises 4, question 7)
One of the best ways to learn is just to experiment. Don’t be afraid to make mistakes.
2. The 4 programs below all use the formula 𝑙 = 2𝜋𝑟 to compute the length (𝑙) of the
circumference of a circle of radius 𝑟. The value of 𝑟 is entered by the user. (The
programs assume 𝜋 = 3.14.)
Study the 3 programs carefully – type them in and run them if you have time.
a) prompts the user to enter a number and store its value in a variable (e.g. number1)
b) convert number1 to an integer
c) prompts the user to enter another number and store its value
d) convert number2 to an integer
e) computes the sum of the two integers
f) displays the answer in an appropriate message
Hint: You need to re-arrange the lines of code displayed below into the correct order (but be
warned there is one extra line given that you don’t need)
2. Modify the program you just wrote to compute and display the difference, product and
quotient of the two numbers entered.
3. The average (arithmetic mean) of two numbers is calculated by adding them up and
dividing by 2. Write a program to ask a user to enter two numbers, compute their
average and display the result.
4. Given two types of scores – goals and points – where a goal counts for 3 points, write a
program that prompts a user to enter (in two steps)
a) the number of goals scored and
b) the number of points scored.
The program uses the data input to calculate the total points scored. (For example, if a user
enters 4 goals and 10 points the program will output 22 points)
5. The area of a circle is given by the formula 𝑎 = 𝜋𝑟 2 . Write a program that prompts a user
to input a value for a radius (r), and then calculates circle area. The program should also
print out the result. (Assume 𝜋 = 3.14.)
6. How would the program in the previous exercise have to be changed if the requirement
was to ask for the diameter (as opposed to the radius)?
1000 0.1 10
1000 0.05 10
5000 0.1 10
8. A person’s basic gross wages is calculated based on an hourly rate for a standard 40
hour week. In addition, overtime is paid at a rate of ‘time and a half’ for the first 10 hours
and ‘double time’ thereafter. Deductions include PAYE (20%), PRSI (5%) and USC (2%).
Write a program that prompts the end-user (e.g. a wages clerk) to enter the number of
hours worked and then outputs the following information:
9. Two points in a plane are specified using the coordinates (x1,y1) and (x2,y2). Write a
program that uses the formula below to calculate (and display) the slope of a line through
two points entered by the user.
𝑦2 − 𝑦1
𝑠𝑙𝑜𝑝𝑒 =
𝑥2 − 𝑥1
10. Why is testing such an important aspect of developing software? As an exercise devise
and implement test cases for the previous program. Use the table below to assist you.
Sample Input
Expected Output Actual Output
X1 Y1 X2 Y2
input Prompts the user to enter a value. The data entered is taken as a
string
int(x) Converts from a string to an integer
Functions are useful because they are re-usable. This means they can save programmers
from having to repeat the same lines of code every time they need a specific task carried
out. Therefore, functions can be used to avoid duplication of code.
From what we know so far, the general form of a function definition looks like this:
def functionName():
FUNCTION BODY
Once a function has been defined it just takes one line of code to use it. This is the function
call.
The general form of a function call look like this. (Note, the brackets are needed but def and
colon are not).
functionName()
The code to define a function must appear before the code to call it in a Python program.
Functions make it possible to develop solutions piece by piece. Large scale software
systems are developed by breaking big problems down into smaller problems. Each function
is written to do a specific task. Such systems are said to be modular.
The program begins running from line 9 which calls the function and the following output is
displayed:
Once all the lines in the function body have been executed the program continues to run at
line 10. Line 10 tells Python to display a blank line.
The function can be re-used simply by adding another call – see line 11 below.
Parameters allow programmers to pass information into a function. Take a look at this.
Notice personName between brackets in the function header? This is a function parameter.
A parameter is a special kind of variable used by functions.
Notice also the text James between brackets in the function call (line 9)? This is a function
argument. Arguments are passed into functions.
The text James is passed into the function in the above example.
KEY POINT: A function parameter is a variable which gets it value from the argument
passed in. When a function is called value of the argument is assigned to the parameter.
The value of personName is then used in the print statement on line 2. A parameter can be
used anywhere inside the function body in the same way as you would use a variable.
The advantage of using parameters and arguments is that they make functions much more
flexible. The behaviour of a function can be altered by passing different arguments into it.
This is demonstrated below where the three calls on the left hand side result in the output
displayed on the right.
The three arguments used are the strings James, Joe and Fred.
At runtime each argument is received by the parameter, personName and the name is used
in the output.
Test your understanding: Change the above code so that the output displayed would be
as follows:
The error is displayed because line 8 is attempting to call a function (i.e. homework) using
Jack as an argument. However, there is no parameter specified inside brackets in line 1 of
the function definition. This tells Python not to expect any arguments when the function is
called.
Now look at the following. The parameter named on line 1 (i.e. firstName) tells Python to
expect a value to be passed when the function is called. However, the function call – line 8 –
does not specify an argument. Hence the error.
KEY POINT: Python always expects the same number of arguments to be passed into the
function as the number of parameters specified in the function definition.
Tips:
1. Experiment. Deliberately cause syntax errors.
The three column below show three different function calls – each using different
arguments. What are the arguments? Use the space underneath each call to write the
output that would be displayed from that call.
Now study the following. What difference(s) do you notice? (Try to use words like
parameter and argument in your answer). What output does this program display?
Look at the code below carefully – the variable name is the argument and firstName is
the parameter.
When the function is called (line 10), the string Jack is passed into the function - firstName
is assigned the value Jack.
The program would display the exact same output if the call was:
The code below uses the input command to prompt the user for a name.
When the function displayGreeting is called (line 7) Python does two assignments:
a) the value of the first argument (i.e. Hello World!) is assigned to the parameter msg1.
b) the value of the second argument (i.e. Is there anyone out there?) is assigned to the
parameter msg2.
Hello World
Is there anyone out there?
Parameters are received into a function in the same order as the arguments provided.
Therefore, if the arguments were switched around like this,
Notice the use of a comma to separate parameters (and arguments) from one another?
Test your understanding: What output do you think this program would display? What are
the arguments and what are the parameters?
Write your answer below:
Key the code in and run it. State in one sentence what the program does?
Modify the above program so that it adds any two numbers entered by the end-user. (Hint:
You will need to add code to prompt the user to enter a second number – call it y.)
a)
b)
c)
d)
e)
f)
b) add(1+1,4)
c) a = 3
add(a,4)
d) b = 5
add(2,b)
e) a = 3
b = 5
add(a,b)
f) a = 3
b = 5
add(b,a)
g) a = 3
b = 5
add(a+b,a)
h) a = 3
b = 5
add(a,a+b)
5. Write your own function to display the following message – name the function iAmSam
I am Sam
Sam I am
6. Modify the function you just wrote to use a parameter (call it name). Whatever name is
passed in as the argument to the function should be used instead of Sam in the output
message.
7. Define your own function to accept three parameters – your first name (name), the
county you come from (county) and your favourite colour (colour). Test your function
by calling it in a program. The function should print out a message like:
State what you would expect to happen when each of the code blocks displayed on the left
hand side below is run.
c) name = "Dave"
displayGreetingV2("Good evening", name)
e) name = "Dave"
displayGreetingV3("Good evening", name)
g) sum = 2+3
displayGreetingV2(sum)
h) sum = "2+3"
displayGreetingV2(sum)
i) sum = "2+3"
displayGreetingV3(sum, 2+3)
Consider the conversion of pounds sterling into euro. The bank would need to know the
amount in sterling and the exchange rate. These are the inputs. The inputs are used to
calculate an output. In this case the output would be the amount in euros.
The bank might use the following Python program to do the conversion.
We already know that data can be passed into functions using parameters. The function
convert receives 2 parameters – sterling and rate. The arguments passed into the
function are pounds and 1.26 respectively. (The program is based on a conversion rate of
£1 = €1.26).
IMPORTANT: The return statement on line 3 is used to pass the value of euro back to the
caller.
When the function ends the value in euro is assigned to the variable amountInEuro.
The input to the function is parameter miles. The output of the function is kms.
We now look at the code the call function in order to calculate the number of kilometres in 50
miles.
The output of the function is kms. This value is assigned to the variable kilometres.
Once a function ends its variables and parameters are all destroyed.
Write a line of code to call this function to convert 80 kilometers into miles and display the
result.
Now write a line of code to call the first function, miles2kilometers. Use miles (returned
by your call to kilometers2miles) as the argument. What is your result?
The function is called on line 9. The arguments passed into add are 2 and 3. The value
returned by the function (i.e. sum) is assigned to the variable answer.
The three code snippets shown below all do the same thing. You should study them carefully
before trying them out for yourself.
FUNCTION 1 FUNCTION 2
Write a line of code to call the first function – save your answer in a variable e.g. answer.
Now try to do the same for the second function. What problem do you encounter?
For each of the tasks suggest a name for the function and state what you think the inputs
and the outputs should be.
Examples of two different ways the function can be called are shown below (A and B)
A.
B.
3. Explain the syntax error in the code shown below. How could this error be fixed?
6. Complete the program below so that it can add any two numbers entered by the end-
user.
7. Implement definitions for the following functions (in the same program). Write code to
test your functions.
8. The function square squares the number passed in. Modify the code so that it cubes.
Take a look at the following code to add two numbers and display the result.
The problem is that we have to declare the variable result to ‘catch’ the value returned by
the function.
The call to add is used as an argument to the print function. In fact, the value returned by
add is passed into print. The effect is to display 5.
When a function is used an argument to another function the inner function is always
evaluated first. (Python starts at the innermost function and works its way out).
The call below displays 10. Can you figure out why?
To convert this data to integer format we use int and to convert the data into decimal
format we use float. Normally this is done in two lines as follows:
Converting text to
a integer
Converting text to
a float
The Python library math contains a host of ready-made functions that can be used to make
calculations. One of these functions is called sqrt. This function returns the square root of
its argument.
Before a program can use any library function, it must first import the library using the
import statement (see line 1 below)
The listings below show three different ways to find and display the square root of 2. Try
them out.
The numeric literal 2 is used as The variable n is used as an The sqrt function is used as an
an argument to the sqrt function argument to the sqrt function argument to print
The syntax for making a call to any Python library function is as follows:
<library-name>.<function-call>
For example, to use the sqrt function from the Python math library to calculate the square
root of 2 we would write:
math.sqrt(2)
The program does exactly the same thing. In this case, the pow function is passed as an
argument to the print function.
We can define our own power function using the power operator.
1.
2.
Programmers ask the following questions when encapsulating code using functions:
What does the code do? This would be a good name for the function.
What are the inputs? The function should have a parameter for each input.
What is the output? This will be the return value of the function
What does the code do? The code converts kilometres to miles. It uses a conversion of
one kilometre to approximately 0.62 miles. A good name for the function would be
convertKms2Miles
What are the inputs? The only input is the value in kilometres to convert.
What is the output? The output is the converted value in miles.
KEY POINT: Deciding what function parameters and return values to use is an essential
programmer skill.
Ok. So this works. The code is more modular because it has a function but it still just
displays the same old weather page every time it’s called. Boring!
The solution below passes in the web page URL as an argument and the function returns
the page to the caller. This is the bells and whistle solution!
a)
b)
c)
Modify the program so that it asks the user for the required inputs and does the calculation in a
function.
5. Write a program that prompts a user to enter the radius of a circle and uses the value
entered to calculate and display its area. The calculation should be performed in a
function. (Note: 𝐴 = 𝜋𝑟 2 )
1
𝑎𝑟𝑒𝑎 = ×𝑏×ℎ
2
In the triangle below, 𝑎 is the length hypotenuse while 𝑏 and 𝑐 are the lengths of the other
two sides. Mathematically, Pythagoras’s Theorem can be written as
𝑎2 = 𝑏 2 + 𝑐 2
Pythagoras’s Theorem is very useful when we know the lengths of two sides of a right
angled triangle and we need to find the length of the third side. The following equation which
derives from the above formula can be used to calculate the length of the hypotenuse of a
right angled triangle.
𝑎 = √𝑏 2 + 𝑐 2
Define a function called hypotenuse that calculates and returns the length of the
hypotenuse of a right angled triangle when the lengths of the other two sides are given.
Then use the function to find the lengths of the hypotenuses of the triangles displayed
below:
8. Write a program that prompts a user to enter a number of days and then proceeds to
compute the number of minutes in that number of days.
9. Extend the program just written to prompt for a number of hours as well as a number of
days.
9
𝑓 = 𝑐 + 32
5
5
𝑐 = (𝑓 − 32) ×
9
From To
Euro Pounds Sterling
Pounds Sterling US Dollar
The program should define two functions – one for each conversion. Each function should
receive the amount to be converted as a parameter and return the converted amount. You
will need to look up the proper exchange rates yourself (try xe.com).
When you are satisfied that your currency converter works properly enhance it by writing a
small function that converts from Euro to US Dollar. For this task you should rely only on the
functions you’ve just implemented.
Throughout these notes there are lots of examples followed by related exercises.
It is important that you read the examples carefully before attempting the
exercises.
The more exercises you attempt the more mistakes you will make - The more
mistakes the more you will learn!
Let’s start off with a simple game program. The computer picks a random number between 1
and 10 and the user tries to guess it. If the guess is right the message You win! is displayed.
Here’s the code for the game. Study it carefully – there’s a fair bit going on.
Line 8 checks whether the user’s guess is the same is the computer’s number. This check is
made using an if-statement. If statements are Python’s way of making decisions.
In this case the condition is guess == number. Line 9 of the program will be executed only
if the two numbers are the same. Notice the use of double equals to compare two variables.
The execution of line 9 is conditional i.e. it depends on whether the condition associated with
it (guess == number) evaluates to True or False. Notice how this line is indented.
If the two numbers are not the same the condition will evaluate to False and Python will not
run line 9.
Quick Question
Why might it be useful to insert line 4 as follows
into the above program? (try it and see!)
if <condition>:
<conditional-code>
This time however, three messages are displayed if the guess is correct. Notice that lines 9-
11 are all indented to the same level. These lines are associated with the condition on line 8.
They make up what is called the conditional code for this condition.
Indentation returns to normal on line 13. Line 13 is therefore executed unconditionally. This
means that the final message displaying the computer’s number will be displayed regardless
of what the user entered.
Quick Question
How might a random number generator be used
to simulate a coin toss?
Code Answers
3. What is wrong with the following? Suggest two solutions to the problem.
4. Explain why the conditional code (lines 3 and 4) in the listing below never gets
executed.
5. Study the code below and explain what happens when the user enters:
a) 0
6. Complete the sentence: When Python evaluates a condition the result is either _______
or _________ .
The values in the above examples are all compared for equality. Conditions such as these
are tests for equality because the == operator is used.
Operator Meaning
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
== Equals
!= Not equals
Relational operators are used to compare two values. They are the basic building blocks for
conditions – also known as Boolean expressions. The first value is compared to the
second value. The type of comparison depends on the operator used. The result will always
be either True or False.
EXAMPLES
Example 1:
This example illustrates the use of relational operators to compare two values. Python’s
result is shown in the right hand column.
Condition Result
2 > 5 False
5 > 2 True
6 >= 6 True
6 >= 5 True
3 < 1 False
0 > 1 False
1 < 0 False
1 == 0 False
4 == 4 True
4 <= 4 True
3!= 4 True
3 <= 4 True
Condition Result
5 > 𝑥 True
𝑥 > 𝑦 True
𝑥 <= 𝑦 False
𝑦 <= 0 True
𝑧 > 𝑦 False
𝑥 == 𝑧 False
0 == 𝑦 True
𝑥!= 𝑦 True
2. Assuming 𝑥 = 1, and 𝑦 = 0 what would Python evaluate the conditions listed in here
to?
a) 𝑥 > 5
b) 5 > 𝑥
c) 𝑦 <= 0
d) 0 == 𝑦
e) 𝑥 == 𝑦
f) 𝑥!=𝑦
g) 𝑥 > 𝑦
h) 𝑦 > 𝑥
i) 𝑥 <= 𝑦
j) 𝑥 >= 𝑦
The conditional block from lines 4-6 will be executed only of the condition result==100
evaluates to True. If Python finds this condition is False the flow of control jumps straight
to line 8.
Try running the above program using the inputs shown in the table below. Record the output
displayed, along with an explanation in the space provided below.
100 100
100 49
80 50
50 20
KEY POINT
The association of a block of conditional code with an if statement ends as soon as the
level of indentation returned back to the original level.
Answer: The colon is missing from the end of line 2. Attempting to run the above code will
result in the following syntax error message box being displayed.
One of the skills you need to focus on as a novice programmer is the ability to deal with the
unexpected. In this case, you should teach yourself to understand Python error messages
such as the one displayed and become competent in dealing with them. To correct the
syntax error above just add a colon to the end of line 2.
KEY POINT: Python syntax requires that a colon is used to mark the end of a condition in
an if statement.
Answer: On line 2 an assignment statement i.e. (x=0) is being used where a Boolean
expression is expected. The code produces the following error – notice it is the exact same
error produced when we forgot the colon above.
To correct the syntax error above just change line 2 to be: if (x == 0):
KEY POINT: It is a common programming error to use the assignment operator (=) when
the intention is to test for equality using the relational equals operator (==)
(i)
(ii)
(iii)
(iv)
(v)
(vi)
(vii
)
The following table shows three different scenarios for initialising 𝑥 and 𝑦 before the code
above (i.e. at lines 1 and 2). What output would be generated for each scenario?
Initialisation Output
(i)
(ii)
(iii)
3. Write a program to read in two numbers (e.g. x and y) and display the message x is not
equal to y as appropriate.
4. Write a program that prompts the user to enter a student percentage mark (as an
integer). If the value entered is not 50 or greater display the message Unfortunately,
you have not been successful on this occasion. Try again.
Let’s say we want to display the message You loose! if the user’s guess is wrong.
Only one of the messages is displayed – never both. We use an if-else statement as
shown below.
Python evaluates the condition, guess == number, and, depending on the outcome either
line 9 or line 11 will be executed next. Never both. Line 13 is not part of the if-else statement.
It is always executed.
Notice:
- the else keyword appears on the same level of indentation as the if
- the use of the colon after else
- the code attached to the else is indented
The else statement is always used as an alternative to the if-statement. Both scenarios are
said to be mutually exclusive.
Output: Output:
What do you think this program would display if the value of result was
50?
if <condition>:
<IF-CODE>
else:
<ELSE-CODE>
Well done!
Finished
Unsuccessful
Finished
The behaviour of this program at runtime depends on the value entered by the user for
result. Now complete the following:
result 38 51
Unsuccessful
Program Options are …
output: 1. Repeat course or go on the dole
2. Emigrate
Can you spot any difference between this listing and the one above (at the top of the
page)?
Explain why both listings are logically equivalent (i.e. do exactly the same thing).
2. The code below displays a simple menu system, prompts the user to make a choice and
then, based on that choice, calls one of two functions.
The requirement is that if the user enters a 1 the function convertCent2Fahr will be
called. Otherwise, the function convertFahr2Cent will be called. (Assume definitions
exist for both functions).
a) Insert the correct condition into the red box so that this requirement is satisfied.
a) What output would be generated for the following values of score and highScore?
100 1000
1000 100
1000 1000
b) Re-write the code so that the duplicated line, print("Do you want to play again?
") appears only once. Both solutions should be logically equivalent.
c) Remove the duplicated instruction to display the message GAME OVER from the
following:
b) What change would need to be made so that line 14 gets executed regardless of what
the user enters?
c) The arithmetic expression n1+n2 appears twice in the above program – once on line 10
and again on line 14. Are both instances of this same expression always executed at
runtime? Explain.
d) Without changing the logic of the program, suggest a change so that the expression
n1+n2 only occurs once in the program. (Hint: use a variable).
e) Let us say the condition on line 10 was changed to userAnswer != n1+n2. What
other changes would need to be made so that the logic of the program remained
unaltered.
5. Write a program that generates two random numbers and ask the user to enter their
product. If the user is right the program should display Correct. Otherwise, the program
should display Incorrect.
b) What do you think would happen if the values entered for n1 and n2 were the same?
d) Can you think of any other test that could be used to determine that one number is greater
than another? (Hint: What is the result when you subtract a larger number from a smaller
number?).
d) Insert the correct condition in the red box so that the logic makes sense.
Implement the following Boolean functions. Test your code with numbers entered by the user.
d) Write a program that accepts a single number from a user and display the word ‘fizz’, if the
number entered is a multiple of 10. Otherwise, ‘buzz’. (Hint: A number is a multiple of 10
if the remainder after dividing by 10 is zero).
a) What would the output be if n1 and n2 were both initialised to zero (instead of 28 and 47)
10. Write a program that uses a random number generator to simulate tossing a coin.
11. Define a function (call it abs) that accepts an integer from the user and returns its
absolute value. Write code to test your function.
This time instead of displaying message You loose! if the user’s guess is wrong we change
our requirement so that the program displays the message
- Too High if the user’s guess is greater than the computer’s number and
- Too Low if the guess is less.
The program should still display the message You win! if the user’s guesses is right.
Because there are now three possibilities we need to use a multiple option if-elif
statement in our solution.
Only one of the three lines - 9, 11 and 13 - will be executed in any given run of the program.
If line 9 is executed the next line to be executed will be 15.
If line 11 is executed the next line to be executed will be 15.
If line 13 is executed the next line to be executed will be 15.
In other words, once a block of code attached to a True condition is executed the flow of
control jumps to the next line of code after the if-elif statement.
When executing an if-elif statement Python executes the block of code attached to the
first condition which evaluates to True. If none of the conditions are found to be True then
Python runs the code attached to the else statement (if one exists).
It is worth noting that the same logic can be achieved by re-arranging the order of the
conditions in the if-elif statement.
As a programmer you will need to be able to recognise when and where you build decision
statements into your programs. Examples of scenarios that require the use of decisions are:
a social network site (system) will only grant a user access if the password entered was
correct for the given username
an ATM system should not permit a user request to withdraw cash unless that user had
sufficient funds in their account to meet that request
a payroll program would contain a block of code to be used only if the number of hours
worked was over 50 (i.e. overtime calculation)
a flight booking system might offer discounted fares for passengers who are over 55.
a CAO points calculator will only add 100 to a student’s points tally if the grade achieved
was an A1; 90 for and A2; 85 for a B1; 80 for a B2; 75 for a B3 etc.
As a first step towards creating your own conditions, it is a good idea to formulate the
problem using pseudo-code.
c) Study the code below carefully and complete the table on the right (i.e. Output column).
8 4
2 3
3 3
5 1
7 7
2. Write a program to accept a single number from a user and print the word POSITIVE if
the number is greater than zero and NEGATIVE if the number is less than zero and
ZERO if the number entered is zero.
if <condition 1>:
<CODE-BLOCK 1>
elif <condition 2>:
<CODE-BLOCK 2>
elif <condition 3>:
<CODE-BLOCK 3>
…
elif <condition N>:
<CODE-BLOCK N>
else:
<ELSE-CODE-BLOCK>
Notes:
The first condition always appears in an if statement
There can be as many elif statements as you want
Each elif statement must include a condition
The use of a final else statement is optional
The if, elif and else keywords all appear at the same level of indentation.
A colon must be used at the end of the lines containing the if, elif and else
statements
Each condition is evaluated in sequence. If a condition evaluates to True then the
associated code block is executed. Once the code block is executed the flow of control
continues from the next line after the if-elif statement. If none of the conditions
evaluate to True then the final code block (i.e. the code block associated with the else
keyword) is executed.
c) Let’s say we extend the menu as shown below. Fill in the blanks.
e) Fill in the blank boxes below to implement a solution without using functions.
3. Study the two programs shown until you understand what they both do.
Explain why both these programs are logically the same as program 2 shown above
PROGRAM 1 PROGRAM 2
x = input("Enter a number from 1-
x = input("Enter a number from 1-5")
5")
x = int(x)
x = int(x)
if (x == 1):
if (x == 1):
print("One")
print("One")
elif (x == 2):
elif (x == 2):
print("Two")
print("Two")
elif (x == 3):
elif (x == 3):
print("Three")
print("Three")
elif (x == 4):
elif (x == 4):
print("Four")
print("Four")
elif (x == 5):
else:
print("Five")
print("Five")
c) What changes would you need to make to both programs in order to accommodate the
following line of code.
print("Invalid number entered - you must enter a number between 1 and 5.")
d) Write a program to accept a number from 1 to 10 from the user and display its ordinal
value. For example, if the input was 5 the output would be 5th.
e) Outline how this program could be designed to display the ordinal value of any number
entered
6. Write a program to prompt a user to enter a month number and then display the name of
the month. For example, if the user enters 5 the program will display May.
c) Modify the (fixed) code from the previous question so that it uses a variable called
grade and just one print statement at the end that displays the value of grade.
The end-user is prompted to enter the number of hours worked and the hourly rate of
pay. Time and a half applies to all hour worked between 40 and 50 hours and double
time applies to every hour worked in excess of 50.
Now complete the table below for the sample inputs provided. You should use a calculator to
complete the expected output column. The Actual Output column can be completed by
running the program.
2. Write a program to read in an integer and display the message Valid month if the integer
is between 1 and 12 inclusive. If the number entered is not between 1 and 12 the
program should display the message Sorry. The value you entered is an invalid month.
3. Write a program to display the sign (i.e. POSITIVE or NEGATIVE) that would result from
the product of two integers (without calculating the product – you should verify your
program works by having the program perform the actual calculation).
5. Write a program that examines two integer variables and exchanges their values if the
first one is greater than the second one
6. Write a program that reads in and displays the largest of three integers
7. Let use assume for the purpose of this exercise that passwords can only be numbers
(integers). Write a program that initialises a variable called password to the value 9999.
The program should then prompt a user to enter a number (i.e. password). If the value
entered is the same as 9999 the program should display the message User
authenticated. Otherwise, the program should display the message WARNING: Intruder
alert!
8. Write a program that asks a user whether s/he wants to add (0), subtract (1), multiply (2)
or divide (3). The program should then ask for two numbers to be input and, based on
the code entered, perform the appropriate operation. (See iteration exercise for
continuation.)
9. Write a program that prompts a user to enter a percentage mark (between 0 and 100)
and depending on the mark entered display the appropriate grade as follows:
Distinctions (80 or greater), Merit (between 65 and 80), Pass (between 50 and 65) and
Unsuccessful (less than 50).
10. Write a program to prompt a user to enter a month number and then display the number
of days in that month. (Assume February has 28 days.) For example, if the user enters 3,
the program will display the message - This month has 31 days.
11. Write a program to prompt a user to enter a month number and then display the number
of days in that month using the name of the month in the output. (Assume February has
28 days.) For example, if the user enters 3, the program will display the message –
March has 31 days.
12. Write a program that reads a date as three integers (day, month and year) from the
keyboard. The program should output the message Valid if the date is valid; Invalid
13. Write a programme that prompts a user to enter a year and display whether the year
entered was (or will be) a leap year. A year is defined to be leap if it is divisible by 4 but
not by 100. If a year is divisible by 4 and by 100, it is not a leap year unless it is also
divisible by 400. (For example, 1800 and 1900 are not leap years while 1600 and 2000
are.)
Thus, years such as 1996, 1992, 1988 and so on are leap years because they are
divisible by 4 but not by 100. For century years, the 400 rule is important. Thus, century
years 1900, 1800 and 1700 while all still divisible by 4 are also exactly divisible by 100.
As they are not further divisible by 400, they are not leap years.
14. Ordinal numbers are the words representing the rank of a number with respect to some
order, in particular order or position (i.e. first, second, third, etc.). Ordinal numbers are
alternatively written in English with numerals and letter suffixes: 1st, 2nd or 2d, 3rd or 3d,
4th, 11th, 21st, 101st, 477th. Write a program that accepts a number as input and prints
out its ordinal value by concatenating an appropriate suffix to the number that was
inputted. The following table lists some example inputs and outputs:
Input Output
1 1st
2 2nd
3 3rd
12 12th
21 21st
15. Write a program that prompts the user to enter a time (e.g. HH:MM – two separate inputs
may be needed) and display the time in words e.g. 9:40 “twenty to ten”.
Introduction to Loops
Let’s say – for some strange reason – that we wanted to display the string “Hello World” 10
times.
Although the code shown below does the job, it looks a bit strange (or at least it should do!)
with the same line being repeated 10 times. There must be a better way.
We can see from the above that we would like the line to
be executed 10 times. Before coding a loop we must first recognise that a loop is needed.
This is the difficult bit. The easy bit is actually writing the loop in Python.
There are two types of loops in Python – while loops and for loops. For the moment we
will stick with while loops.
The program below uses a while loop to display the string “Hello World” 10 times.
Study the program carefully and see if you can figure out how it works.
Line 2 initialises a variable called count to zero. The loop will end when count reaches 10.
Line 3 is the start of the while loop.
- count < 10 is a Boolean expression known as the loop guard
(the use of brackets around the loop guard is optional)
- if the value of count is less than 10 the loop guard evaluates to True
- if the loop guard evaluates to True the loop body is executed
Lines 4 and 5 make up the loop body
- line 4 displays the text Hello World
- line 5 increases the value of count by 1
- after line 5 execution loops back to line 3
In this example count is known as the loop variable. The loop variable is important
because it controls the number of times the loop will be executed. Here the value of count
will eventually reach 10 at which point the loop guard will evaluate to False and the loop
body will not be executed.
A loop works by testing the value of the loop variable on each cycle.
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
Hello World
while <expression>:
<statement(s)>
The statement(s) section of a loop is called the loop body. The loop body is conditional
code and can consist of one or more lines. Each line of code in a loop body must be
indented.
Once the last line of the loop body has been executed the flow of control loops back to the
loop guard. This is called an iteration. The loop guard is re-evaluated and as before the loop
body will be executed if the result is True; otherwise the loop body will be skipped and
execution will continue from the next line after the loop body.
Remember! The loop body is executed as long as the loop guard remains true.
Notice that the loop body (i.e. the conditional code) of the while loop might not ever be
executed. When the condition is tested and the result is False, the loop body will be
skipped and the first statement after the loop body will be executed.
3. Now re-arrange the 4 lines below so that the same output is generated
4. Describe in your own words the difference between a loop guard and a loop body
Small changes to the loop guard can cause the loop body to be executed either more often
or less often than intended by the programmer. Study the examples below carefully.
The three programs below all display the numbers 1…5 vertically. See if you can figure out
how they work.
Even though the loop guards are different the three programs all do the same thing
(i)
(ii)
(iii)
(iv)
(v)
(vi)
(vii
)
Care should always be taken by the programmer to ensure that a loop will – at some stage –
come to an end. In other words, it is the programmer’s responsibility to write the necessary
code that will eventually cause the loop guard to evaluate to False. Consider the two small
example programs illustrated below:
Warning! Once you start a program that contains an infinite loop it can be difficult to stop.
(On Windows systems you may need to use the Task Manager to end the task.)
In this example the loop can never be executed which of course makes no sense.
The example is just fabricated to illustrate the point that sometimes loops are not executed
because of particular runtime circumstance that causes the loop guard to evaluate to False
the first time it is tested.
To solve this problem we introduce a variable called max. We prompt the user to enter a
value and store it in max. The loop is written as before, with one difference. This time instead
of ending when the counter reaches 10, the loop continues until the counter reaches max.
1. n = 1
2. max = input("Enter the upper limit")
3. max = int(max)
4. while (n <= max):
5. print(n)
6. n = n + 1
If the user enters 4 the program will display the following output:
1
2
3
4
Counting backwards
In this example we examine a program that displays all the whole numbers backwards
between two numbers entered by the user - max and min.
Look carefully at how – on each iteration of the loop - line 8 decrements (subtracts 1 from)
the value stored in the variable max. This continues until eventually the value of max
becomes less than the value of min and the loop guard min <= max evaluates to False.
(i)
(ii)
(iii)
(iv)
(v)
2. In the last three example listings above, what is the value of the variable n after the loop
has terminated?
3. Write a program that displays all the whole numbers between two numbers entered by
the user max and min.
4. Write a program that displays all the numbers from 100 down to 1 inclusive.
5. Write a program that displays every 10th number between zero and 100 inclusive i.e. 0,
10, 20, 30 etc.
6. Given the following code to add two random numbers between 1 and 10, write a program
that adds two random numbers three times. (Hint: You will need to wrap the code
provided inside a loop body and execute the loop three times.)
import random
n1 = random.randint(1, 10)
n2 = random.randint(1, 10)
print(n1, "+", n2, "=", n1+n2)
Thus far, we have not been doing very much with our loop variable. (Most examples so far
just display the contents of the variable and either increment or decrement it.) In the
following examples we will develop the possible uses of loop variables.
Computing squares
The program below loops over a variable n, to compute and display the following table of
values.
Before looking at the solution think about it. Try to answer the following questions.
Does the first row (i.e. the row header) need to be printed inside a loop?
How many times does the loop body get executed to produce the output shown?
What is the loop variable?
Which values are calculated by the program?
For each of the 5 data rows what calculation is being carried out?
How are the columns so neatly aligned?
Notice the use of ‘\t’ in the above program. ‘\t’ is an example of a special character called an
escape sequence. Python interprets the ‘\t’ escape sequence as a tab character. Therefore,
every time a ‘\t’ character appears in a print statement Python prints a tab in its place. It is
through the use of the ‘\t’ character that the data displayed in output columns are kept so
neatly aligned.
Some other common escape sequence characters are illustrated in the table below:
The value on the right hand side of the equals sign is calculated by
multiplying 7 by n.
Remember, the parts inside the quotations are string literals and as such are not interpreted
by Python. The pieces outside the quotations are variables or expressions. These are
evaluated by Python and the result of the evaluation is displayed.
In the program listing shown below we improve our ‘7 times program’ by asking the user
what times tables they wish to have displayed.
2. Modify the program just written to generate the addition table for any number entered by
an end user
3. Write a program that displays a table of the squares and cubes of the first 10 numbers as
illustrated below:
4. Given the formula below to convert from degrees Celsius to Fahrenheit, write a program
to calculate and tabulate Fahrenheit values for all Celsius values between zero and 100
in steps of 10.
9
𝐹 = 𝐶 + 32
5
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10
print(1+2+3+4+5+6+7+8+9+10)
As a slight improvement we will introduce a variable - total, to store the result and display
a more meaningful message.
total = 1+2+3+4+5+6+7+8+9+10
print("The sum of the first 10 natural numbers is", total)
Although, the programs above work, their use is very limited. A better and more general
solution can be written as follows using a simple while loop.
The key to understanding the above code lies in the use of the variable total. Notice that
total is initialised to zero before the loop begins execution. We focus in particular on line 5.
Notice how the variable total appears on both sides of the assignment operator (=). Line 5
calculates a new value for total by adding its old value to the value of counter. The table
below shows how a new value for total is calculated on each iteration of the while loop.
total total
Iteration (counter)
(before assignment in line 5) (after assignment in line 5)
1 0 1
2 1 3
3 3 6
4 6 10
5 10 15
6 15 21
7 21 28
8 28 36
9 36 45
10 45 55
The technique of using a variable to accumulate a total is quite common (and therefore
important) in computer programming. (As an example, think about how a retail point of sale
system might calculate the total bill.)
The program should prompt the user to enter each of the ten marks. It will need to keep a
running total of all the marks. Once the total is known the average can be calculated, simply
by dividing the total by 10.
The Python solution is shown below – except the lines are all jumbled up and not
indented properly. Can you re-arrange into a working solution?
counter = 1
while (counter < 10):
print(counter)
counter = counter + 1
Let us consider how the digits 1 through to 9 could all be displayed (using a loop) on the
same line i.e. horizontally as shown below.
The problem with the above solution is that the program moves onto a newline each time the
digit (i.e. the value of counter) is displayed. If we want to display all the digits on a single line
then we need a solution that calls the print() function just once. The call to print() will
have to be after the loop body. The loop itself just builds up the output to display.
We introduce a variable called output. Initially output is set to be an empty string (i.e. "").
On each iteration of the loop the value of counter is concatenated (i.e. added) to output.
The table below illustrates how the value of output changes with each loop iteration.
counter output
1
2
3
4
5
6
7
8
9
By the time the loop is finished the value of output has been accumulated to the desired
string 𝟏𝟐𝟑𝟒𝟓𝟔𝟕𝟖𝟗. The solution is shown below.
1. output=""
2. counter = 1
3. while (counter < 10):
4. output = output + str(counter)
5. counter = counter+1
6. print(output)
Line 4 is the key line. This line builds up the output string by adding the current value of
counter to the output string accumulated so far. Since counter is a numeric type it must
be converted to a string so that it can be added to output. The build in function str()
does this by converting counter to a string.
Notice from the listing shown on the left hand side below, that with a very slight change we
can generate the output displayed on the right.
In the above listing the call to print() has been moved inside the loop. Therefore, the
contents of output are displayed on each loop iteration.
At an initial glance a solution might seem trivial – just modify line 4 of our original solution to
append a comma after each digit as follows:
1. output=""
2. counter = 1
3. while (counter < 10):
4. output = output + str(counter) + ","
5. counter = counter+1
6. print(output)
However, this would result in a string with an extra, unwanted comma at the end as follows:
So, what about changing the code to add a comma in before each digit?
1. output=""
2. counter = 1
3. while (counter < 10):
4. output = output + "," + str(counter)
5. counter = counter+1
6. print(output)
This just moves the extra, unwanted comma to the start of the string as shown:
The problem is that we have 9 digits but only need 8 commas. In other words there is a
difference of one between the number of iterations required to display the digits and the
commas.
In the case of this example a solution can be achieved by using the loop to accumulate the
output string following the sequence - digit followed by comma - up to but not including the
digit 9.
1. output=""
2. counter = 1
3. while (counter < 9):
4. output = output + str(counter) + ","
5. counter = counter+1
6. output = output + str(counter)
7. print(output)
Once the loop has finished, line 6 completes the construction of the output string by adding
the digit 9 - without the trailing comma.
An alternative solution – shown below – works by building up the output string using the
sequence comma followed by digit – from digit 2 onwards.
1. output="1"
2. counter = 2
3. while (counter < 10):
4. output = output + "," + str(counter)
5. counter = counter+1
6. print(output)
Figure it out
Try running the following code.
Can you figure out what it does? The following questions might help you.
What are your inputs?
What is the output?
2. Write a program that sums all the numbers from 1 to x where x is some number entered
by the end-user. For example, if the end-user entered 12 the program would compute
and display the result of 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12.
3. Write a program that sums all the numbers from x to y where both x and y are two
numbers entered by the end-user. For example, if the end-user entered 8 and 13 the
program would compute and display the result of 8 + 9 + 10 + 11 + 12 + 13.
1 1
4. The reciprocal of a number 𝑥 is denoted by 𝑥. For example, the reciprocal of 5 is 5. Write
a program to sum the reciprocal of the first 10 natural numbers i.e.
1 1 1 1 1 1 1 1 1 1
+ + + + + + + + +
1 2 3 4 5 6 7 8 9 10
5. Develop a ‘mini point of sale system’ to calculate the total amount due based on the
items –quantities and prices - listed in the table below.
6. The factorial of a non-negative integer n, denoted by 𝑛!, is the product of all positive
integers less than or equal to n. For example, 5! = 5 × 4 × 3 × 2 × 1 = 120. Write a
program that prompts a user to enter a number and then compute and display its
factorial
7. Write a program that uses a loop to display the output shown below.
8. Now modify your program so that the output is accumulated as a string and displayed on
a single line as follows:
9. Finally, enhance the program so that the final plus sign is not displayed i.e. the output
should look like:
The challenge here is to develop a loop guard that allows the loop to be executed a variable
number of times.
What exactly does ‘as long as there are more numbers to add’ mean? To answer this
question we need to understand sentinels.
A sentinel is a special type of loop guard used to end a loop when the number of
iterations is not known before the program is run. The sentinel value is decided upon by
the programmer and used to terminate a loop.
In the case of this example, if we choose zero as the sentinel it will mean that the loop
should end when the user enters the number zero. A programmer needs to be careful not to
choose a sentinel that is a possible legitimate value (and so should be processed like every
other value by the loop). Since the purpose of this program is to add a list of numbers, it
seems reasonable to use zero as a sentinel.
The use of the sentinel can be seen in line 5 of the Python implementation shown below.
You should verify the program works by keying it in and running it. Notice how lines 3 and 7
both prompt the user to enter a number. In both cases the end-user is reminded that the
sentinel is zero. Line 6 keeps the running total by adding the number just entered to the total
so far.
It is quite common to maintain a counter in a sentinel controlled loop. The main reason for
this is that by the time the loop has finished execution the counter can be used to indicate
how many iterations of the loop took place.
11. print("The sum of the all the numbers entered is", total)
12. average = total/counter
13. print("The average of the all the numbers entered is", average)
Notice that the variable counter is initialised to zero (line 3) and, how on every iteration of
the loop the counter is incremented by 1 (line 7). Finally, when the loop is finished, the
counter is used to compute the average (line 12).
Sentinels Summary
A sentinel is a value used to terminate a loop. The sentinel is chosen by the programmer
and forms part of the loop guard which controls access to a loop.
There should be no chance that the value chosen as the sentinel could be a legitimate value
that should be processed by the loop body. For example, if the loop body is dealing with
numbers greater than zero, then the sentinel could be either zero or any negative number.
In general, the psuedo-code for a sentinel loop looks something like this
2. Write a program that repeatedly reads a positive number and displays its square root.
The program should end when the user enters −1 (i.e. the sentinel is −1.)
If you are unsure you should modify the following mixture of Python and pseudo-code.
import math
3. Write a program that selects a random number between 1 and 10 and asks the user to
repeatedly enter a number until s/he has guessed the random number.
If you are unsure you should modify the following mixture of Python and pseudo-code.
import random
4. Write a program that generates two random numbers (say between 1 and 20) and asks
the user to enter their sum (or product). The program should continue until the user
enters the correct answer.
5. Enhance the last two solutions so that the user has at most three chances.
Here the loop body (i.e. lines 3 and 4) is only executed if the condition in the pseudo-code
i.e. ‘value is invalid’, is true. We need not concern ourselves with the details of how the
program actually determines whether the value entered is valid or not. (Suffice to say that an
actual implementation would need to contain the code that tests for the validation of value in
question. The test would evaluate to true if the value is invalid and false otherwise.)
The important point to recognise is that the loop body may be executed zero or more times
depending on whether the value entered by the user is valid or not. If the user enters a valid
value the first time, loop body will not be executed. On the other hand, if the user enters an
invalid value, the loop body will be executed – and continue to be executed – as long as the
value entered by the end-user remains invalid. In this way the program guarantees, that by
the time line 5 is reached, the value to be processed will be valid.
In the first example, the end user is prompted to enter a response to the question “Do you
wish to continue (Y/N)”. The only valid (acceptable) responses are either “Y” or “N”. The loop
ensures that the user is repeatedly prompted as long as their answer is not equal to “Y” and
not equal to “N”. In this way the programmer can be sure that by the time the loop has exited
the user has entered one of “Y” or “N” and can take appropriate action based on the user
decision.
In the second example, the program prompts the end user to enter a numeric value for a
month. Since the only valid values are any number between 1 and 12 inclusive the program
keeps looping until a value in this range has been entered.
2. Write a program that repeatedly adds two numbers entered by the user. At the end of
each iteration the program should prompt the user with the message “Do you wish to
continue (Y/N)”. The program should continue as long as the user answers “Y”.
3. Write a program that asks a user whether s/he wants to add (0), subtract (1), multiply (2)
or divide (3). The program should then ask for two numbers to be input and, based on
the code entered, perform the appropriate operation. At the end of each calculation the
program should prompt the user with the message - Do you wish to continue (Y/N). The
program should end when the user enters N.
Consider a simplified payroll scenario where tax is calculated at 20% on income less than
€40,000 and 50% on income of €40,000 or greater. We wish to write a program that accepts
the 5 incomes listed below and calculate the net pay for each income provided. For each
income entered, the program should display the gross pay, the tax payable and the net pay.
Gross Income
€50,000
€10,000
€40,000
€25,000
€82,500
Our solution will use a loop to prompt the user for each of the 5 values. The loop will need to
contain an if-else statement to decide whether the income is less than the threshold of
€40,000 or not. If the income is less than €40,000 the code will calculate the tax to deduct
based on the low rate of 20%. Otherwise, the tax will be calculated based on the 50% rate.
counter=1
while (counter <= 5):
gross = input("Enter gross income:")
gross = float(gross)
if (gross < 40000):
tax = gross * .2
else:
tax = gross * .5
counter=counter+1
Key in the above code and then run. Use the output to complete the table below:
€10,000
€40,000
€25,000
€82,500
From the problem statement it should be clear that we are going to require a loop – to iterate
over all the numbers between 1 and 100. A number is defined to be even if it is evenly
divisible by 2. In other words, if we divide a number by 2 and the remainder is zero we can
conclude that the number is even.
We can use this information to code the following Python condition to test for evenness. If
the condition evaluates to True the program can conclude that n is even; otherwise n must
be odd.
(n % 2 == 0)
The full solution presented below wraps the condition as part of an if statement inside a
while loop.
1. n = 1
2. while (n <= 100):
3. if (n % 2 == 0):
4. print(n)
5. n = n+1
For every value of n between 1 and 100, n is tested for evenness. If the condition evaluates
to True, the value in the variable n is displayed. As there is no else statement, there is no
processing carried out if n is not even. In other words odd numbers are ignored. Line 5 is
executed regardless of whether n was even or not.
The program below displays all odd numbers between 1 and 100.
1. n = 1
2. while (n <= 100):
3. if (n % 2 != 0):
4. print(n)
5. n = n+1
Can you spot the subtle difference between the two programs?
An interesting variation to the above is the following program which counts all the numbers
between 1 and 100 that are evenly divisible by 4.
1. count = 0
2. n = 1
3. while (n <= 100):
4. if (n % 4 == 0):
5. count = count + 1
6.
7. print("There are", count, "numbers evenly divisible by 4 between 1 and 100")
Key it in and try running it!
Let us wrap our code – from the previous page - to determine the ‘evenness’ of a number
into a function.
1. def isEven(number):
2.
3. if (number % 2 == 0):
4. return True
5. else:
6. return False
This is an example of a Boolean function because it returns a Boolean value i.e. either True
or False. The function uses the remainder operator (%) to test whether the number passes
in is even or not. If the value passed in as number turns out to be even the function returns
True. Otherwise the function will return False.
To code below demonstrates how the above function could be used to display all the even
numbers between 1 and 100.
1. n = 1
2. while (n <= 100):
3. if isEven(n):
4. print(n)
5. n = n+1
Line 3 is key. Here the call to the function appears as part of a conditional statement. This is
fine, since conditions evaluate to True or False and the function isEven(number) is
guaranteed to return one of these values.
As before, with a very slight modification we can display all the odd numbers between 1 and
100.
1. n = 1
2. while (n <= 100):
3. if !isEven(n):
4. print(n)
5. n = n+1
When a function call appears in a loop body, the function will be called on each iteration of
the loop.
Question. How might the above code be modified to count all the even/odd numbers
displayed?
2. Write a program that repeatedly prompts a user to enter a number. If the user enters an
even number the program should display Even; otherwise, the program should display
the message Odd. The program should end when the user enters zero.
3. Write a program that keeps a count of the number of even numbers entered by a user
until zero is entered.
4. A prime number is a number that has exactly two factors, 1 and itself.
The Boolean function below isPrime determines whether the number passed in is
prime or not. The function will return True if number is a prime number; False
otherwise.
a) Use the isPrime function to display all the prime numbers between 2 and 100
inclusive.
b) Use the isPrime function to count and display the number of prime numbers
between 2 and 1000.
c) Use isPrime to display the first 50 prime numbers.
6. Enhance the program from the previous exercise to print out the total number of factors
the number entered has.
7. Maths Teacher. Write a program that generates two random numbers (between 1 and
100) and prompts the user to enter the sum of the two numbers. If the user enters the
correct value display Correct. Otherwise display the message Incorrect. Try again. The
program should give the user three chances and at the end of each cycle should ask the
user – Do you wish to continue (Y/N). The program should end when the user enters N.
Although, the semantics of while and for loops is the same, the syntax is substantially
different. Let’s jump straight into an example.
The program below uses a for loop to display all the numbers from 0 up to, but not
including, 10.
In order to understand the above program it is first necessary to understand that range is a
build-in function which returns a list of values. In the above example the call range(0,10)
returns a list of all the numbers from 0 up to but not including 10 i.e.
range(0,10) -> 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
range(8,12) -> 8, 9, 10, 11
If only one argument to range is provided, the first argument is taken to be zero. Therefore,
range(5) -> 0, 1, 2, 3, 4
In the case of this example, the for loop works by iterating over each value in the sequence
(i.e. 0 through to 9). At the start of each iteration the value of the next item in the sequence is
assigned to the loop variable. In this example, the name of the loop variable is num.
Notice how at the start of each iteration the iterating variable is assigned the next value in
the sequence. The loop ends when all the values in the sequence have been used.
Once the loop terminates, execution continues at the next line after the loop body.
The loop starts by assigning the first item in the sequence to the loop variable referred to as
iterating_var. Next, the statement(s) that make up the loop body are executed. The loop
continues the cycle of assigning the next item in the sequence to the iterating variable and
then processing it in the loop body until the entire sequence is used up.
Observe the use of colon (:) and also that the statements which make up the loop body are
indented.
The syntax of the Python for loop is illustrated in the following flow diagram.
The answer is that there is no clear cut answer! Since both constructs are semantically
equivalent the use of one over the other is a matter of programmer taste. However, you may
find the following guidelines helpful – particularly the first point.
As a novice programmer you should not worry too much – use whichever you feel more
comfortable with.
Many programmers prefer to use a for loop when the number of iterations is known in
advance i.e. for counter controlled repetition.
When the number of iterations is not known in advance a while loop is often preferred.
This covers situations where you want to keep running a loop until a certain condition is
met as well as sentinel controlled repetition. (This includes the common task of reading
(and processing) the contents from a file until an end-of-file (EOF) character is read.)
In general for loops are more suitable for iterating over lists/arrays. We will cover the
topic of lists/arrays at a later stage.
For the moment it is important that you can recognise situations where you need to use a
loop in your program. The choice of which type of loop to use i.e. for or while, doesn’t
really matter. Loops that can be coded using a while construct can also be constructed using
a for construct and vica versa.
For example, the programs on the left-hand-side and right-hand-side are logically equivalent
i.e. they do exactly the same thing.
Counting Numbers
Earlier we encountered an example to display all the numbers from 1 up to some number
(max) entered by the user. The solution using a while loop is shown below.
1. n = 1
2. max = input("Enter the upper limit")
3. max = int(max)
4. while (n <= max):
5. print(n)
6. n = n + 1
Cubes
The program on the left hand side below generates and displays the first 10 cubes as shown
on the right hand side.
total=0
for n in range(1, 11):
mark=input("Enter student mark: ")
mark=int(mark)
total=total+mark
average=total/10
print("The average mark is", average)
9. average = total/10
10. print("The average mark is", average)
As a final point it is worth noting that for loops do not lend themselves very well to situations
where there are an unknown number of iterations. (In other words for loops lend themselves
to scenarios where the number of iterations is known in advance of runtime.) For this reason,
it is rare to use sentinels with for loops.
Code
(i)
(ii)
(iii)
(iv)
(v)
2. The built in function pow(x,y) returns x raised to the power of y. Use a for loop to
implement your own power(x,y) function.
3. Write a program that uses a for loop and the power function you just implemented in
the previous exercise to compute the sum 12 + 22 + 32 + 42 + … + 𝑛2.
4. Look back over the exercises you completed earlier – in particular, look at your solutions
to exercises 2, 3, 4 and 7. Now attempt to provide an implementation using for loops.
A continue statement causes the loop to skip the remainder of its body and transfer
control back to the loop guard
1. # Break Example
2. var = 10
3. while var > 0:
4. print('Current variable value :', var)
5. var = var -1
6. if var == 5:
7. break
8.
9. print("Good bye!")
1. # Continue Example
2. var = 10
3. while var > 0:
4. var = var -1
5. if var == 5:
6. continue
7. print('Current variable value :', var)
8. print("Good bye!")
The first element in our list would be 00:00, the second element would be 00:01, followed by
00:02 and so on until we reach 00:59. The next elements would be 01:00, 01:01, 01:02,
01:03 etc. The final element in the list would be 24:59.
In effect we are moving through the hours in sequence and for each hour we move through
the minutes. Conceptually, this is a loop within a loop.
The following code lists all the possible times – minute by minute - of the 24-hour clock as
discussed earlier.
In this example the outer loop iterates over the variable hour and the inner loop iterates
over the variable minute. The outer loop changes only after the inner loop has made 60
iterations. The inner loop causes the value hour:minutes to be printed vertically. The final
line (i.e. print("")) is only executed after the inner loop has completed. This results in the
values for each hour being separated by a blank line.
Care should be taken when using nested loops as they can impact on program runtime
performance. The above simple program makes 24 × 60 = 1440 iterations!
for i in range(5):
output=""
for j in range(1, 10):
jStr=str(j)
output=output+jStr
print(output)
Note the use of the built in function str to convert an integer to a string. In this case the
integer to convert is contained in the variable j. The string equivalent of the integer is stored
in the variable jStr. The string to display (i.e. output) is constructed by concatenating
each successive value of jStr.
The program is fine in the sense that it illustrates how to use a variable (i.e. n) inside a
while loop. The same functionality could easily have been achieved using a for loop as
follows.
Regardless of which type of loop was used the key point is that the loop is useful because
each output line can generated by using the same statement (i.e. 7 multiplied by the iterating
variable, n).
What if we wanted to print out all the multiplication tables from 1 to 12? In order to solve this
problem we need to use nested loops.
Our solution will make use of the fact that we already have the code to generate and display
the 7 times tables. We will take our ‘7 times’ code and generalise it to work for every value
between 1 and 12. To do this we will introduce a new variable called tables and another
loop to iterate over tables. Two solutions - using while and for loops – are presented on
the next page.
Study both solutions carefully (key them in and run them) before reading the commentary
which follows.
The first thing to notice is that although the first solution is terser (i.e. shorter) both solutions
do exactly the same thing. The main reason that the solution with the for loop is terser is
because it does not have to increment the loop variables i.e. lines 7 and 8 in the second
solution are not needed in the first.
However, the key point is the use of nested loops in both solutions. The indentation of code
is critical to the understanding of the use of both loops. In the case of this example there are
two loops – the first loop is referred to as the outer loop and the second loop is called the
inner loop. Each loop is marked by a new level of indentation. In the solutions above we see
two levels of indentation – each level corresponds to a particular loop.
Iteration around the outer loop always occurs at a slower pace than iteration around the
inner loop. For every step in the outer loop there are 12 iterations of the inner loop. The
outer loop is controlled by the variable tables and the inner loop is controlled by the
variable n. In effect what is happening is that for every iteration of the variable tables there
are 12 iterations of the variable n. Thus, the 1 times tables are displayed (i.e. 1 × 1 = 1, 1 ×
2 = 2, …. 1 × 3 = 3), followed by the 2 times tables (i.e. 2 × 1 = 2, 2 × 2 = 4, …. 2 × 3 = 6)
and so on right up to the 12 times tables (i.e. 12 × 1 = 12, 12 × 2 = 24, …. 12 × 3 = 36).
i = 2
while(i < 20):
j = 2
while (j <= (i/j)):
if not(i%j):
break
j = j + 1
if (j > i/j):
print(i, " is prime")
i = i + 1
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
Use the table below to trace through the program variables and deepen you understanding
of how the program works.
i j i/j i%j
Nested loops are most commonly used for iterating over two dimensional (2D) arrays (i.e.
the inner loop does the horizontal processing and the outer or slower loop does the vertical
processing). 2D arrays in turn are used in the implementation of many board games. Arrays
and lists will be discussed in more detail at a later stage.
2. Write a program to compute and tabulate the factorial of all numbers from 0 to 10? Your
output should look like ….
𝒏 𝒏!
0 1
1 1
2 2
3 6
4 24
5 120
6 720
7 5,040
8 40,320
9 362,880
10 3,628,800
3. Write a program that asks for a number (call it 𝑛) and, based on the number entered
display a triangle such as the one depicted as an example with 𝑛 = 5.
1
12
123
1234
12345
1234
123
12
1
4. Write a program that uses a loop – and 4 conditionals – to print out the following:
2. Unlucky 13. Write a program to generate and display 6 random numbers between 1 and
45. If any of the numbers generated are 13 stop the program with a message “Process
terminated – unlucky 13!”.
3. Five Quick Picks. Write a program to generate and display 5 rows of 6 numbers between
1 and 45
4. Write a program that simulates the rolling of a dice (Hint: use a random number between
1 and 6.) The program should continue until a six is ‘rolled’. The program should display
the number of rolls it took to reach 6.
5. Extend the above program to roll a dice 1000 times. Display the average score. Display
the number of times each number came up (i.e. number of ones, twos, threes, fours,
fives and sixes.)
6. Extend the earlier program to count the number of throws it takes to get ‘snake eyes’
Implement with one dice first i.e. a single roll at a time. Then two. (Snake eyes mean two
ones in a row with one dice or double ones if using two die.)
8. Study the program listing shown on the left hand side below and see if you can figure out
how it generates the output displayed on the right hand.
displayDigits(87)
displayDigits(261297)
displayDigits(5)
displayDigits(999)
e) Use the displayDigits() function above as a template for a function to count the
number of digits in a number. Call your function countDigits(). Test your function
countDigits() by making the following calls:
countDigits(87)
countDigits(261297)
countDigits(5)
countDigits(999)
number I x y
Now trace the value of each variable used by completing the table provided on the right
hand side.
10. Write a program to accept 3 numbers (i.e. DD MM YY) and determine whether the
numbers entered constitute a valid date. If the date entered is invalid print an appropriate
error message to the user. (Hint: You need to answer the question – what is a valid
date? Ignore the possibility of leap years.)
Write a program that asks a user to enter 6 results. For each result enter a code (‘H’ to
indicate the result is higher level; ‘O’ for ordinary level) followed by the actual
percentage. The program should then determine the relevant points for the percentage
entered and keep a running total of the points to date. Once the last result has been
entered the program should display the points total accumulated.
Can you think of any possible ways the program could be made more realistic? What if
the user didn’t enter the best 6 results? What about data validation? What about
additional points for Higher level Mathematics? How many times in one run could a user
enter a point’s value greater than 100? How might you incorporate an averaging
functionality?
String Processing
In this section you will learn more about ….
What a string is
The use of variables to store strings
How to concatenate two strings together
Accessing the characters of a string
o Indexing
o Slicing
String Processing (using loops to traverse a string)
o Counting letters, vowels
o Building up an output string
print("Hello World")
In this program the string Hello World is a string. It is passed as an argument into the built in
Python function called print. The function print causes the string to be displayed the string
on the output console.
It is useful to think of strings as a type of data for our programs to process. Python, like most
programming languages supports two basic types of data – strings and numbers. Numeric
data can be either whole numbers (i.e. integers) or decimal (i.e. float).
Variables can be used to reference string literals (in a similar manner to the way we have
already been using variables to store numeric data). For example, the following code snippet
would have the same effect as the above:
In the above program the string Hello World is assigned to the variable called message. Any
subsequent reference to this variable is a reference to the string. Therefore, when message
is passed as an argument to the print function, the effect is to display the text Hello World
as output.
Key Point: Strings can be referenced directly using string literals or indirectly by using
variables.
It is important to understand strings for the simple reason that they are one of the most
common types of data processed by computer programs and systems. Consider any system
that prompts a user to enter non-numeric data such as name or address. The values entered
are more than likely stored by the program as strings. Even data such as phone number
which you might think is numeric are often stored as strings – this is because a phone
number can contain non-numeric characters such as open bracket, ‘(‘, close bracket, ‘)’,
dashes, ‘-‘, or even the plus symbol, ‘+’.
As is the case with other datatypes such as ‘int’ and ‘float’ there are certain operations
associated with strings. The main operations are addition, multiplication, indexing and
slicing. These are now explained in turn.
Both programs below illustrate how the plus operator is used to concatenate strings.
The program on the left concatenates two string literals while the program on the right hand
side concatenates the two string referenced by the variables str1 and str2.
Assuming that the name of the user is stored in a variable called name, the following
program snippet will display such a welcome message.
name="Joe"
...
message = "Welcome"
print(message+" "+name)
The second line in the above snippet concatenates a space followed by the contents of the
variable name to the initial string referenced by message. Let’s say the string referenced by
name is Joe. The effect would be to display the message Welcome Joe.
Notice that the program snippet below does exactly the same thing.
name="Joe"
...
message = "Welcome "
print(message+name)
The difference between the two programs is very subtle but important to our understanding
of strings. In the second snippet the space character which separates the two strings is
contained (as the last character) in the string referenced by message. Therefore, it is not
necessary to concatenate the space character in the argument to print.
One of the key skills to the art of computer programming is a keen eye for detail. It is
therefore essential that programmers are completely aware and in control of every single
character that makes up a string. A characters can be thought of as any single symbol that
than be typed in from the keyboard.
The two strings referenced by variables string1 and string2 are concatenated together
in the same expression (line 3). Notice how the space is also included. The resulting string is
assigned to the variable string3. When the program is run it displays the string Cavan
Institute.
It is also perfectly legal (i.e. syntactically correct) to add/concatenate any mixture of string
literals and string variables. For example the following code snippets are valid.
2. Write a one line program that displays the string Hello Python users!
3. Change the program so that the string Hello Python users! is assigned to a variable
before being displayed.
4. Write a program that stores your first name in one variable (e.g. firstName) and your
surname in another variable (e.g. lastName) and finally prints out the result of
concatenating the two variables. (For example, if your first name is Joe and your
surname is Blogs the program will output JoeBlogs.)
5. Modify the above program so that it concatenates a space at the end of the first name
before concatenating the surname. (This time the output will be something like Joe
Blogs)
6. Write a program that prompts a user to input their first name (e.g. Joe) followed by their
surname (e.g. Blogs) and then print a message along the lines:
Hello Joe Blogs. Welcome to my crazy world!
7. Write a program that asks a user to enter a noun (e.g. apple) and then a number. If the
number is 1 the program should output the message – The singular of apple is apple. If
the number is greater than one the program output message should be – The plural of
apple is apples.
8. Read the short program below (type it in if you want) and then answer the questions
shown.
Consider the one line program shown below (the program does not display any output).
The program simply initialises a variable called message with the string Hello World. The
variable message is actually a reference to the string i.e. rather than containing the string, it
contains the address of the memory location where the string is stored. We shall see later on
that this concept of referencing is important but for the moment let us concentrate on the
string itself. In particular, we will look at the index or position of each character that makes
up the string. This is illustrate in the diagram below where the index of each character is
shown below the character.
As can be seen the first character i.e. ‘H’ has an index of zero. This is important. The first
character in a string always occurs at index position zero (this is often called the zeroth
position), the second character at index position 1, the third character at index position 2 and
so on. The string Hello World contains 11 characters and each character has a unique index
ranging from 0 to 10.
In general, when there are n characters in a string the last character always occurs at index
position n-1. Therefore, if there are 5 characters in a string the last character occurs at index
position 4.
Each individual character of a string can be accessed through the process of indexing. In
Python (and most programming languages) square brackets are used to denote the index
operation. To access a particular character in a string the character’s index is enclosed in
square brackets. For example, the first element of the above string can be accessed using
message[0]. Similarly,
message[0] H
message[1] e
message[2] l
message[3] l
message[4] o
message[5] ‘ ‘
message[6] W
message[7] o
message[8] r
message[9] l
message[10] d
Line 5 assigns the character stored at index position 0 i.e. ‘C’ to the variable c1. Line 9
assigns the character stored at index position 1 i.e. ‘a’ to the variable c2. The program
displays the following output:
C
a
v
a
n
As a final point it is worth noting that unlike most other programming languages, Python
permits the use of negative numbers as indices.
Note the use of negative indexing is not encouraged as it is not supported in most other
programming languages. As an exercise try adding the line ‘print(string[-6])’ to the above.
What happens?
Strings are immutable meaning that they cannot be changed. For this reason it is not
permitted to use the index operator ([]) on the left hand side of an assignment expression.
For example, the string Cavan could not be changed to Navan by using the following:
2. For each of the strings listed below answer the questions which follow.
2. print(town[0])
3. print(town[1])
4. print(town[2])
5. print(town[3])
6. print(town[4])
4. What error would be generated if the following line was added to the above program?
print(town[5])
5. What output would result from each call to the print function in following program
snippet?
str1 = "Hello"
str2 = "world"
str3 = str1+" "+str2+"!"
pos = 6
print(str1[1])
print(str2[4])
print(str3[0])
print(str3[4])
print(str3[5])
print(str3[pos]) # Note the use of a variable as the index
print(str3[10])
ch1 = str1[0]
ch2 = str2[1]
ch3 = str3[11]
print(ch1+ch2+ch3)
A
A town
tow
town
Cavan
town like Cavan
A town
Slicing is a useful way to extract part of a string (i.e. a substring) from a larger string. The
colon is delimited by the start and end position of the substring we are interested in
extracting. The resulting substring (or slice) runs from the starting index up to but not
including the end. If the start is missing it us assumed to be zero i.e. the first position of the
string. If end is missing it is assumed to be the last position of the string. What do you think
the statement ‘print(string[:])’ would output?
String Length
The length of any string is the number of characters in that string. A string length can be
obtained by using the len built in function. The use of the len function is illustrated in the
following example.
Since len return the actual number of characters in a string we say it is one based. Recall
that indices are zero based. Care must therefore be taken when using the result returned by
len as an index. The following line of coded (which attempts to access the last character of
the str) causes an ‘index out of range error’ because the index given by len(str) is one
greater than the required index. Line 9 of the previous program shows the correct way to
access the last character of a string using the len function.
uprCaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
lwrCaseLetters = "abcdefghijklmnopqrstuvwxyz"
letters = uprCaseLetters+lwrCaseLetters
print(uprCaseLetters[0:26])
print(uprCaseLetters[0:5])
print(uprCaseLetters[1:5])
print(uprCaseLetters[:5])
print(uprCaseLetters[20:25])
print(uprCaseLetters[20:])
print(letters[0:26])
print(letters[26:52])
2. Write a small program to extract the following strings from the string:
The quick brown fox jumps over the lazy dog
a) “quick”
b) “fox”
c) “The”
d) “The quick brown fox”
e) “jumps over the lazy dog”
3. Write a program that asks a user to input their first name (e.g. Joe) followed by their
surname (e.g. Blogs) and then outputs the initial of the forename followed by the
surname (e.g. JBlogs).
4. Write a program that asks a user to input their first name (e.g. Javier) followed by their
surname (e.g. Mascherano) and then outputs the initial of the forename followed by the
first seven characters of the surname (e.g. JMascher). Test your program using Joe
Blogs as the name.
5. Put a loop in the program from the previous exercise to keep going until the user enters
“quit” as the first name (i.e. use quit as the sentinel to end the loop).
6. Write a program that accepts a date in the format DDMMYY (e.g. 010114) and outputs
three lines e.g. Day is 01, Month is 01, Year is 2014.
7. Modify the last program to remove any leading zeros from the day and month (if they
occur). For an input of 010114 the output would be Day is 1, Month is 1, Year is 2014.
For an input of 120114 the output would be Day is 12, Month is 1, Year is 2014.
You should check each of the above out by passing the test string as the argument into the
print function. For example, use print("apple" < "banana") to verify the first test.
The comparison operators in and not in check whether a value occurs (does not occur) in
a string (or indeed any other ordered list). Like the relational operators, in and not in
return either True or False depending on whether the item being checked for is a member
of the list on the right hand side. The use of the in operator is illustrated in the table below.
1. For each of the following tests state whether the result would be True or False
The applications of string processing are wide and varied. One simple application of string
processing might be to analyse large volumes of text. For example, a user might be
interested in knowing the number of sentences or words a piece of text contains. Perhaps a
user might be interested in searching for and/or counting the number of occurrences of a
certain character (e.g. a vowel) or sequence of characters (e.g. a word) in a piece of text.
Another application of string processing is in the generation of ciphers that could be used to
encrypt or decrypt data.
The technique for string processing relies on the use of loops. The following program
demonstrates the use of a for loop to count the number of characters in a string.
Lines 3 and 4 of the above program initialise the variables str and count. The purpose of
the program is to count the number of characters in the variable referenced by str. The
variable count is just used to store the number of characters processed by the loop on line
5. Line 5 is the key line in this program. This line iterates through every character in the
string, str. Line 6 – the only line in the loop body - increments the value of count on each
iteration. By the time the loop has finished execution, the value of count will be the number
of characters in the string (i.e. the length of the string). Line 8 simply displays the value of
count before the program terminates.
In the interest of good design practice it is worth pointing out how the essence of the above
code could be captured using a function – we will call it length. It is important to study the
listing below and understand how it works and why it is more useful than the above code.
return count
string = "The quick brown fox jumps over the lazy dog"
l = length(string)
print(l)
The program is very similar to the one shown on the previous page. This time instead of
counting the characters in the string the program just displays each individual character on
the screen. The following code snippet has the same effect – this time using a for loop.
Note the use of the variables index and length in the above program – the former is used
as the index into the current character in string, str and the latter is used to store the length
of the string. Both variables are used to form the loop guard shown on line 8. The while loop
keeps going as long as the value of index is less than the value of length. Line 9 causes
the character at the current index position in str to be displayed. Line 10 increments the
index on each iteration of the loop.
Challenge. Modify the above code so that it uses a while loop instead of the for loop.
7. print(count)
Lines 4 and 5 are key. Line 4 sets up the loop to iterate through the string which was entered
by the user when line 1 was executed. The variable ch is used to store a reference to each
character in string as they are being iterated through. Line 5 asks the question is the current
character a vowel? If the answer is true line 6 is executed and the variable count is
incremented. In any case, execution continues at line 4 until all the characters in the string
have been processed. When the loop ends the value in count is displayed and the program
terminates.
print(count)
You should study the above code carefully paying particular attention to the use of variable
index.
Challenge. Modify the above code so that it is encapsulated in a function. The name of the
function should be countVowels. The function should accept one parameter – the string –
and return the number of vowels in the string. A sample call to the function would be:
The problem with the above program is that each word is displayed on a new line straight
after it is entered by the user. Our requirement is that all the words should be displayed on a
single line of output. A better solution is presented below:
1. sentence=""
2. word = input("Please enter a word (stop to end)")
3. while (word != "stop"):
4. sentence = sentence + word + " "
5. word = input("Please enter a word (stop to end)")
6.
7. print(sentence)
Notice the use of the variable sentence. The above program works by building up the
string referenced by this variable – from line 1 where sentence is initialised to an empty
string right through to line 7 which displays the final sentence. The loop works in the same
way as it did for the previous program i.e. it keeps executing until the word entered by the
user is stop. Line 4 is the key line. This line works by concatenating the word just entered to
the sentence accumulated so far. The resulting reference is assigned to the variable
sentence. Notice also how the space to separate the individual words is tagged on to the
end each time.
The table below illustrates how the sentence is built up for a sample run of the program in
which the user enters the following four words individually – The, quick, brown, fox.
The following initial attempt displays all the characters of str excluding vowels:
1. string = "The quick brown fox jumps over the lazy dog"
2. vowels = "aeiou"
3. for character in string:
4. if character not in vowels:
5. print(character)
1. string = "The quick brown fox jumps over the lazy dog"
2. vowels = "aeiou"
3. index = 0
4. length = len(string)
5. while index < length:
6. character = string[index]
7. if character not in vowels:
8. print(character)
9. index = index + 1
Both implementations have the same problem i.e. all the non-vowel characters are printed
as they are found. This means that they are separated by a newline. In order to have the
resulting string printed on a single line it is necessary to construct a new string by add the
non-vowel characters to it as they are found. This is done as follows:
1. string = "The quick brown fox jumps over the lazy dog"
2. newStr = ""
3. vowels = "aeiou"
4. for character in string:
5. if character not in vowels:
6. newStr = newStr + character
7.
8. print(newStr)
Notice how in the above example, the variable newStr is built up and added to every time a
non-vowel character is encountered.
Challenge. Modify the above code so that it uses a while loop instead of the for loop.
In essence, the reversed string is produced by first taking the last character of the input
string, and then the second last and so on until we reach the first character. In other words
we traverse the input string, starting from the last character and ending at the first. As we
encounter each character along our traversal we add (i.e. concatenate) it to some new
output string. By the end of the traversal this output string will have become the desired
reversed string. We can now develop our solution using the following pseudo-code:
We are now ready to implement our solution. Try running the following code to verify that it
works.
Although the above short program does what we initially set out to do i.e. it reverses a string,
its use is very limited because it only works once. Furthermore, the only string it ever
reverses is "The quick brown fox jumps over the lazy dog". It would be much better to have a
piece of code that could reverse any string and which could be used as often as we wanted
without having to duplicate the above lines. This can be accomplished by encapsulating the
functionality of the above in a single function (we will call reverseString). The string to be
reversed can be passed in as an argument to the function and the reversed string can be
returned from the function. The implementation is shown on the next page.
Challenge. Modify the above code so that it uses a for loop instead of the while loop.
7. What would be the effect of adding the following lines of code to the second snippet?
8. Generalist the function countLetters so that the second argument is also a string.
Lists (Arrays)
In this section you will learn more about ….
What is an array?
Array operations – indexing and slicing
Aliasing and Cloning an array
Lists are another example of a compound datatype. Unlike strings, which can only be
composed of other strings, lists can contain values of any datatype. (A simple analogy is a
shopping list - this is made up of a collection of numbers and strings e.g. 8 cartons of milk, 3
slice pan etc.)
A list is therefore an ordered collection of values whose datatypes can be different. Lists are
known as arrays in many other programming languages. (There are some technical
differences between lists and arrays, but these differences are so subtle that from a
beginner’s viewpoint it is fair to consider lists and arrays as the same thing.)
Lists can be initialised by enclosing comma delimited values with square brackets.
The following string operations (which you learned earlier) also apply to lists.
List
Concatenation
Operation
The two lists are joined together using the ‘+’ operator. The above code yields the
following output:
Individual elements of a list can be accessed by indexing. The first element of every list
occurs at index position zero, the second element at index position one and so on. The
index is specified inside square brackets positioned immediately after the name of the list
variable (or actual list.) The above code displays the following output.
Milk
Bread
1
2
3
4
5
6
The above code prints “The day is” followed by the abbreviated day. This is the day held
in the list at the position entered by the user. Remember that lists (like strings and arrays)
use a zero-based index and so we subtract one from the index.
While lists and strings have lots in common one important distinction is that lists are
mutable (i.e. their contents can be changed) while strings are not. This means that
elements can be inserted into lists, removed from a list, or simply changed.)
It is worth pointing out that the sliced list can be assigned to a variable thereby creating
another list. For example the following code results in the new list being stored in the
variable nonIrishFruits
len can be used to setup the loop guard when we require to iterate through each element
of a list. Consider the following code which iterates through each element of the list
daysOfWeek, printing out the current value on each iteration.
It is important to understand the use of the variable i as the index to the list, in the above
examples.
Finally, the following implementation of a list traversal algorithm is worth mentioning. Once
again this is just an alternative to the preceding two examples.
It should be noted that the above implementation does not make use of either indexing or
the len function and could therefore be considered a simpler more elegant solution to the
problem of list traversal.
List methods
A number of list methods (i.e. types of functions only associated with lists) deserve some
special mention.
The following block of code demonstrates the use of these methods. The last line (line 25)
results in the list ['apple', 'apple', 'banana', 'kiwi', 'orange', 'pear', 'peas'] being displayed (i.e.
at the end of the program this is the contents of the list fruits.)
You should read through the code carefully and try to understand how the final output is
arrived at.
Example 1
The following program simulates the selection of a random card from a deck of cards. (i.e.
pick a card, any card.)
As an exercise extend the above program to deal five unique cards. Start off by
encapsulating the above code in a function called dealCard. In phase 2 you will need to
create a loop inside which you call dealCard 5 times. (Hint: you will need to build up a new
list – call it hand – and each time a random card is generated append it to hand only if it is
not already in the hand.)
Example 2
The following program using a list to keep track of the frequency of outcomes from a roll of a
6-sided dice. (Each position in the list is used to represent the number of times that number
came up.)
Exercises
1. Extend the above code to run 1000 times (Hint: for i in range (1000):)
2. Modify your program to simulate the rolling of two dice – how many rolls before the sum
of the two dice make seven?
3. Try keeping track of the frequencies of the sum of both die.
The operator is (and is not) can be used to determine whether two objects are aliases of
one another or not (i.e. whether they are really the same object or not.) The is operator
returns True if the objects being compared are aliases of one another.
Try running the following code which demonstrates the difference between aliasing and
cloning.
In the above code any changes that are made to count1 are also made to count2. However,
since count3 starts out as a clone of count1, changes to count1 have no effect on count3.
Consider the function rollDice below which encapsulates the code in example 2 on the
previous page.
Line 12 of the above code passes in the list referenced by count as an argument into the
function rollDice where it is received as the parameter named freqList. It is important
DESIGN YOUR SOLUTION USING PEN AND PAPER BEFORE WRITING YOUR
PROGRAM.
IMAGINE WHAT THE RUNNING PROGRAM WOULD LOOK OUT – screens, inputs,
outputs – AND WORK TOWARDS THAT.
TEST FOR NORMAL CONDITONS FIRST. ENSURE YOUR TEST CASES CAUSE
EVERY LINE OF CODE TO BE EXECUTED AT LEAST ONCE and CHECK
BOUNDARY CONDITIONS
Also,
Develop a style of programming and stick to it consistently e.g. be consistent with the
number of spaces you use for indentation
Keep import statements at the top of your file
Functions must be defined before they are called so keep all function definitions towards
the top of your program (after the imports)
Use two/three blank lines to separate functions
Use meaningful names for variables and functions.
Variable names cannot begin with a number (or contain spaces). Same for function
names.
Use lowercase letters for naming variables and functions (e.g. address). If a variable or
function name is two words use ‘camel case’
Avoid the use of global variables if at all possible – pass information using parameters
and as return values.
Get into the habit of using lots of comments to explain your code
Practice, practice, practice – you won’t get it right first time so keep going back over the
exercises