Programming 511 Study Guide (Python)
Programming 511 Study Guide (Python)
STUDY GUIDE
Copyright © 2024
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
LIBRARY INFRASTRUCTURE........................................................................................... 4
ASSESSMENT ...................................................................................................................... 4
TOPIC 1 ............................................................................................................................... 10
1.2 Hardware and Software Hardware ................................. Error! Bookmark not defined.
1.3 How Computers Store Data ............................................ Error! Bookmark not defined.
i
TOPIC 2 ............................................................................................................................... 29
2.3 Input, Processing, and Output ........................................ Error! Bookmark not defined.
2.4 Displaying Output with the print Statement ................... Error! Bookmark not defined.
TOPIC 3 ............................................................................................................................... 54
ii
3.6 Logical Operators ........................................................................................................... 64
TOPIC 4 ............................................................................................................................... 72
TOPIC 5 ............................................................................................................................... 86
FUNCTIONS........................................................................................................................ 86
iii
5.6 Global Variables and Global Constants ........................................................................ 100
6.9 Reading a File with a Loop and Detecting the End of the File .................................... 124
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
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,
1
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 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.
2
LECTURES AND TUTORIALS
Students must refer to the notice boards on their respective campuses for details of the lecture
and tutorial timetables. The lecturer assigned to the module will also inform you of the number
of lecture periods and tutorials allocated to a particular module. Prior preparation is required
for each lecture and tutorial. Students are encouraged to actively participate in lectures and
tutorials to ensure success in tests, group discussions, practicals, assignments and
examinations.
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
[Link]. (2019). The Python Tutorial — Python 3.8.0 documentation. [online] Available
at: [Link]
[Link]. (2019). Learn Python - Free Interactive Python Tutorial. [online] Available
at: [Link]
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.
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.
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
4
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%
5
Table 2: Bloom's Taxonomy
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
• Predict consequences
Questions Cues
apply, demonstrate, calculate, complete, illustrate, show, solve, examine, modify,
relate, change, classify, experiment, discover
6
• Seeing patterns
• Organisation of parts
• Recognition of hidden meanings
• Identification of components
Question Cues
analyse, separate, order, arrange, divide, compare, select, infer, connect, classify,
explain
Question Cues
combine, integrate, modify, rearrange, substitute, plan, create, design, invent,
what if? compose, formulate, prepare, generalise, rewrite
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)
7
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.
Readiness
finance
•Employer/Employee
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 the fundamental workings of computers.
• Comprehend how data is stored and manipulated in computer systems.
• Recognize the advantages of using high-level programming languages.
• Write basic programs using Python's syntax and structure.
1.1 Introduction
The first section of this topic provides an insight into the functioning of computers, data
storage and manipulation, and the rationale behind using high-level languages for
programming. Key concepts such as Python programming, interactive and script modes, and
the IDLE (Integrated Development and Learning Environment) are introduced.
Computers are integral to our daily lives, found in various forms such as desktops, laptops,
smartphones, and embedded systems in appliances and vehicles. Their versatility stems from
the ability to be programmed to perform a myriad of tasks. At the core, a computer is a
machine that processes data and executes instructions.
• Data Representation: Computers use binary (0s and 1s) to represent data. This binary
system is the basis of data storage and manipulation in computer systems.
10
High-Level Programming Languages
• Why High-Level Languages?: These languages, such as Python, are closer to human
language, making them easier to learn and use. They abstract the complexities of binary
code and hardware specifics, enabling programmers to focus on solving problems.
Introduction to Python
• Interactive Mode: Allows you to type Python commands and get immediate
feedback. Ideal for learning and experimenting.
• Script Mode: Involves writing Python code in a file and then running it as a
program. Used for developing complete applications.
Practical Application
• Writing Basic Programs: Start with simple tasks like printing text, performing
arithmetic operations, and gradually progress to more complex programming constructs
like loops, functions, and data structures in Python.
11
Figure 1-1 A word processing program and a presentation program (Gaddis, 2021)
1.2 Hardware and Software
1.2.1 Understanding Computer Hardware
Introduction to Computer Systems
A computer is a sophisticated device composed of various hardware components, each
performing specific functions to facilitate the execution of tasks. Understanding these
components is crucial for grasping how computers operate and how they execute
programming instructions, such as those written in Python.
12
Key Components of a Computer System
13
Figure 1-4 A lab technician holds a modern microprocessor
14
Think point: Can you think of any other input devices?
Output Devices
Output devices are essential components in computing, as they allow us to visualize and
interact with the data processed by computers. These devices are crucial not only for general
computer use but also in Python programming, where outputs are often displayed or printed
for debugging, data analysis, or user interaction.
Common Output Devices:
• Monitor: Displays visual output from a computer. Python programs often use GUI
libraries like Tkinter or PyQt to create applications whose results are displayed on
monitors.
• Printer: Converts digital data into a physical format. Python can be used to format and
send documents or reports to a printer.
1.2 Software
Software is the non-tangible component of computing. It's categorized into system software
and application software, both of which are crucial in Python programming.
System Software:
• Operating System: Manages hardware and is essential for running Python interpreters
or integrated development environments (IDEs) like PyCharm or Visual Studio Code.
• Utility Programs: These include software like antivirus programs and system
management tools, which can be automated or enhanced using Python scripts.
• Software Development Tools: Python itself falls under this category as it's used to
create, modify, and test software applications.
Application Software:
This is software used for performing specific tasks. Python is often used to develop various
kinds of application software, like web applications (using frameworks like Django or Flask),
data analysis tools (using libraries like Pandas and NumPy), and automation scripts.
Checkpoint: Think of other application software you use daily. How might Python play a
role in these tools?
15
1.3 How Computers Store Data
Understanding data storage is crucial for Python programmers, especially when dealing with
data types and memory management.
• Bytes and Bits: In Python, understanding bytes is important when dealing with binary
data, file I/O, and network communications. Python has a bytes type for handling binary
data.
• Positive and Negative Charges: The binary system (0s and 1s) in computing correlates
to the positive and negative charges in bits. In Python, boolean values (True and False)
are often used to represent these binary states.
Enhancing Python Learning:
Understanding these fundamentals is crucial for Python programmers, especially when
dealing with file handling, data processing, and creating software applications. Recognizing
the role of hardware and system software in running Python applications helps in optimizing
performance and developing more efficient programs.
16
1.3. Storing Numbers in Python
1. Introduction to Binary System
• Binary Basics:
• In digital electronics and computing, information is represented using two states:
'on' and 'off'.
• These states correspond to two digits in the binary system: 1 (on) and 0 (off).
• This system, known as binary, forms the basis of all modern computing systems.
2. Binary Numbering System
• Structure:
• A binary number is composed exclusively of 0s and 1s. Each digit in this system
is called a "bit".
• The position of each bit in a binary number determines its value, increasing
exponentially from right to left, starting at 0.
• For example, in the binary number 1011, the rightmost bit (1) represents 2^0, the
next bit (1) represents 2^1, and so on.
3. Decimal to Binary Conversion
• Understanding Conversion:
• In Python, you can convert decimal numbers (base-10) to binary (base-2) using
the bin() function.
• Example: bin(10) will return '0b1010', where '0b' is a prefix indicating a binary
number.
4. Binary Arithmetic in Python
• Operations:
• Python allows binary arithmetic, such as addition (+), subtraction (-),
multiplication (*), and division (/).
• Bitwise operations like AND (&), OR (|), XOR (^), NOT (~), left shift (<<), and
right shift (>>) are also performed on binary numbers.
5. Practical Applications
• Binary in Python Programming:
• Understanding binary is crucial for tasks like data encoding, file I/O operations,
network communications, and system design in Python.
• Python's ability to easily handle binary data makes it a powerful tool for
developing applications that interact with low-level system components
17
Figure 1-6 The values of binary digits as powers of 2
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
18
Figure 1-8 Two bytes used for a large number
19
Your computer stores the number 65 when you input an uppercase A using the keyboard. This
65 is stored as a binary number.
21
• Common examples of high-level programming languages include Python, C++, Ruby,
Ada, BASIC, and Visual Basic. Each of these languages has its unique features and areas
of application, but they all share the trait of being more abstracted from machine-level
instructions.
High-Level vs. Low-Level
• In comparison to assembly language, which requires detailed knowledge of the CPU and
is closer to machine language, high-level languages simplify many tasks. A complex task
in assembly might require several intricate instructions, while in a high-level language,
the same task could be achieved with fewer and simpler commands.
Key Words, Operators, and Syntax: An Overview
Key Words
• Reserved Words: These are predefined words in a programming language that have
special meanings. They are the building blocks of the language's syntax and are used to
perform various programming functions.
Operators
• Functionality: Operators in high-level languages are used to perform operations on data.
These include arithmetic operations, logical operations, comparison operations, and
more.
Syntax
• Rules: The syntax of a language is a set of rules and guidelines that dictate how the code
must be written and structured. Correct syntax is essential for the program to be
understood and executed by the computer.
Statements
• Instructions: A statement in a programming language is an individual instruction that
performs a specific operation. A program is essentially a collection of these statements
that collectively perform a complex task.
1.4.3 Compilers and Interpreters
Source Code
• The code written in a high-level language is known as source code. It's the human-
readable set of instructions that needs to be converted into machine language for the
computer to execute.
22
Compilers and Interpreters
• Compiler: A compiler is a program that translates the entire source code into a machine
language program (executable file) in one go. This process is done before the program is
run.
• Interpreter: An interpreter, on the other hand, translates the source code into machine
language on the fly, executing it line by line. This means the code is being translated and
run simultaneously.
Syntax Errors
• Errors such as misspellings, incorrect punctuation, or improper use of operators are called
syntax errors. These errors prevent the code from being correctly translated into machine
language, leading to program failures or unexpected behavior.
An interpreter is a program that both translates and executes the instructions in a high-level
language program.
25
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
[Link] words that make up a high-level programming language are called __________. a.
binary instructions
b. mnemonics
26
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
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.
27
• Exit the Python interpreter. (In Windows, press Ctrl-Z followed by Enter. On other systems,
press Ctrl-D.)
28
TOPIC 2
PYTHON FUNDAMENTALS
Learning Outcomes
After studying this topic you should be able to:
• Design a program
• Utilize the print function for output display.
• Incorporate comments and manipulate variables.
• Read input from the keyboard.
• Execute calculations and perform string concatenation.
• Produce formatted output using F-strings.
• Implement named constants for improved code clarity.
2.1 Introduction
This topic delves into the essentials of program development, emphasizing variables, data types,
and sequence structures. You'll learn to craft programs that interact with users, perform
calculations, and output results in a structured format. Tools such as pseudocode and flowcharts
are introduced to aid in program design.
2.2 Designing a Program
The Program Development Cycle (PDC)
Effective programming starts with a well-thought-out design. The PDC guides programmers
through essential stages to ensure their programs are both functional and efficient.
Five Phases of the PDC:
Design the Program: Planning the program's structure and functionality.
Write the Code: Translating the plan into executable code.
Correct Syntax Errors: Refining the code by fixing syntax-related issues.
Test the Program: Verifying the program works as intended.
Correct Logic Errors: Resolving errors in the program's logic.
29
Refer to Figure 2-1 on page 31 of the recommended textbook for a visual representation of
the PDC.
Steps in Program Design:
1. Understand the Task: This involves comprehending the program's purpose, often
derived from client requirements.
Pseudocode
Example of Pseudocode:
Flowcharts
Flowcharts offer a visual representation of a program's logic, making them invaluable for
understanding and conveying complex processes.
Flowcharts simplify logic, highlight potential errors, and enhance the structure and clarity of
code. They are essential for ensuring that code is organized, comprehensible, and
maintainable.
Figure 2-3 The input, processing, and output of the pay calculating program
32
Output:
South Africa
Zimbabwe
Zambia
Botswana
Malawi
2.4.1 Strings and String Literals
• String Literals: Strings in Python are sequences of characters used as data.
When a string appears directly in code, it's called a string literal.
• Usage: Strings can be enclosed in single, double, or triple quotes.
• Single and Double Quotes: Use double quotes if the string contains a single
quote (apostrophe) and vice versa.
Examples:
print("Don't hate your neighbour!")
print('Your assignment is to read "Hamlet" by tomorrow.')
Output:
Don't hate your neighbour!
Your assignment is to read "Hamlet" by tomorrow.
• Triple Quotes: Used for multi-line strings, preserving formatting and
whitespace.
Example with Triple Quotes:
string_1 = '''Hello,
World!'''
print(string_1)
Output:
Hello,
World!
33
2.5 Comments
• Purpose: Comments are non-executable statements used to explain and
annotate code.
• Types:
• Single-line Comments: Start with # and extend to the end of the line.
• Multi-line Comments: Enclosed in triple quotes (''' or """).
Examples:
# This is a single-line comment """ This is a
multi-line comment """
2.6 Variables
• Definition: Variables in Python are named locations in memory for storing
data values.
• Assignment: Use the assignment operator = to assign values to variables.
Examples:
x = 42
y = "Hello, World!"
z = [1, 2, 3]
• Type Inference: Python automatically determines the type of a variable
based on the assigned value.
Variable Naming Best Practices:
• Naming Rules:
• Must begin with a letter or underscore (_).
• Can include letters, digits, or underscores after the first character.
• Should not be a reserved word in Python.
• Case-sensitive.
• Cannot contain spaces.
• Readability: Use lowercase with underscores for readability (e.g.,
age_of_student).
2.6.1 Variable Naming Rules
When naming variables in Python, follow these guidelines for clarity and to
adhere to Python's syntax rules.
34
Example:
age = 25
35
• 2ndAttempt (starts with a digit)
• user-name (contains a hyphen)
• global (reserved word)
• full name (contains a space)
Note:
While Python allows the use of both lowercase with underscores and CamelCase, it's crucial
to maintain consistency within your project. Adhering to one style throughout a project aids
in readability and understanding of the code by other developers.
37
2. Reassignment of Variable:
You can change the value of a variable at any point in your program. This is known as
reassignment. For example:
dollars = 99.95 # Line 8: Variable 'dollars' is given a new value 99.95
After this reassignment, the variable dollars now refers to the new value 99.95.
Memory Management and Garbage Collection
• Previous Value in Memory:
When a variable is reassigned, the old value (2.75 in our example) remains in the computer's
memory temporarily. However, since it's no longer referenced by the dollars variable, it
becomes inaccessible through your program.
• Garbage Collection:
Python uses a mechanism called "garbage collection" to reclaim memory occupied by
unreferenced values. This process automatically and periodically looks for objects in
memory that are no longer in use (i.e., not referenced by any variable) and frees up the
memory they occupy.
• Automatic Memory Management: This aspect of Python's design simplifies
memory management for developers. Unlike languages where memory
management is manual, Python automates this process, reducing the risk of
memory leaks.
• Efficiency and Optimization: While the Python garbage collector is efficient,
it is still advisable for programmers to manage resources wisely, especially in
large-scale applications where resource management is crucial for performance.
38
Types of Numeric Literals:
1. Integer (int):
• An integer is a numeric literal without a decimal point.
• It can be positive, negative, or zero.
• Examples: 7124, 503, -9.
2. Floating-Point Number (float):
• A float is a numeric literal with a decimal point.
• It represents real numbers and can include fractions.
• Examples: 1.5, 3.1415, 5.0.
Determining Data Types with type() Function:
• Python provides a built-in function type() to determine the data type of a value.
• The output of the type() function is in the format <class 'type'>, indicating the data type
of the provided argument.
Examples:
print(type(1)) # Output: <class 'int'> print(type(1.0)) # Output: <class 'float'>
• In these examples, 1 is identified as an integer (int), and 1.0 as a floating-point number
(float).
39
Reassigning a Variable to a Different Type
Dynamic Typing in Python:
• In Python, variables are dynamically typed. This means that a variable's data type is not
explicitly declared and can change during the execution of a program.
Example and Explanation:
Consider the following example:
string1 = 'Hello World'
print(type(string1)) # Output: <class 'str'>
string1 = 123
print(type(string1)) # Output: <class 'int'>
In this example, string1 is first assigned to a string 'Hello World'. Its type is <class 'str'>. Later,
string1 is reassigned to an integer 123, changing its type to <class 'int'>.
Caution in Dynamic Typing:
• While dynamic typing offers flexibility, it requires careful management to avoid errors.
• Mismanagement can lead to unexpected behavior or runtime errors, especially in complex
programs.
Think Point:
Consider the following assignments:
value1 = 99
value2 = 45.9
value3 = 7.0
value4 = 7
value5 = 'abc'
After execution, the Python data types are:
value1: <class 'int'>
value2: <class 'float'>
value3: <class 'float'>
value4: <class 'int'>
value5: <class 'str'>
40
2.6.4 Reading Input from the Keyboard
Using the input() Function:
The input() function in Python reads a line of text from the user and stores it as a string.
Example:
Reading and using user input:
name = input('What is your name? ')
print('Hello, ' + name)
This code will prompt the user with "What is your name?" and store the user's response in the
name variable.
Handling Numeric Input:
The value returned by input() is always a string. To use it as a number, you must explicitly convert
it.
Example with Numeric Conversion:
Converting user input to an integer:
age = input('What is your age? ')
age = int(age)
print('You are ' + str(age) + ' years old.')
Here, the user's age is initially read as a string, then converted to an integer using int(age). The
print() function outputs the age, converting it back to a string with str(age).Here, the user's age
is initially read as a string, then converted to an integer using int(age). The print() function
outputs the age, converting it back to a string with str(age)
Output
Program Output (with input shown in bold)
41
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
Example a =
5b=
3
addition = a + b subtraction = a - b
multiplication = a * b division = a / b
floor_division = a // b modulus = a %
b exponentiation = a ** b
42
print("Modulus: ", modulus) # Output: Modulus: 2 print("Exponentiation: ",
exponentiation) # Output: Exponentiation: 125
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
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.
43
Example Expressions
% is the remainder operator. Its purpose is to perform division and return the remainder.
For Example: leftover = 17 % 3 #remainder is 2
44
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)
var1 = 1 var2 = 2
var3 = 3 var4 = 4
result = var1 * 2 + var2 * 3 + \ var3 * 4 +
var4 * 5
print(result)
45
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 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.
46
More arguments for the print Function
In Python, you can use multiple print statements to print on the same line by using the end
parameter of the print function. By default, end is set to '\n', which means a new line will be
added after each print statement. You can change the value of end to “ “ (an empty string) to
prevent the addition of a new line.
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
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
47
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.
For example:
my_value = 7.23456
print (“The value is %.2f“ % my_value)
Output
The value is 7.23
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.
48
Another example:
Output
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.
49
print (‘Hello %s. Good to see you!’ % name) print (‘The sales on %s
were $%.2f.’ % (day, sales))
Output
Hello Ringo. Good to see you!
The sales on Monday were $8450.55.
GRAVITY = 9.8
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.
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?
50
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
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
52
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
• 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, ifelse, 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
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".
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)
55
< (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
Here is an example: # Three test
scores test_score1 = 80
test_score2 = 90
test_score3 = 95
# Use an if statement to check the value of the average if average > 90:
# Display a message if the condition is True print("Congratulations! Your
average score is above 90.")
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.
Here is another example that conditionally executes a block containing three statements:
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"
# Compare the two strings using the equality operator if string1 == string2:
print("The strings are equal.") else:
print("The strings are not equal.")
Output
The strings are not equal.
To perform a case-insensitive comparison, you can convert the strings to either upper- or
lower-case using the upper() or lower() methods and then compare them.
# Compare the two strings using the greater than operator if string1 > string2:
print("string1 is greater than string2.")
else:
print("string1 is not greater than string2.")
Output
60
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
# Get the number of years on the current job. years_on_job = int(input('Enter the
number of years employed: '))
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 condition_1:
statement statement
etc. elif condition_2:
statement statement
etc. 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:
63
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
3.6.1 The and Operator
Example: x =
5y=
10
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:
65
3.6.2 The or Operator
Example: x = 5 y = 10 if x < 10
or y < 5:
print("At least one condition is True")
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.
Here is another example for a program that prints a message if temperature is not greater than
100 degrees.
66
if not(temperature > 100):
print (‘This is below the maximum temperature.’)
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")
67
Here is an example: a
= True b =
False
print(a) # Output: True print(b) # Output:
False Boolean variables are often used in
control structures, such as if statements, to
determine the flow of the program based on
whether a certain condition is true or false:
flag = True if flag:
print("Flag is set to True") else:
print("Flag is set to False")
68
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.
a. flag
69
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.
[Link] 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.
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.
70
• 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.
71
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.
72
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.
73
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.
74
4.4 The for Loop
The for loop in Python is a count-controlled loop, which means that it executes a block of
code a certain number of times. The for loop uses a counter to keep track of how many times
the loop has been executed and terminates when the counter reaches a specified value. for
variable in [value1, value2, etc.]: statement statement etc.
for num in [1, 2, 3, 4,5]: print (num)
Output
1
2
3
4
5
The above code will print the numbers 1 through 5 on separate lines.
Here is an explanation of this code:
75
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
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
76
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
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.
77
# Print the numbers 1 through 10 # and their
squares.
for number in range(1, 11): square =
number**2
print(f'{number}\t{square}')
Output
Number Square
---------------
1 1
2 4
3 9
4 16
5 25
6 36
7 49
8 64
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?
4.4.2 Generating Lists that Range from Highest to Lowest for num
in range(5, 0, -1): print (num)
78
Output
5
4
3
2
1
• The range function generates a sequence of numbers from 5 to 1 (range(5, 0, -1)), counting
down by 1 with each step (the third argument -1).
• The for loop iterates over this sequence, with the loop variable num taking on each value
in turn.
• In each iteration, the loop uses the print function to print the value of num on a new line.
Think Point: What are the disadvantages of duplicated code resulting from not using loops?
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.
Here is an example that calculates the running total of a list of numbers: num1
= 5 num2 = 3 num3 = 7 num4 = 2 num5 = 8 running_total = 0
for number in [num1, num2, num3, num4, num5]:
running_total += number
print(f'The total is {total}.')
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
79
• 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.
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
80
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.
Output
Program Output (with input shown in bold)
Enter the property lot number or enter 0 to end.
Lot number: 100
81
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
Research: How can you use a loop for input validation? Use an example of a relevant Python
program to explain this concept
The outer_loop_variable and inner_loop_variable can be any variable name of your choice.
For each iteration of the outer loop, the inner loop goes through all of its iterations. Inner
loops complete iterations before outer loops.
82
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
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
...
83
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
Problem: Write a program that displays a rectangular pattern of asterisks and a triangle of
asterisks using nested loops.
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
84
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
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.
85
TOPIC 5
FUNCTIONS
Learning Outcomes:
After studying this topic you should be able to:
• Gain knowledge of writing and calling void functions
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.
86
Figure 5-1 Using functions to divide and conquer a large task
Source: Gaddis(2021) page 220
• Improved readability and maintainability: Functions allow for breaking down a complex
program into smaller, manageable chunks, making the code easier to read, understand, and
maintain.
• 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.
• Improved testing: Modularizing a program with functions allows for testing individual
components in isolation, making it easier to identify and fix bugs.
88
inside the function are executed when the function is called. To call the function, simply
write the function name followed by parentheses "()".
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.
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.
90
91
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.
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.
92
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?
first_function() second_function()
print("Outside both functions:", local_variable) # This line will raise an error
Output
Inside first_function: 10
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.
93
Also, when we try to access local_variable outside of both functions, a NameError is raised,
as the variable is not defined in the global scope. The scope of variable refers to the region of
the code where the variable is defined and can be accessed. In other words, it's the area of the
code where the variable has visibility and can be used.
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.
94
• 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.
• 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.
95
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.
Output
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")
96
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!
97
Figure 5-4 Two arguments passed to two parameters
Source: Gaddis(2021) page 241
Think Point: What would be the effect of reversing the order of arguments passed to a function
when it is called?
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}.')
98
# Call the main function.
main()
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 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)
99
def show_interest(principal, rate, periods):
interest = principal * rate * periods
print(f'The simple interest will be ${interest:,.2f}.')
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)
100
5.6.2 Global constants
Global constants, on the other hand, are global variables that have a fixed value and cannot
be changed once set. The naming convention for global constants is to use all capital letters
with underscores between words. For example:
PI = 3.14
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
print(circumference)
101
• A program is difficult to understand when it uses global variables.
# The sum function accepts two numeric arguments and # returns the
sum of those arguments.
def sum(num1, num2): result =
num1 + num2 return result
102
Output (with input shown in bold)
Enter your age: 22
Enter your best friend's age: 24 Together you
are 46 years old.
• 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)
print(result)
103
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.
104
# Call the main function. main()
• 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
pseudorandom 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
[Link] 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.
105
calculate_salary(basic_salary, allowances)
• 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
[Link], the program displays the gross salary and net salary.
• 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.
106
• 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
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.
107
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.
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.
108
4. Constants: [Link], math.e, [Link]
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 = [Link](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 [Link](x) function to
calculate the square root of x.
• The [Link](x) function returns the square root of the argument x as a floatingpoint
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.
110
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?
111
9. Look at the following function header: def my_function(a, b, c):
Now look at the following call to my_function:
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.
112
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
113
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.
114
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.)
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.
115
6.4 Reading Data From a File
Reading a file: To read the contents of a file, you can use the read method of the file object.
Here's an example that reads the entire contents of a file into a string: file =
open("[Link]", "r") contents = [Link]() print(contents) [Link]()
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.
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("[Link]",
"r") as file:
contents = [Link]() print(contents)
Examples
116
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("[Link]", "w")
When you run this program, it will create a new file named [Link] in the current
directory, write the specified text to the file, read the contents of the file, and then print 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("[Link]", "w")
117
# Write some text to the file [Link]("This is line 1.\n")
[Link]("This is line 2.\n") [Link]("This is line 3.\n")
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("[Link]", "w")
# Read and print the contents of the file, line by line line = [Link]()
while line:
print(line) line =
[Link]()
118
# Close the file [Link]()
When you run this program, it will create a new file named [Link] in the current
directory, write the specified text to the file, read the contents of the file line by line, and then
print each line to the console. The program then closes the file, releasing any resources it was
using.
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 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
119
You can strip the newline character from the end of a string using the strip method. For
example:
Output
This is a string
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.
120
# Read three lines from the file line1 =
[Link]() line2 = [Link]()
line3 = [Link]()
Output
John Locke
David Hume
Edmund Burke
• This program reads the contents of a file named [Link] one line at a time. The
program starts by opening the file in read mode using infile = open('[Link]', '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 [Link](), and prints the contents of the three
lines that were read from the file.
121
• 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.
# Verify that the data was written to the file with open('[Link]', 'r') as
f:
print([Link]())
In this example, the file '[Link]' 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.
122
6.8 Writing and Reading Numeric Data
Before writing, numbers must be converted to strings. A value is turned into a string by the
built-in function str.
• This code will open the file [Link] 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.
124
A line of text is automatically read from the input file by the for loop. There is no special
condition or testing needed and the priming read is not required. The loop automatically
terminates whenever the file's end is reached.
Example:
# Open the file for reading with
open('[Link]', 'r') as file:
# Initialize a variable to keep track of the sum sum = 0
• This code will open the file [Link] 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.
125
Review Questions
1. A file that data is read from is known as a(n) .
a. input file
b. output file
c. sequential access file
d. binary file
2. Before a file can be used by a program, it must be .
a. formatted
b. encrypted
c. closed
d. opened
3. This type of file contains data that has not been converted to text. a. text
file
b. binary file
c. Unicode file
d. symbolic file
4. When working with this type of file, you access its data from the beginning of the file to
the end of the file.
a. ordered access
b. binary access
c. direct access
d. sequential access
5. This is a small “holding section” in memory that many systems write data to before writing
the data to a file.
a. buffer
b. variable
c. virtual file
d. temporary file
6. This marks the location of the next item that will be read from a file.
a. input position
b. delimiter
c. pointer
126
d. read position
7. When a file is opened in this mode, data will be written at the end of the file’s existing
contents.
a. output mode
b. append mode
c. backup mode
d. read-only mode
8. True/False
When you open a file that file already exists on the disk using the 'w' mode, the contents of
the existing file will be erased.
9. True/False
The process of opening a file is only necessary with input files. Output files are automatically
opened when data is written to them.
10. If an existing file is opened in append mode, what happens to the file’s existing contents?
11. If a file does not exist and a program attempts to open it in append mode, what happens?
12. Assume a file containing a series of names (as strings) is named [Link] and exists on
the computer’s disk. Write a program that displays the number of names that are stored in
the file. (Hint: Open the file and read every string stored in it. Use a variable to keep a count
of the number of items that are read from the file.)
13. Write a program that writes a series of random numbers to a file. Each random number
should be in the range of 1 through 500. The application should let the user specify how
many random numbers the file will hold.
127
References
Gaddis, T. (2021). Starting out with Python. 5th Global Ed. United Kingdom: Pearson
Education. ISBN: 9781292408637
[Link]. (2019). The Python Tutorial — Python 3.8.0 documentation. [online] Available
at: [Link]
128