Programming 511 Study Guide (Python)
Programming 511 Study Guide (Python)
PROGRAMMING 511
(PROGRAMMING USING PYTHON)
FIRST SEMESTER
YEAR 1
FACULTY OF INFORMATION TECHNOLOGY
STUDY GUIDE
Copyright © 2023
Richfield Graduate Institute of Technology (Pty) Ltd
Registration Number: 2000/000757/07
All rights reserved; no part of this publication may be reproduced in any form or by any means, including photocopying
machines, without the written permission of the Institution
Table of Contents
SECTION A: PREFACE............................................................................................. 1
INTRODUCTION ........................................................................................................ 1
METHOD OF STUDY................................................................................................. 2
ASSESSMENT ........................................................................................................... 4
TOPIC 1 ................................................................................................................... 10
INTRODUCTION TO COMPUTERS AND PROGRAMMING .................................. 10
i
TOPIC 2 ................................................................................................................... 26
PYTHON FUNDAMENTALS.................................................................................... 26
TOPIC 3 ................................................................................................................... 54
DECISION STRUCTURES AND BOOLEAN LOGIC .............................................. 54
ii
3.5 Nested Decision Structures and the if-elif-else Statement ................................ 62
TOPIC 4 ................................................................................................................... 73
TOPIC 5 ................................................................................................................... 88
FUNCTIONS ............................................................................................................ 88
iii
5.5 Passing Arguments to Functions ........................................................................ 96
6.9 Reading a File with a Loop and Detecting the End of the File .......................... 129
iv
SECTION A: PREFACE
INTRODUCTION
We trust you will find the contents and learning outcomes of this module both
interesting and insightful as you begin your academic journey and eventually, your
career in the IT world. This section of the study guide is intended to orientate you to
the module before the commencement of formal lectures. The following lectures will
focus on the study units described
Module details
Table 1: Module details
Programming 511
1
This module exposes learners to the various aspects of programming, including
understanding the fundamentals of data storage, input and output, functions,
sequences and lists, file I/O, decision structures and boolean logic, repetition
structures, functions, files and exceptions, lists and tuples, dictionaries and sets,
classes, object-oriented programming, inheritance and objects that are created from
standard library classes.
METHOD OF STUDY
Only the key sections that have to be studied are indicated under each topic in this
study guide are expected to have a thorough working knowledge of the prescribed
textbook. These form the basis for tests, assignments and examinations. To be able to
do the activities and assignments for this module, and to achieve the learning
outcomes and ultimately to be successful in the tests and exams.
You will need an in-depth understanding of the content of these sections in the learning
guide and the prescribed books. To master the learning material, you must accept
responsibility for your studies. Learning is not the same as memorising. You are
2
expected to show that you understand and can apply the information. Lectures,
tutorials, case studies and group discussions may also be used to present this module.
NOTICES
All information about this module such as tests dates, lecture and tutorial timetables,
assignments, examinations etc. will be displayed on the notice board located at your
campus. Students must check the notice board daily. Should you require any
clarification, please consult your lecturer, programme manager or administrator of your
respective campus.
RECOMMENDED MATERIAL
Python.org. (2019). The Python Tutorial — Python 3.8.0 documentation. [online]
Available at: https://docs.python.org/3/tutorial/.
3
LIBRARY INFRASTRUCTURE
The following services are available to you:
Each campus keeps a limited quantity of the recommended reading titles and a
wider variety of similar titles which you may borrow. Please note that students
are required to purchase the prescribed materials.
Arrangements have been made with municipal, state and other libraries to stock
our recommended reading and similar titles. You may use these on their
premises or borrow them if available. It is your responsibility to safe keeps all
library books.
RGIT has also allocated one library period per week to assist you with your
formal research under professional supervision.
RGIT has dedicated electronic libraries for use by its students. The computers
laboratories, when not in use for academic purposes, may also be used for
research purposes. Booking is essential for all electronic library usage.
ASSESSMENT
The assessment for this module will comprise two Continuous Assessment (CA) Tests,
an assignment and an examination. Your lecturer will inform you of the dates, times
and the venues for each of these. You may also refer to the notice board on your
campus or the Academic Calendar, which is displayed in all lecture rooms.
CONTINUOUS ASSESSMENT TESTS
ASSIGNMENT
There is one compulsory assignment for each module in each semester. Your lecturer
will inform you of the Assignment questions at the commencement of this module.
EXAMINATION
There is one three-hour examination for each module. Make sure that you diarise the
correct date, time and venue. The examinations department will notify you of your
results once all administrative matters are cleared, and fees are paid up. The
examination may consist of multiple-choice questions, short questions and essay type
questions.
4
This requires you to be thoroughly prepared as all the content matter of lectures,
tutorials, all references to the prescribed text and any other additional
documentation/reference materials are examinable in both your tests and the
examinations. The examination department will make available to you the details of
the examination (date, time and venue) in due course. You must be seated in the
examination room 15 minutes before the commencement of the examination. If you
arrive late, you will not be allowed any extra time. Your learner registration card must
always be in your possession.
FINAL ASSESSMENT
There are two compulsory tests for each module (in each semester). The final
assessment for this module will be weighted as follows:
CA Test 1 13%
CA Test 2 13%
Assignment 14%
Examination 60%
Total 100%
Question Cues
list, define, tell, describe, identify, show, label, collect, examine, tabulate,
quote, name, who, when, where, etc.
Understanding information
Grasp meaning
Translate knowledge into a new context
Interpret facts, compare, contrast
Order, group, infer causes
Comprehension
Predict consequences
Question Cues
summarize, describe, interpret, contrast, predict,
associate, distinguish, estimate, differentiate, discuss, extend
Use information
Use methods, concepts, theories in new situations
Solve problems using required skills or knowledge
Application
Questions Cues
apply, demonstrate, calculate, complete, illustrate, show, solve, examine,
modify, relate, change, classify, experiment, discover
Seeing patterns
Organisation of parts
Recognition of hidden meanings
Identification of components
Question Cues
Analysis
6
Use old ideas to create new ones
Generalise from given facts Relate knowledge from several areas
Predict, draw conclusions
Question Cues
Synthesis
Question Cues
assess, decide, rank, grade, test, measure, recommend, convince, select,
judge, explain, discriminate, support, conclude, compare, summarise
Soft skills
Employment skills
Life skills
End-User Computing (if not included in your curriculum)
It is in your interest to attend these workshops, complete the Work Readiness Logbook
and prepare for the working world. The illustration below outlines some of the key
concepts for Work Readiness that will be included in your timetable.
7
Figure 1: Work Readiness
SOFT SKILLS
•Time management
•Working in Teams
•Problem solving skills
•Attitude & goal
setting
•Etiquettes & Ethics
Work
EMPLOYMENT
SKILLS
Readiness LIFE SKILLS
•CV writing skills •Manage personal
•Interview skills finance
•Presentation skills •Driving skills
•Employer/Employee •Basic life support &
relationship first aid
•End-user computing
8
Students will be fully inducted on the Work Integrated Learning Module, the Workbooks
& assessment requirements before placement with employers. The partners in the
Work Integrated Learning are the same as the Work Readiness Programme:
9
TOPIC 1
INTRODUCTION TO COMPUTERS AND PROGRAMMING
Learning Outcomes:
After studying this topic you should be able to:
• Understand how computers work
• Understand how data is stored and manipulated
• Understand why we write programs in high level languages
• Write programs using the correct Python language syntax
1.1 Introduction
The first part of this topic explains how computers work, how data is stored and
manipulated, and why we write programs in high-level languages. Python, interactive
mode, script mode, and the IDLE environment are all introduced.
The uses of computers are almost limitless in our everyday lives. In school, students
use computers for tasks such as writing papers, searching for articles, sending email,
and participating in online classes. At work, people use computers to analyse data,
conduct business transactions, communicate with customers and co-workers, control
machines in manufacturing facilities, and do many other things. And don't forget that
cell phones, tablets, smart phones, car navigation systems, and many other devices
are computers too.
Computers can perform such a wide variety of tasks because they can be
programmed. This means that computers are not designed to do just one job, but to
do any job that their programs tell them to do. A program, commonly referred to as
software, is a set of instructions that a computer follows to perform a task. Python is
one of the programming languages that can be used for writing these programs, and it
would be a good choice.
10
Figure 1-1 A word processing program and a presentation program (Gaddis, 2021)
11
Figure 1-2 Typical components of a computer system (Gaddis, 2021)
12
Figure 1-3 The ENIAC computer (Gaddis, 2021)
Main Memory
13
Known as the random-access memory, it serves as the computer's work area and
stores both the data and the running programs (RAM). RAM is a volatile sort of memory
that can be quickly accessed, used for temporary storage, and erased when the
machine is shut down. See Figure 1-2.
Input Devices
Any data the computer collects from people and from other devices is called input. The
hardware component that collects the data is called an input device. The following are
some of the common input devices are: keyboard, mouse, scanner, microphone, digital
camera etc.
Output Devices
Any data the computer produces for people or for other devices is called output. The
hardware component that formats and presents the data is called an output device.
Some of the common output devices are: monitor, printer etc.
14
1.2.2 Software
Everything that a computer does is controlled and managed by software. The two
categories of software are: system software and application software.
System Software controls and manages the basic operations of a computer. Types of
system software include:
• Operating System: controls the internal operations of the computer’s hardware and
manages all of the devices connected to the computer.
• Utility Programs: perform a specialized task that enhances the computer’s
operation or safeguards data.
• Software Developments Tools: are programs that are used to create, modify, and
test software.
Application Software: programs that people normally spend most of their time running
on their computers performing everyday tasks are referred to as application software.
For example: Microsoft Word (Word processing program), PowerPoint (a presentation
program), spreadsheet, email programs, web browsers, and game programs.
Checkpoint: Can you think of any other application software?
15
A positive charge is similar to a switch in the on position while a negative charge is
similar to a switch in the off position.
16
For example:
Figure 1-7 Determining the value of 10011101 (The bit pattern for 157)
Source: Gaddis (2021) page 9
The largest value that can be stored in a byte with eight bits is 255 and two bytes are
used for larger numbers; maximum value is 65535
17
Characters are stored in the computer’s memory as binary number. The ASCII
(American Standard Code for Information Interchange) is set of 128 numeric codes
that represent the English letters, various punctuation marks, and other characters.
For example, the ASCII code for the uppercase letter A is 65.
Your computer stores the number 65 when you input an uppercase A using the
keyboard. This 65 is stored as a binary number.
18
Only machine language-written programs can be run on computers. A program may
have thousands or even millions of binary instructions, as was already indicated;
developing such a program would be laborious and time-consuming. A 0 or a 1 in the
wrong position will result in an error, making machine language programming
extremely challenging.
However, the CPU cannot run assembly language programs, it understands machine
language instructions. An assembly language program is converted to a machine
language program using a special program called an assembler.
High-level languages allow you to create powerful and complex programs without
knowing how the CPU works, using words that are easy to understand.
Examples of high level programming languages include:
Ada, BASIC, Python, C++, Ruby, Visual Basic etc.
The same task might be accomplished in assembly language with a few instructions
and would require a thorough understanding of how the CPU communicates with the
computer's output device.
19
Each high-level language has its own set of predefined words that the programmer
must use to write a program. Key words or reserved words have specific meaning and
purpose in the programming language. Programming languages also have:
• Operators - perform various operations on data
• Syntax - a set of rules that must be strictly followed when writing a program
• Statements - individual instructions written in a programming language
An interpreter is a program that both translates and executes the instructions in a high-
level language program
20
Figure 1-11 Executing a high-level program with an interpreter
21
Figure 1-12 IDLE
22
Review Questions
A(n) __________ is a set of instructions that a computer follows to perform a task.
a. compiler
b. program
c. interpreter
d. programming language
2. The physical devices that a computer is made of are referred to as __________.
a. hardware
b. software
c. the operating system
d. tools
3. The part of a computer that runs programs is called __________.
a. RAM
b. secondary storage
c. main memory
e. the CPU
4. A component that collects data from people or other devices and sends it to the
computer
is called __________.
a. an output device
b. an input device
c. a secondary storage device
d. main memory
5. A video display is a(n) __________ device.
a. output
b. input
c. secondary storage
d. main memory
6. A __________ is enough memory to store a letter of the alphabet or a small number.
a. byte
b. bit
c. switch
d. transistor
23
7.The words that make up a high-level programming language are called __________.
a. binary instructions
b. mnemonics
c. commands
d. keywords
8. The rules that must be followed when writing a program are called __________.
a. syntax
b. punctuation
c. keywords
d. operators
9. A(n) __________ program translates a high-level language program into a separate
machine language program.
a. assembler
b. compiler
c. translator
d. utility
True/False
10. A syntax error does not prevent a program from being compiled and executed.
11. Windows, Linux, Android, iOS, and macOS are all examples of application
software.
12. Word processing programs, spreadsheet programs, email programs, web
browsers, and games are all examples of utility programs.
Exercise
To make sure that you can interact with the Python interpreter, try the following steps
on your computer:
• Start the Python interpreter in interactive mode.
• At the >>> prompt, type the following statement then press Enter:
print('This is a test of the Python interpreter.') Enter
• After pressing the Enter key, the interpreter will execute the statement. If you typed
everything correctly, your session should look like this:
>>> print('This is a test of the Python interpreter.') Enter
24
This is a test of the Python interpreter.
>>>
• If you see an error message, enter the statement again, and make sure you type it
exactly as shown.
• Exit the Python interpreter. (In Windows, press Ctrl-Z followed by Enter. On other
systems, press Ctrl-D.)
25
TOPIC 2
PYTHON FUNDAMENTALS
Learning Outcomes
After studying this topic you should be able to:
• Design a program
• Display Output with the print function
• Add comments and use variables
• Read input from the keyboard
• Perform calculations and string Concatenation
• Display formatted output with F-strings
• Use named constants
2.1 Introduction
This topic introduces the program development cycle, variables, data types, and simple
programs that are written as sequence structures. The student learns how to write
simple programs that read input from the keyboard, perform mathematical operations,
and produce formatted screen output. Pseudocode and flowcharts are also introduced
as tools for designing programs.
26
Figure 2-1 The program development cycle
Refer to page 31 of the recommended textbook.
Pseudocode
Programmers need to be careful while writing code because syntax errors like
misspelled words and forgotten punctuation characters might occur. As a result,
programmers find it helpful to write a program in pseudocode.
27
The word “pseudo” means fake, so pseudocode is fake code. It is an informal language
that has no syntax rules and is not meant to be compiled or executed. Instead,
programmers use pseudocode to create models, or “mock-ups,” of programs.
Programmers may give their full attention to the design of the program because they
don't have to worry about syntax errors when writing pseudocode.
For Example:
Write pseudocode to calculate and display the gross pay for an hourly paid employee.
Input the hours worked
Input the hourly pay rate
Calculate gross pay as hours worked multiplied by hourly pay rate
Display the gross pay
Flowchart
Flowcharts are often used to visually represent algorithms and logic structures.
Flowcharts help programmers to understand and develop complex logic, as well as to
communicate the logic to others. Flowcharts are especially useful in programming
languages that require a lot of decision-making, such as if-then-else statements, loop
structures, and switch statements.
The arrows that connect the symbols represent the "flow" of the program. You start at
the Start terminal and follow the arrows to the End terminal in order to step through the
symbols in the correct order.
1. Input is received
2. Some process is performed on the input
3. Output is produced
29
Figure 2-3 The input, processing, and output of the pay calculating program
To print the Python Programming, use the Python print function as follows:
Output:
South Africa
Zimbabwe
Zambia
30
Botswana
Malawi
Output
Don't hate your neighbour!
I'm enjoying everything about programming!
Similarly, you can enclose a literal string that uses double quotes as part of the string
inside single-quote marks.
print('Your assignment is to read "Hamlet" by tomorrow.')
Output
Your assignment is to read "Hamlet" by tomorrow.
31
Triple quotes in Python allow you to create multi-line strings, preserving the line breaks
and white space. You can use either single quotes (' ' ') or double quotes (" " ") as triple
quotes, as long as they match on both ends.
The following example demonstrates how to use triple quotes in Python:
Using triple single quotes
string_1 = '''Hello,
World!'''
print(string_1)
Output:
Hello,
World!
print(string_2)
Output:
Hello,
World!
2.5 Comments
In Python, comments are used to add explanations and annotations to your code. They
are ignored by the Python interpreter and do not affect the execution of the code.
Single-line comments - starts with the # symbol and continue until the end of the line.
For example:
32
# This is a single-line comment
Multi-line comments - start and end with triple quotes (either ' ' ' or " " ").
For example:
"""
This is a
multi-line comment
"""
It is a good practice to add comments to your code to explain what it does, how it
works, and why it is designed the way it is. This makes your code easier to understand
and maintain, especially for other people who might be working on the same code.
More examples:
1. Full-line comment
# This program calculates net pay
2. End-line comment
Print “John Smith” # Display the name
2.6 Variables
In Python, a variable is a named location in memory where you can store a value. You
can use a variable to store data, such as numbers, strings, lists, and dictionaries, and
then use that data in your program.
To create a variable in Python, you use the assignment operator (=) to assign a value
to a name.
variable=expression
where, variable is the name of the variable, = is the assignment operator and
expression is the value or piece of code that results in a value.
For example:
x = 42
y = "Hello, World!"
z = [1, 2, 3]
33
After these assignments, the variable x will hold the value 42, the variable y will hold
the string value "Hello, World!", and the variable z will hold the list value [1, 2, 3].
In Python, there is no need to declare the type of a variable before using it. The type
of a variable is determined by the type of the value assigned to it.
It's a good practice to give your variables meaningful names that describe what they
are used for. Avoid using names that are already used as keywords or built-in functions
in Python.
More examples
age = 25
After this statement executes, a variable named age will be created, and it will
reference the value 25.
34
Sample variable names
Output
First item: 1
Second item: 2
Output
I am staying in room number 503
If you want to display items on the same line, you can use the end parameter of the
print() function:
You can also use the sep parameter to change the separator between items:
print("First item:", 1, sep=" | ")
print("Second item:", 2, sep=" | ")
Output
First item: | 1
Second item: | 2
Variable Reassignment
Variables, as the name suggests, can reference different values while a program is
running. When you assign a value to a variable, the variable will reference that value
until you assign it a different value. In Python, you can reassign a variable to a new
value at any time. This is done by using the assignment operator (=).
For example:
x = 10
print(x) # Output: 10
x = 20
36
A variable named dollars is created in line 3 and given the value 2.75. Then, the dollar
variable is given a new value, 99.95, by the statement on line 8. The lower half of the
above program illustrates how this alters the dollars variable.
Even though the previous value of 2.75 is still there in the computer's memory, it can
no longer be used because it is not referenced by a variable. The Python interpreter
does automatically remove that value from memory through a process known as
garbage collection.
In Python, you can determine the data type of a value using the type() built-in function.
For example:
type(1)
Output
<class 'int'>
37
When the value 1 is passed as an argument to the type () function, the output (<class
'int'>) indicates that the value is an int.
Here is another example that passes 1.0 as an argument:
type(1.0)
Output
<class 'float'>
The output indicates that the value is a float.
string1 = 123
print(type(string1))
Output
<class 'str'>
<class 'int'>
38
Here, the variable string1 is first assigned a string value 'Hello World', and its type is
str. But later in the code, string1 is reassigned to the integer value 123, and its type
changes to int.
This means that in Python, you can reassign a variable to a value of a different type
without any issues. However, this can also lead to unexpected behavior and errors if
you are not careful, so it's important to be aware of the type of the values you're working
with.
Think point:
Look at the following assignment statements:
value1 = 99
value2 = 45.9
value3 = 7.0
value4 = 7
value5 = 'abc'
After these statements execute, what is the Python data type of the values
referenced by each variable?
It is important to note that the value returned by input() is always a string, even if the
user enters a number. To use the value as a number (e.g. integer or float), you need
to convert it explicitly using the appropriate conversion function (e.g. int(), float(), etc.).
For example:
age = input('What is your age? ')
39
age = int(age)
print('You are ' + str(age) + ' years old.')
Output
You are [user-entered value] years old.
Here, the user is prompted to enter their age, which is stored as a string in the age
variable. The line age = int(age) then converts the string to an integer, and the line
print('You are ' + str(age) + ' years old.')
Output
Program Output (with input shown in bold)
What is your name? Chris Enter
What is your age? 25 Enter
What is your income? 75000.0
Here is the data you entered:
Name: Chris
Age: 25
Income: 75000.0
40
Example
a = 5
b = 3
addition = a + b
subtraction = a - b
multiplication = a * b
division = a / b
floor_division = a // b
modulus = a % b
exponentiation = a ** b
41
Integer Division
Integer division is the behaviour that results when an integer is divided by another
integer resulting in the answer being an integer as well.
For Example:
num_add = 17 + 5 # the answer will be 22
num_div_int = 3 / 2
# the answer is 1; 0.5 is the fractional part and it is truncated.
num_div_real = 3.0 / 2.0 # the answer is 1.5
result = a + b * c ** 2
print(result) # Output: 29
In this example, c is first raised to the power of 2, then multiplied by b, and finally the
sum of a and the previous result is obtained.
Example Expressions
42
Grouping with Parentheses
% is the remainder operator. Its purpose is to perform division and return the
remainder.
For Example: leftover = 17 % 3 #remainder is 2
43
2.7.3 Data Type Conversion
Python follows the following rules when evaluating mathematical expressions:
When an operation is performed on two int values, the result will be an int.
When an operation is performed on two float values, the result will be a float.
When an operation is performed on an int and a float, the int value will be
temporarily converted to a float and the result of the operation will be a float.
For example:
x = 27.9
y = int(x) # y will be assigned 27
x = -12.9
y = int(x) # y will be assigned -12
y = 7
x = float(y) # x will be assigned 7.0
In Python, statements can be broken down into multiple lines by using the line
continuation character ( \ ).
For example:
units_sold = 10
sales_amount = 100
print('We sold', units_sold, 'for a total of', sales_amount)
44
var1 = 1
var2 = 2
var3 = 3
var4 = 4
result = var1 * 2 + var2 * 3 + \
var3 * 4 + var4 * 5
print(result)
2.8 Escape Characters and String Concatenation
In Python, escape characters are used to represent certain special characters within a
string. The backslash (\) is used as an escape character to indicate that the character
following it should be treated specially.
A special character that is preceded with a backslash (\), appearing inside a literal.
For example:
print ‘One\nTwo\nThree’
Output
One
Two
Three
String concatenation is achieved through the use of the string concatenation operator
(+).
For example:
print('this is' + 'one string.') # one string is appended to another
45
Output
This is one string
In Python, Implicit String Literal Concatenation is a feature that allows multiple string
literals to be concatenated together without the need for explicit concatenation
operators such as + or \
For example:
print("Hello "
"world")
Output
Hello world
This feature can be useful for breaking up long string literals into multiple lines, making
the code easier to read and maintain. Note that this only works for string literals and
not for variables or expressions.
Here's an example:
print("This is the first part", end="")
print(" and this is the second part.")
Output
This is the first part and this is the second part.
You can also specify an item separator for print statements by using the sep parameter
of the print function. By default, sep is set to ' ' (a single space), but you can change it
to any string value you want.
For example:
print(1, 2, 3, sep=", ")
Output
1, 2, 3
46
2.9 Formatting
2.9.1 Formatting the output of a print statement
You can format the output of a print statement in a variety of ways. Some of the most
common methods include:
1. Concatenation: You can concatenate strings using the + operator, and you can
convert non-string values to strings using the str function.
name = "John"
age = 32
print("My name is " + name + " and I am " + str(age) + " years
old.")
2. format() function: To format the output of a print statement in Python, you can use
the format() method. This method allows you to specify placeholders in the string
to be printed, and then replace those placeholders with actual values. For example:
name = "John Doe"
age = 30
print("My name is {} and I am {} years old.".format(name, age))
Output
My name is John Doe and I am 30 years old.
3. Using f-strings: You can also use f-strings, which are a more recent way to format
strings in Python, introduced in Python 3.6:
name = "John Doe"
age = 30
print(f "My name is {name} and I am {age} years old.")
Output
My name is John Doe and I am 30 years old.
This would give the same output as the format() method.
In the above code, %.2f is a placeholder for the formatted floating-point number
my_value with 2 decimal places. The % operator replaces the placeholder with the
actual value, and the resulting string is printed to the console.
Here, .2f specifies that the number should be formatted as a floating point with 2
decimal places.
Another example:
Output
48
The values are 6.8 and 1.235
You can also format integers and other numerical values in a similar way. For example:
integer = 42
print(f"The integer is: { integer:d }")
Output
The integer is: 42
Here, d specifies that the value should be formatted as a decimal integer.
GRAVITY = 9.8
49
This is just a convention and not enforced by the language itself, so it is still possible
to change the value of these variables. To enforce the immutability of a value, one
could use the constant library in Python or simply use a tuple or a namedtuple.
PI = 3.14159265
radius = 5
area = PI * (radius**2)
Output
In this example, the named constant PI is used in the calculation of the area of a circle.
The value of PI is not expected to change, so it is created as a named constant. The
radius is given a value of 5 and the area of the circle is calculated using the formula PI
* (radius**2). The result is then printed to the console.
Think point: Despite named constants being mutable, why is it important to use them
instead of magical numbers?
Review Questions
1.A __________ error does not prevent the program from running, but causes it to
produce
incorrect results.
a. syntax
b. hardware
c. logic
d. fatal
2. A __________ is a single function that the program must perform in order to satisfy
the customer.
a. task
b. software requirement
50
c. prerequisite
d. predicate
3. An informal language that has no syntax rules and is not meant to be compiled or
executed is called __________.
a. faux code
b. pseudocode
c. Python
d. a flowchart
4. A __________ is a diagram that graphically depicts the steps that take place in a
program.
a. flowchart
b. step chart
c. code graph
d. program graph
5. A __________ is a sequence of characters.
a. char sequence
b. character collection
c. string
d. text block
13. Write assignment statements that perform the following operations with the
variables a, b, and c:
a. Adds 2 to a and assigns the result to b
b. Multiplies b times 4 and assigns the result to a
c. Divides a by 3.14 and assigns the result to b
d. Subtracts 8 from b and assigns the result to a
14. One acre of land is equivalent to 43,560 square feet. Write a program that asks the
user to enter the total square feet in a tract of land and calculates the number of acres
in the tract.
Hint: Divide the amount entered by 43,560 to get the number of acres.
15. Assuming there are no accidents or delays, the distance that a car travels down
the interstate can be calculated with the following formula:
Distance = Speed X Time
A car is traveling at 70 miles per hour. Write a program that displays the following:
• The distance the car will travel in 6 hours
• The distance the car will travel in 10 hours
52
• The distance the car will travel in 15 hours
53
TOPIC 3
DECISION STRUCTURES AND BOOLEAN LOGIC
Learning Outcomes
After studying this topic you should be able to:
• Write programs that use the if Statement
• Write programs that use the if-else Statement
• Write programs that compare strings
• Use nested decision structures and if-elif-else statement in writing
programs
• Implement programs that use logical operators
• Implement programs that use boolean variables
3.1 Introduction
Decision can be made using decision structures and conditions. The student will gain
knowledge of relational operators, Boolean expressions, and decision structures in this
topic. They will also learn how to control the flow of a program. We examine the if, if-
else, and if-elif-else statements; also covered are nested decision structures and
logical operators.
On the other hand, a decision (or selection) structure is a control structure that can
execute a set of statements and perform a specific action only if a certain condition
exists. The most common way to implement a decision structure is with an if statement.
Decision (selection) structure: Diamond symbol represents a true/false condition
Single alternative decision structure provides only one alternative path of execution.
54
Figure 3.1 A simple decision structure
if condition:
statement
statement
statement
etc.
In the above syntax, the 3 statements are executed only if the condition is true.
x = 10
if x > 5:
print("x is greater than 5")
In this example, the condition x > 5 is True, so the code inside the if statement will be
executed and the output will be "x is greater than 5".
55
Relational operators are used to compare values and determine the relationship
between them. The relational operators in Python are:
== (equal to)
!= (not equal to)
> (greater than)
< (less than)
>= (greater than or equal to)
<= (less than or equal to)
These operators return a boolean value of True or False based on the comparison
between the values. For example:
3 == 3 This expression returns True because the two values being compared (3 and
3) are equal to each other.
"hello" == "hello" This expression returns True because the two strings being
compared are identical.
3 != 4 This expression returns True because the two values being compared (3 and 4)
are not equal to each other.
"hello" != "world" This expression returns True because the two strings being
compared are not the same.
4 >= 4 This expression returns True because 4 is equal to 4, and 4 is also greater than
or equal to 4.
56
1 <= 4 This expression returns True because 3 is less than or equal to 4.
Here is an example:
# Three test scores
test_score1 = 80
test_score2 = 90
test_score3 = 95
Output
Congratulations! Your average score is above 90.
In this example, the average of the three test scores is calculated and stored in the
variable average. Then, an if statement is used to check if the value of average is
greater than 90. If the condition is true (i.e., average > 90), the message
"Congratulations! Your average score is above 90." is displayed.
57
Source: Gaddis (2021) Page 125
if condition:
statement
statement
etc.
else:
statement
statement
etc.
58
Figure 3-2 A dual alternative decision structure
Indentation is used to indicate blocks of code and determine the scope of variables
and control structures. In an if-else statement, the code inside each block is indented
from the if or else keyword. The standard indentation is 4 spaces, but you can use any
number of spaces as long as you are consistent.
59
3.4 Comparing Strings
You can compare strings using the equal to (==) and not equal to (!=) operators, as
well as the comparison functions such as "cmp()" (which is deprecated in Python 3).
In Python, string comparison is case-sensitive by default.
Here is an example:
# Define two strings
string1 = "Hello"
string2 = "World"
Output
The strings are not equal.
string1 = "Hello"
string2 = "World"
Output
string1 is not greater than string2.
Output
string1 is less than string2.
Note the following points about ASCII codes for representing characters:
• The uppercase characters A through Z are represented by the numbers 65 through
90.
• The lowercase characters a through z are represented by the numbers 97 through
122.
• When the digits 0 through 9 are stored in memory as characters, they are
represented
• by the numbers 48 through 57. (For example, the string 'abc123' would be stored
• in memory as the codes 97, 98, 99, 49, 50, and 51.)
• A blank space is represented by the number 32.
When a program compares characters, it actually compares the codes for the
characters.
61
3.5 Nested Decision Structures and the if-elif-else Statement
62
else:
print(f'You must have been employed '
f'for at least {MIN_YEARS} '
f'years to qualify.')
else:
print(f'You must earn at least $'
f'{MIN_SALARY:,.2f} '
f'per year to qualify.')
if x > 0:
if x < 100:
print("x is positive and less than 100")
else:
print("x is positive and greater than or equal to 100")
else:
print("x is negative or zero")
if condition_1:
statement
statement
etc.
elif condition_2:
statement
statement
etc.
63
else:
statement
statement
etc.
Here is an example:
x = 42
if x < 0:
print("x is negative")
elif x == 0:
print("x is zero")
else:
print("x is positive")
In this example, x is compared to 0 first. If x is less than 0, the first branch is taken and
the message "x is negative" is printed. If x is equal to 0, the second branch is taken
and the message "x is zero" is printed. If x is greater than 0, the final branch is taken
and the message "x is positive" is printed.
Note that the elif clause is optional, and you can have multiple elif clauses. When a
condition is met, the corresponding branch is executed and the remaining conditions
are skipped.
64
else:
print (‘Your grade is A.’)
Example:
x = 5
y = 10
65
if x < 10 and y > 5:
print("Both conditions are True")
else:
print("One of the conditions is False")
Output
Both conditions are True
In the above example, both x < 10 and y > 5 are True, so the expression x < 10 and y
> 5 is True. This means that both conditions are True and the if block gets executed.
Another example:
Example:
x = 5
y = 10
if x < 10 or y < 5:
print("At least one condition is True")
66
else:
print("Both conditions are False")
Output
At least one condition is True
In the above example, x < 10 is True and y < 5 is False, so the expression x < 10 or y
< 5 is True. This means that at least one condition is True and the if block gets
executed.
x = 5
if not (x < 10):
print("x is not less than 10")
else:
print("x is less than 10")
Output
x is not less than 10
Here is another example for a program that prints a message if temperature is not
greater than 100 degrees.
67
In Python, logical operators <, >, <=, >=, ==, and != are used to compare values and
check if a number falls within a specific range.
The following four examples all check if a number is within a specific range:
Example 1:
if x >= 20 and x <= 40:
print (‘The value is in the acceptable range.’)
Example 2:
if x < 20 or x > 40:
print (‘The value is outside the acceptable range.’)
Example 3:
# This is an error!
if x < 20 and x > 40:
print (‘The value is outside the acceptable range.’)
Example 4:
num = 10
if num >= 0 and num <= 10:
print("Number is within the range 0 to 10")
else:
print("Number is outside the range")
69
Review Questions
Multiple Choice
1. A __________ structure can execute a set of statements only under certain
circumstances.
a. sequence
b. circumstantial
c. decision
d. Boolean
2. A __________ structure provides one alternative path of execution.
a. sequence
b. single alternative decision
c. one path alternative
d. single execution decision
3. You use a(n) __________ statement to write a dual alternative decision structure.
a. test-jump
b. if
c. if-else
d. if-call
4. and, or, and not are __________ operators.
a. relational
b. logical
c. conditional
d. ternary
5. The ___________ operator takes a Boolean expression as its operand and reverses
its
logical value.
a. and
b. or
c. not
d. either
6. A ___________ is a Boolean variable that signals when some condition exists in the
program.
70
a. flag
b. signal
c. sentinel
d. siren
7. You need to test a condition then execute one set of statements if the condition is
true.
8. If the condition is false, you need to execute a different set of statements. What
structure
will you use?
9. Briefly describe how the and operator works.
10. Briefly describe how the or operator works.
11.The following code contains several nested if-else statements. Unfortunately, it
was writ ten without proper alignment and indentation. Rewrite the code and use the
proper conventions of alignment and indentation.
if score >= A_score:
print('Your grade is A.')
else:
if score >= B_score:
print('Your grade is B.')
else:
if score >= C_score:
print('Your grade is C.')
else:
if score >= D_score:
print('Your grade is D.')
else:
print('Your grade is F.')
12. Write nested decision structures that perform the following: If amount1 is greater
than 10 and amount2 is less than 100, display the greater of amount1 and amount2.
13. The area of a rectangle is the rectangle’s length times its width. Write a program
that asks for the length and width of two rectangles. The program should tell the user
which rectangle has the greater area, or if the areas are the same.
71
14. On a roulette wheel, the pockets are numbered from 0 to 36. The colours of the
pockets are as follows:
• Pocket 0 is green.
• For pockets 1 through 10, the odd-numbered pockets are red and the even-numbered
pockets are black.
• For pockets 11 through 18, the odd-numbered pockets are black and the even-
numbered pockets are red.
• For pockets 19 through 28, the odd-numbered pockets are red and the even-
numbered pockets are black.
• For pockets 29 through 36, the odd-numbered pockets are black and the even-
numbered pockets are red.
Write a program that asks the user to enter a pocket number and displays whether the
pocket is green, red, or black. The program should display an error message if the user
enters a number that is outside the range of 0 through 36.
72
TOPIC 4
REPETITION STRUCTURES
Learning Outcomes:
After studying this topic you should be able to:
• Use the while loop to write a loop controlled program
• Write programs that use a count-controlled loop
• Write a program that calculates a Running Total
• Understand and use sentinels to terminate loops
• Validate input using loops
• Implement programs that use nested loops
4.1 Introduction
Repetition structures, also known as looping structures, allow you to repeat a set of
instructions multiple times. There are two main types of looping structures in Python:
for loops and while loops.
A for loop is used to iterate over a sequence (such as a list, tuple, or string) or other
iterable object, and execute a block of code for each item in the sequence. A while
loop is used to repeatedly execute a block of code as long as a given condition is true.
73
statement
etc.
Example:
count = 0
while count < 5:
print(count)
count += 1
Output
0
1
2
3
4
The following steps explain the code for the above program.
1. The variable count is initialized to 0.
2. The while loop starts with the condition count < 5. As long as this condition is
true, the loop will continue to execute.
3. The first iteration of the loop prints the value of count, which is 0.
4. After printing, the value of count is incremented by 1 using count += 1.
74
5. The condition count < 5 is evaluated again. Since it's still true (0 < 5), the loop
continues to execute.
6. The second iteration of the loop prints the value of count, which is now 1.
7. The value of count is incremented again by 1.
8. The condition count < 5 is evaluated again. Since it's still true (1 < 5), the loop
continues to execute.
9. This process repeats until the value of count becomes 5, at which point the
condition count < 5 is no longer true, and the loop terminates.
Something must happen inside the loop to change the condition keep_going == 'y'
to false in order for the loop to terminate. The last statement in this example takes care
of that. The loop will terminate if the user enters a value which is not ‘y’; in this case
the condition will evaluate to a false.
The above code will print the numbers 1 through 5 on separate lines.
Here is an explanation of this code:
76
4.4.1 Using the range Function with the for Loop
The syntax of the for loop using the range function is as follows:
for variable in range(start, end, step):
statement
statement
etc.
variable is a variable that takes on the value of the current iteration of the loop.
range is a built-in function that generates a sequence of numbers. The start argument
specifies the starting value of the sequence, the end argument specifies the stopping
value (which is not included in the sequence), and the step argument specifies the
difference between each number in the sequence. If step is not specified, it defaults to
1.
Example:
for num in range(1, 10, 2):
print (num)
Output
1
3
5
77
7
9
First argument, 1, is the starting value for the list
Second argument, 10, is the ending limit of the list
Third argument, 2, is the step value
If one argument is passed to the range function, as shown in the above program, that
argument is used as the ending limit of the sequence of numbers.
Output
0
1
2
3
4
If you provide the range function two arguments, the first argument serves as the
sequence's starting value and the second argument serves as its ending limit. For
example:
for num in range(1, 5):
print(num)
Output
1
2
3
4
78
for num in range(5):
print(‘Dings’)
Output
Dings
Dings
Dings
Dings
Dings
The following program uses a loop to display a table showing the numbers 1 through
10 and their squares.
Output
Number Square
---------------
1 1
2 4
3 9
4 16
5 25
6 36
7 49
8 64
79
9 81
10 100
Think Point: How would you modify the above program so as to let the use control
the loop iterations by asking the user to enter the start, end and step values?
Think Point: What are the disadvantages of duplicated code resulting from not using
loops?
4.5 Calculating a Running Total
80
One can calculate a running total using a for loop by initializing a variable to store the
total and updating it in each iteration of the loop. Typically, two components are used
in programs that determine the sum of a set of numbers:
A loop for reading each number in the sequence
A variable that tally's the numbers as they are read.
Output
25
• The variables num1, num2, num3, num4, and num5 store the numbers to be
summed.
• The running_total variable is initialized to 0 to store the total.
• The for loop iterates over the list of numbers [num1, num2, num3, num4, num5],
with the loop variable number taking on each value in turn.
• In each iteration, the loop adds the current number to the running_total
• Note that the running_total is updated in each iteration to accumulate the sum of
all the numbers in the list. The final value of running_total is 25, which is the sum
of all the numbers in the list.
Refer to page 189 of the prescribed textbook for a similar example for calculating a
running total.
81
4.6 The Augmented Assignment Operators
Augmented assignment operators are a shorthand notation in programming languages
for updating the value of a variable. They perform the operation and assignment of the
result to the variable in a single statement. For example, instead of writing "x = x + 1",
the augmented assignment operator "+=" can be used to write "x += 1"
4.7 Sentinels
A sentinel in Python is a special value used to indicate a specific condition, such as
the end of a data stream or the termination of a loop. Sentinels are often used as
markers to determine when a certain action should be performed, such as breaking
out of a loop or returning a specific value. In Python, the None object is a commonly
used sentinel value, indicating the absence of a value.
Example:
The county tax office calculates the annual taxes on property using the following
formula: property tax = property value X 0.0065
You learn that each property is assigned a lot number, and all lot numbers are 1 or
greater. You decide to write a loop that uses the number 0 as a sentinel value. During
each loop iteration, the program will ask the clerk to enter either a property’s lot
number, or 0 to end.
82
lot = int(input('Lot number: '))
Output
Program Output (with input shown in bold)
Enter the property lot number or enter 0 to end.
Lot number: 100
Enter the property value: 100000.00
Property tax: $650.00.
Enter the next lot number or
enter 0 to end.
Lot number: 200
Enter the property value: 5000.00
Property tax: $32.50.
Enter the next lot number or enter 0 to end.
Lot number: 0
83
Research: How can you use a loop for input validation? Use an example of a relevant
Python program to explain this concept
Example:
for i in range(1, 11):
for j in range(1, 11):
print(i * j, end='\t')
print()
Output
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
84
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
This code uses two nested for loops. The outer loop is controlled by the variable i and
iterates over the range (1, 11). The inner loop is controlled by the variable j and iterates
over the range (1, 11). For each iteration of the outer loop, the inner loop runs to
completion, resulting in the multiplication of i and j for each iteration, which is printed
on the same line separated by a tab. After each inner loop iteration, a newline character
is printed to move to the next line. The output of this code would be a table of the
multiplication of integers from 1 to 10.
outer loop: i = 1
inner loop: j = 1 i*j=1
inner loop: j = 2 i*j=2
...
inner loop: j = 10 i * j = 10
outer loop: i = 2
inner loop: j = 1 i*j=2
inner loop: j = 2 i*j=4
...
inner loop: j = 10 i * j = 20
...
outer loop: i = 10
inner loop: j = 1 i * j = 10
inner loop: j = 2 i * j = 20
...
inner loop: j = 10 i * j = 100
85
Review Questions
Multiple Choice
1. A __________ -controlled loop uses a true/false condition to control the number of
times that it repeats.
a. Boolean
b. condition
c. decision
d. count
2. A __________ -controlled loop repeats a specific number of times.
a. Boolean
b. condition
c. decision
d. count
3. The -= operator is an example of a(n) __________ operator.
a. relational
b. augmented assignment
c. complex assignment
d. reverse assignment
4. A(n) __________ variable keeps a running total.
a. sentinel
b. sum
c. total
d. accumulator
5. The input operation that appears just before a validation loop is known as the .
a. prevalidation read
b. primordial read
c. initialization read
d. priming read
6. Validation loops are also known as .
a. error traps
b. doomsday loops
c. error avoidance loops
d. defensive loops
86
7. True/False
To calculate the total number of iterations of a nested loop, add the number of iterations
of all the loops.
8. True/False
The process of input validation works as follows: when the user of a program enters
invalid data, the program should ask the user “Are you sure you meant to enter that?”
If the user answers “yes,” the program should accept the data.
9. What is an infinite loop? Write the code for an infinite loop.
10. Why is it critical that accumulator variables are properly initialized?
11. Why must the value chosen for use as a sentinel be carefully selected?
12. Write a while loop that asks the user to enter two numbers. The numbers should
be added and the sum displayed. The loop should ask the user if he or she wishes to
perform the operation again. If so, the loop should repeat, otherwise it should
terminate.
13. Write code that prompts the user to enter a number in the range of 1 through 100
and validates the input.
14. Write a program that uses nested loops to collect data and calculate the average
rainfall over a period of years. The program should first ask for the number of years.
The outer loop will iterate once for each year. The inner loop will iterate twelve times,
once for each month. Each iteration of the inner loop will ask the user for the inches of
rainfall for that month. After all iterations, the program should display the number of
months, the total inches of rainfall, and the average rainfall per month for the entire
period.
87
TOPIC 5
FUNCTIONS
Learning Outcomes:
After studying this topic you should be able to:
• Gain knowledge of writing and calling void functions
• Define and all a void function
• Design a program to use functions
• Declare and use local variables
• Pass arguments to functions
• Declare and use global variables and global constants
• Define and call value-returning functions
• Use the math module
• Store functions in modules
5.1 Introduction
A function in Python is a reusable block of code that performs a specific task. Functions
are defined using the "def" keyword, followed by the function name and a set of
parentheses. The input parameters (if any) are specified within these parentheses. The
code within the function is indented and executed when the function is called.
Functions can optionally return a value using the "return" statement.
88
Figure 5-1 Using functions to divide and conquer a large task
Source: Gaddis(2021) page 220
• Reusability: Functions can be reused across multiple parts of the program or even
in other programs, reducing the amount of code that needs to be written and making
it easier to test and debug.
89
• Better error handling: Functions can be designed to return error codes or throw
exceptions, making it easier to handle errors and exceptions within the program.
• Improved testing: Modularizing a program with functions allows for testing individual
components in isolation, making it easier to identify and fix bugs.
90
• The code inside the function is indented to indicate that it is part of the function.
The function is defined using the "def" keyword and ends with a colon (:). The
statements inside the function are executed when the function is called. To call the
function, simply write the function name followed by parentheses "()".
91
perform operations, print results, and change the state of its arguments, but it does not
return a value to be assigned to a variable or used as an expression.
Example of a void function:
def greet(name):
print("Hello, " + name)
greet("Dings")
Output
Hello, Dings
In this example, the greet function takes a parameter name and prints a greeting
message using it, but it does not return a value.
92
The definition of the main function appears in lines 3 through 6, and the definition of
the message function appears in lines 9 through 11. The statement in line 14 calls the
main function.
93
NOTE: When a program calls a function, the function takes control of the program’s
execution. This means that the control of the program simply transfers to that function.
94
For example, consider the following code:. The pass keyword is ignored by the Python
interpreter, so the following code creates four functions that do nothing.
def step1():
pass
def step2():
pass
def step3():
pass
def step4():
pass
Think Point: What is the importance of the pass keyword in program development?
def second_function():
local_variable = 20
print("Inside second_function:", local_variable)
first_function()
second_function()
print("Outside both functions:", local_variable) # This line
will raise an error
Output
Inside first_function: 10
95
Inside second_function: 20
Outside both functions: NameError: name 'local_variable' is not defined
As you can see, the local variable local_variable is defined inside both functions
first_function and second_function. However, each function has its own separate
instance of local_variable and changes to local_variable inside one function do not
affect the value of local_variable in the other function.
Local variables are declared inside a function and are only accessible within the
function in which they are declared. They are not accessible from outside the function,
even from other functions in the same program.
Output
10
• The code above defines a Python program with two functions: main and
show_double.
• The main function is the entry point of the program, and it defines a local variable
named value with the value 5.
• The main function then calls the show_double function and passes the value
variable as an argument.
The value variable and the number parameter reference the same value.
97
• The show_double function takes one argument, number, and multiplies it by 2 to
get the result.
• Finally, the main function is executed, which triggers the execution of the
show_double function.
5.5.1 Parameter Variable Scope
The function in which a parameter variable is used is referred to as the parameter's
scope. The parameter variable can be accessed from statements inside the function,
but not from statements outside the function.
def main():
calculate(3, 5)
main()
Output
8
Positional Arguments: These are the most common type of arguments, where the
values are passed to the function in the same order as they are defined. The values
are then assigned to the corresponding parameters in the function definition.
Example:
def greet(name, message):
print("Hello, " + name + ". " + message)
Output
98
Hello, John. How are you doing?
Keyword Arguments: These are the arguments that are passed using the parameter
name, followed by an equal sign and its corresponding value. This way, the order of
the arguments does not matter.
Example:
def greet(name, message):
print("Hello, " + name + ". " + message)
greet(message="How are you doing?", name="John")
Output
Hello, John. How are you doing?
Default Arguments: These are the arguments that have a default value in the function
definition. If these arguments are not passed when the function is called, their default
value is used.
Example:
def greet(name, message="Good morning!"):
print("Hello, " + name + ". " + message)
greet("John")
Output
Hello, John. Good morning!
99
Source: Gaddis (2021) Page 240
Think Point: What would be the effect of reversing the order of arguments passed to
a function when it is called?
100
When an argument is passed to a function in Python, the function parameter variable
will reference the argument’s value. However, any changes that are made to the
parameter variable will not affect the argument.
For example,
#This program demonstrates what happens when you
# change the value of a parameter.
def main():
value = 99
print(f'The value is {value}.')
change_me(value)
print(f'Back in main the value is {value}.')
def change_me(arg):
print('I am changing the value.')
arg = 0
print(f'Now the value is {arg}.')
Output
The value is 99.
I am changing the value.
Now the value is 0.
Back in main the value is 99.
In the code, you are passing the value 99 to the function change_me. The function
change_me receives the argument arg and assigns it a new value 0. However, this
change to the arg value does not affect the original value of value passed to the
101
function. Hence, when you print the value of value after calling the change_me
function, it still shows the original value of 99.
The form of argument passing that is used in Python, where a function cannot change
the value of an argument that was passed to it, is commonly called pass by value.
Example:
# This program demonstrates keyword arguments.
def main():
# Show the amount of simple interest, using 0.01 as
# interest rate per period, 10 as the number of periods,
# and $10,000 as the principal.
show_interest(rate=0.01, periods=10, principal=10000.0)
102
Output
The simple interest will be $1000.00.
In this case, the first argument principal is passed as a positional argument, followed
by rate and periods which are passed as keyword arguments.
Problem: Explain whether the following function call will cause an error for the above
program:
show_interest(1000.0, rate=0.01, 10)
103
def display_pi():
print(PI)
It is important to note that, even though global constants are named with all capital
letters, there is no actual enforcement in Python to prevent them from being modified.
It is just a convention used to indicate that their value should not be changed. To
enforce immutability, you can use the constant module or a similar library.
Here is another example that uses a global variable and a global constant:
# Global constant
PI = 3.14
def calc_circumference(radius):
# Accessing the global constant
circumference = 2 * PI * radius
return circumference
# Global variable
circumference = 0
print(circumference)
104
5.7 Introduction to Value-Returning Functions
A value-returning function in Python is a function that returns a value to the caller. The
return statement is used to return a value from the function.
def function_name():
statement
statement
etc.
return expression
105
# Call the main function.
main()
• This code will run without any errors and will provide the expected output.
• When the program is run, it will prompt the user to enter their age and their best
friend's age. The inputs will be stored as the variables first_age and second_age.
• Then, the program calls the sum function and passes first_age and second_age
as arguments. The sum function adds the two arguments together and returns the
result, which is stored in the variable total.
Finally, the program displays the message Together you are [total] years old., where
[total] is the sum of the ages of the user and their best friend.
Example:
def square(x):
return x * x
result = square(5)
106
print(result)
In this example, the square function takes a single argument x and returns the square
of that value. The return value of the function is assigned to the result variable, which
is then printed to the screen. The output of this program will be 25.
It is important to note that a function can only return one value. If you want to return
multiple values, you can use a tuple, a list, or another type of collection to store them.
result = sum_of_squares(3, 4)
print("The sum of squares is:", result)
107
Generating Random Numbers
# This program displays five random
# numbers in the range of 1 through 100.
import random
def main():
for count in range(5):
print(random.randint(1, 100))
• The program generates and displays five random numbers in the range of 1 to 100.
• It first imports the random module, which provides functions for generating pseudo-
random numbers. Then, the main function is defined, which contains a for loop that
runs five times and generates a random integer in the range of 1 to 100 using the
random.randint function. Finally, the main function is called to execute the
program.
• Each time you run the program, it will generate a different set of five random
numbers.
Example
def calculate_salary(basic_salary, allowances):
# Calculate gross salary
gross_salary = basic_salary + allowances
108
# Return both gross and net salaries
return gross_salary, net_salary
def main():
# Get the basic salary from the user
basic_salary = float(input("Enter your basic salary:
"))
• When the program is run, it will prompt the user to enter their basic salary and
allowances. The inputs will be stored as the variables basic_salary and
allowances.
• Then, the program calls the calculate_salary function and passes basic_salary
and allowances as arguments. The calculate_salary function calculates the gross
salary, tax amount, and net salary based on the inputs, and returns both the gross
salary and net salary.Finally, the program displays the gross salary and net salary.
109
# Get the user's name
name = input("Enter your name:")
# Return the name
return name
# Call the get_name function and capture the result
result = get_name()
• This code defines a function named get_name() that prompts the user to enter their
name and returns the name as the result.
• The function uses the input function to prompt the user to enter their name, which
is then stored in the name variable.
• Finally, the function uses the return statement to return the name variable as the
result of the function.
• The code then calls the get_name function and captures its result in the result
variable. The result is then displayed on the screen using the print function.
• When this code is run, the user will be prompted to enter their name, and the
entered name will be displayed on the screen.
def is_positive(number):
if number > 0:
return True
else:
return False
result = is_positive(10)
print(result) # outputs True
110
result = is_positive(-10)
print(result) # outputs False
• In this example, the function is_positive takes a single argument number and
returns True if the number is greater than zero, and False otherwise.
• The function is called twice and the result is captured in the result variable. The
value of the result variable is then displayed on the screen using the print function.
None is a special value in Python that represents the absence of a value. It is often
used as a placeholder when a function doesn't need to return a value. For example, a
function that just prints some text to the screen might return None to indicate that it
doesn't return any meaningful value.
Here is an example of a function that returns None:
def my_function():
print("Hello, World!")
result = my_function()
print(result)
Output
Hello, World!
None
The function my_function does not include a return statement, so it returns None by
default.
111
Here is another example that uses the return none statement.
def my_function(a, b):
print("The sum of", a, "and", b, "is", a + b)
return None
result = my_function(3, 4)
print(result)
Output
The sum of 3 and 4 is 7
None
The function my_function calculates the sum of its two arguments, prints the result,
and then returns None. The value of None is stored in the variable result, and it is
printed to the screen.
112
Table 5-1 Many of the functions in the math module
Source: Gaddis(2021) page 276
# Power function
result = math.pow(x, y)
# Factorial function
result = math.factorial(x)
113
The Python documentation has more information about the math module and this can
be access on the following link: https://docs.python.org/3/library/math.html
The following is an example of a program that calculates the square root of number:
import math
# Calculate the square root of a number
x = 100
result = math.sqrt(x)
print("The square root of", x, "is", result)
Output
The square root of 100 is 10.0
• In this example, we start by importing the math module. This gives us access to all
the mathematical functions and constants defined in the math module.
• Next, we define a variable x with the value 100. We then use the math.sqrt(x)
function to calculate the square root of x.
• The math.sqrt(x) function returns the square root of the argument x as a floating-
point number. In this case, the square root of 100 is 10.0.
Finally, we print the result using the print function, along with a message indicating
what the result represents.
114
Review Questions
1. What is a function?
2. What is meant by the phrase “divide and conquer”?
3. How do functions help you reuse code in a program?
4. A variable that is visible to every function in a program file is a __________.
a. local variable
b. universal variable
c. program-wide variable
d. global variable
5. This standard library function returns a random floating-point number in the range of
0.0 up to 1.0 (but not including 1.0).
a. random
b. randint
c. random_integer
d. uniform
6. This statement causes a function to end and sends a value back to the part of the
program that called the function.
a. end
b. send
c. exit
d. return
7. This is a math module function.
a. derivative
b. factor
c. sqrt
d. differentiate
8. Why do global variables make a program difficult to debug?
9. Suppose you want to select a random number from the following sequence:
0, 5, 10, 15, 20, 25, 30. What library function would you use?
8. What statement do you have to have in a value-returning function?
9. Look at the following function header:
def my_function(a, b, c):
Now look at the following call to my_function:
115
my_function(3, 2, 1)
When this call executes, what value will be assigned to a? What value will be assigned
to b? What value will be assigned to c?
10. The following statement calls a function named half, which returns a value that is
half that of the argument. (Assume the number variable references a float value.)
Write code for the function.
result = half(number)
11. Write a function named times_ten that accepts a number as an argument. When
the function is called, it should return the value of its argument multiplied times 10.
12. A county collects property taxes on the assessment value of property, which is 60
percent of the property’s actual value. For example, if an acre of land is valued at
$10,000, its assessment value is $6,000. The property tax is then 72¢ for each $100
of the assessment value. The tax for the acre assessed at $6,000 will be $43.20. Write
a program that asks for the actual value of a piece of property and displays the
assessment value and property tax.
13. Write a program that generates a random number in the range of 1 through 100,
and asks the user to guess what the number is. If the user’s guess is higher than the
random number, the program should display “Too high, try again.” If the user’s guess
is lower than the random number, the program should display “Too low, try again.” If
the user guesses the number, the application should congratulate the user and
generate a new random number so the game can start over.
116
TOPIC 6
FILES
Learning Outcomes:
After studying this topic you should be able to:
• Create files
• Read from files
• Write to files using Python
• Append text to a file
• Use loops to process files
6.1 Introduction
In Python, you can work with files to read from and write to them. This topic
introduces sequential file input and output. The learner will gain knowledge of how to
read, write, and save vast amounts of data in fields and records.
Terms
Saving data in a file = “writing data to” the file
Output file = file that data is written to
Retrieving data from a file = “reading data from” the file
Input file = file that data is read from
117
Sequential Access: This method involves reading the data in a file in a linear,
sequential manner, starting from the beginning and working towards the end.
Sequential access is often used when reading large files, such as text files, where the
contents of the file need to be processed in order. For example, when reading a large
text file, a program may read the first line, process the data, then read the next line,
and so on. This is similar to the way older cassette tape players work. If you want to
listen to the last song on a cassette tape, you have to either fast-forward over all of the
songs that come before it or listen to them. There is no way to jump directly to a specific
song.
Direct Access: This method involves accessing a specific part of a file without reading
the entire file from start to finish. Direct access is often used when working with binary
files, such as images or audio files, where specific data needs to be retrieved quickly
and efficiently. For example, when reading an image file, a program may seek directly
to the part of the file where the image data is stored and read that data, without having
to read the entire file. When you work with a direct access file (which is also known as
a random access file), you can jump directly to any piece of data in the file without
reading the data that comes before it. This is similar to the way a CD player or an MP3
player works. You can jump directly to any song that you want to listen to.
In general, sequential access is used when reading text files or other data that needs
to be processed in order, while direct access is used when working with binary files or
other data that needs to be retrieved quickly and efficiently. The choice of file access
method depends on the specific requirements of the task at hand, and the nature of
the data being processed.
118
file_variable is the name of the variable that will reference the file object
filename is a string specifying the name of the file
mode is a string specifying the mode (reading, writing, etc.)
119
File_variable.write(string)
File_variable is a variable that references a file object.
Write refers to the operation of the file object used to write data.
String refers to the string that will be written to the file.
Explain how the read operation works assuming that the file to be read has the
following contents:
File contents:
Line 1: This is line 1.
Line 2: This is line 2.
Line 3: This is line 3.
120
It is recommended to use the with statement when working with files in Python, as it
automatically closes the file for you, even if an exception is raised:
with open("example.txt", "r") as file:
contents = file.read()
print(contents)
Examples
He is an example of a Python program that creates a new file, writes some text to it,
reads the contents of the file, and then closes the file:
# Open the file in write mode
file = open("example.txt", "w")
When you run this program, it will create a new file named example.txt in the current
directory, write the specified text to the file, read the contents of the file, and then print
121
the contents to the console. The program then closes the file, releasing any resources
it was using.
Note that the write method writes the text to the file, while the read method reads the
contents of the file into a string. The close method closes the file and frees up any
resources it was using. It's important to close the file when you're done working with it
to ensure that any changes you made to the file are saved and that the file is not locked
by the program, preventing other programs from accessing it.
The following example uses the readline method instead of the read method.
# Open the file in write mode
file = open("example.txt", "w")
122
In reality, a programmer doesn’t know how many lines of texts a file contains but still
want to read the file line by line. This can be achieved using the a loop; here is an
example:
# Open the file in write mode
file = open("example.txt", "w")
Note that the readline method reads a single line of the file at a time, and returns an
empty string when it reaches the end of the file. The while loop continues to read and
123
print lines from the file until the readline method returns an empty string, indicating that
the end of the file has been reached.
Output
This is line 1.
This is line 2.
This is line 3.
Each line of the file is printed on its own line, including the line break at the end of each
line in the file. The line break is represented by the newline character ‘\n’, which is
automatically added to the end of each line when you write to the file, and is also
preserved when you read the contents of the file using the readline method.
Output
This is a string
Output
This is a string
124
So, the original string "This is a string\n" has had the newline character \n stripped
from the end of it using the strip method, and the result is a string without a line break.
So, the original string "This is a string\n" has had the newline character ‘\n’ stripped
from the end of it using the strip method, and the result is a string without a line break.
You can also strip specific characters from the end of a string using the rstrip method.
Output
This is a string
The rstrip method has stripped the newline character ‘\n’ from the end of the string,
resulting in a string without a line break.
125
line3 = line3.rstrip('\n')
Output
John Locke
David Hume
Edmund Burke
• This program reads the contents of a file named philosophers.txt one line at a
time. The program starts by opening the file in read mode using infile =
open('philosophers.txt', 'r').
• Then, it uses the readline method to read three lines from the file, and assigns
each line to a separate variable (line1, line2, and line3).
• Next, the program strips the newline characters (‘\n’) from each of the strings using
the rstrip method, so that the contents of the file can be processed more easily.
• Finally, the program closes the file using infile.close(), and prints the contents of
the three lines that were read from the file.
• The program uses the if __name__ == '__main__' idiom to ensure that the main
function is only called when the program is executed as a standalone script, and
not when the module is imported as a library.
126
6.7 Appending Data to an Existing File
To open an output file in append mode, use the 'a' mode. If the file already exists, it
will not be erased. If the file does not exist, it will be created; when data is written to
the file, it is appended to the end of the contents that are already there.
Example:
# Open the file in append mode
with open('file.txt', 'a') as f:
# Write new data to the end of the file
f.write('This is a new line of text.\n')
In this example, the file 'file.txt' is opened in append mode using the with statement
and the 'a' mode flag. The contents of the file are then appended with a new line of
text using the write method. Finally, the file is read and its contents are printed to verify
that the new data was written to the file correctly.
Note that when you use the write method to write data to a file, you need to include the
line break character \n at the end of each line if you want to preserve the line breaks
in the file.
outfile.write(str(num1) + ‘\n’)
infile = open(‘number.txt’, ‘r’)
# readline method reads strings
string_input = infile.readline()
128
print('The sum of the numbers is:', sum)
• This code will open the file numbers.txt in read mode and read the first, second,
and third lines from the file. It will then strip the newline characters from each line using
the rstrip method and convert each line to a numeric value using the float function.
• Finally, the code adds the numbers together and prints the sum of the numbers.
Note that this code assumes that each line in the file contains a valid floating-point
number, and will raise an error if this is not the case. You should add error handling
code to handle cases where the contents of the file are not as expected.
6.9 Reading a File with a Loop and Detecting the End of the File
It allows reading a file's contents without being aware of how many items are contained
therein. When the readline method tries to read beyond the file's end, it produces an
empty string (' '). If utilizing a while loop, priming read is required to test the loop
condition.
Example:
# Open the file for reading
with open('numbers.txt', 'r') as file:
# Initialize a variable to keep track of the sum
sum = 0
• This code will open the file numbers.txt in read mode and loop over each line in the
file. For each line, it will strip the newline character from the line, convert the line to
a numeric value using the float function, and add the number to a running total sum.
• Finally, the code will print the sum of the numbers. Note that this code assumes
that each line in the file contains a valid floating-point number, and will raise an
error if this is not the case. You should add error handling code to handle cases
where the contents of the file are not as expected.
132
References
Gaddis, T. (2021). Starting out with Python. 5th Global Ed. United Kingdom: Pearson
Education. ISBN: 9781292408637
133