0% found this document useful (0 votes)
6 views167 pages

Programming 511 Study Guide

The document serves as a learner guide for Programming 511 at Richfield Graduate Institute of Technology, focusing on foundational programming concepts using Python. It covers essential topics such as computer operation, data storage, high-level programming languages, and Python syntax, aiming to equip students with the necessary skills for coding and problem-solving. The guide outlines the structure of the IT qualification programs and emphasizes the integration of theoretical knowledge with practical applications in the evolving tech landscape.

Uploaded by

Patrick Daniel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views167 pages

Programming 511 Study Guide

The document serves as a learner guide for Programming 511 at Richfield Graduate Institute of Technology, focusing on foundational programming concepts using Python. It covers essential topics such as computer operation, data storage, high-level programming languages, and Python syntax, aiming to equip students with the necessary skills for coding and problem-solving. The guide outlines the structure of the IT qualification programs and emphasizes the integration of theoretical knowledge with practical applications in the evolving tech landscape.

Uploaded by

Patrick Daniel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 167

STUDENT GUIDE

FACULTY OF INFORMATION TECHNOLOGY

PROGRAMMING 511

i
Registered with the Department of Higher Education as a Private Higher Education Institution under the Higher
Education Act, 1997.Registration Certificate No. 2000/HE07/008

FACULTY OF INFORMATION TECHNOLOGY

LEARNER GUIDE

MODULE: PROGRAMMING 511

PREPARED ON BEHALF OF

RICHFIELD GRADUATE INSTITUTE OF TECHNOLOGY (PTY) LTD

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.

ii
Gaddis, T. (2021). Starting
out with Python. 5th
Global Ed. United
Kingdom: Pearson
Education. ISBN:
9781292408637

iii
Chapter One: INTRODUCTION TO COMPUTERS AND PROGRAMMING ....................................... 1
1.1 Introduction................................................................................................................... 3
1.1.1 Understanding How Computers Work .......................................................................... 3
1.1.2 High-level Programming Languages.............................................................................. 4
1.1.3 Introduction to Python ................................................................................................. 5
1.2 Hardware and Software ................................................................................................. 6
1.3 Software Aspect .................................................................................................................. 9
1.3.1 Software ..................................................................................................................... 10
1.4 How Computers Store Data ............................................................................................... 11
1.5 Storing Numbers in Python ............................................................................................... 12
1.5.1 Introduction to Binary System .................................................................................... 13
1.5.2 Storing Characters in Python ...................................................................................... 14
1.5.2 Advanced Number Storage ......................................................................................... 15
1.6 Review Questions .............................................................................................................. 17
Chapter Two: PYTHON FUNDAMENTALS .................................................................................... 25
2.1 Introduction ...................................................................................................................... 25
2.2 Designing a program ......................................................................................................... 25
2.3 Input, Processing, and Output ........................................................................................... 29
2.4 Displaying Output with the print Statement...................................................................... 30
2.5 Comments ......................................................................................................................... 31
2.6 Variables ............................................................................................................................ 33
2.7 Displaying Multiple Items with the print Statement .......................................................... 36
2.8 Numeric Data Types and Literals ....................................................................................... 39
2.8.1 Understanding Numeric Literals ................................................................................. 39
2.8.2 Determining Data Types with type() Function ............................................................ 40
2.8.3 Creating and Using Strings .......................................................................................... 41
2.8.4 Dynamic Typing in Python .......................................................................................... 42
2.8.5 Reading Input from the Keyboard .............................................................................. 43
2.8.6 Performing Calculations ............................................................................................. 45

iv
2.8.7 Operator Precedence ................................................................................................. 47
2.8.9 The Exponent and Remainder Operators ................................................................... 48
2.8.10 Data Type Conversion ............................................................................................... 49
2.8.11 Escape Characters and String Concatenation ........................................................... 50
2.9 Formatting the output of a print statement ...................................................................... 52
2.10 Review Questions ............................................................................................................ 58
Chapter Three: Decision Structures and Boolean Logic ............................................................. 64
3.1 Introduction................................................................................................................. 64
3.2 The if Statement .......................................................................................................... 64
3.2.1 Boolean Expressions and Relational Operators .......................................................... 66
3.3 The if-else Statement................................................................................................... 68
3.4.1 Other String Comparisons .......................................................................................... 70
3.5 Nested Decision Structures and the if-elif-else Statement .......................................... 71
3.6 Logical Operators ......................................................................................................... 74
3.7 Boolean variable .......................................................................................................... 79
3.8 Review Questions .............................................................................................................. 80
Chapter Four: REPETITION STRUCTURES.................................................................................... 86
4.1 Introduction ...................................................................................................................... 86
4.2 Introduction to Repetition Structures................................................................................ 86
4.3 The while Loop: a Condition-Controlled Loop ................................................................... 87
4.4 The for Loop ...................................................................................................................... 89
4.5 Using the range Function with the for Loop ...................................................................... 90
4.6 Calculating a Running Total ............................................................................................... 95
4.6.1 The Augmented Assignment Operators ...................................................................... 96
4.7 Sentinels ............................................................................................................................ 96
4.8 Nested Loops ..................................................................................................................... 98
4.9 Review Questions ............................................................................................................ 101
Chapter Five: FUNCTIONS......................................................................................................... 111
5.1 Introduction .................................................................................................................... 111

v
5.1.1 Divide and Conquer .................................................................................................. 111
5. 1.2 Benefits of Using Functions ..................................................................................... 113
5.1.4 Void Function ........................................................................................................... 115
5.1.4 Pausing Execution Until the User Presses Enter........................................................ 118
5.1.5 Local Variables .......................................................................................................... 119
5.2 Passing Arguments to Functions ...................................................................................... 120
5.2.1 Parameter Variable Scope ........................................................................................ 122
5.2.1 Parameter Variable Scope ........................................................................................ 122
5.2.2 Passing Multiple Arguments ..................................................................................... 122
5.2.3 Mixing Keyword Arguments with Positional Arguments ........................................... 127
5.3 Global Variables and Global Constants ............................................................................ 128
5.3.1 Global Variables ........................................................................................................ 128
5.3.2 Global constants ....................................................................................................... 129
5.3.3 Introduction to Value-Returning Functions .............................................................. 130
5.4 Review Questions ........................................................................................................... 133
Chapter Six: FILES ...................................................................................................................... 138
6.1 Introduction .................................................................................................................... 138
6.2 Types of Files ................................................................................................................... 138
6.3 File Access Methods ........................................................................................................ 139
6.4 Opening a File ................................................................................................................. 140
6.5 Opening a File ................................................................................................................. 141
6.6 Reading Data from a File ................................................................................................. 141
6.7 Closing a file .................................................................................................................... 142
6.8 Concatenating a Newline to a String............................................................................... 146
6.9 Appending Data to an Existing File ................................................................................. 149
6.10 Writing and Reading Numeric Data ............................................................................... 150
6.11 Reading a File with a Loop and Detecting the End of the File ........................................ 152
6.12 Review Questions .......................................................................................................... 155
References ................................................................................................................................ 159

vi
The Information Technology (IT) qualification at Richfield College is a dynamic and future-focused
program designed to equip students with advanced technical, analytical, and problem-solving
skills. At the core of the qualification is a commitment to academic excellence, industry alignment,
and innovation, fostering graduates who are proficient in addressing modern technological
challenges. This qualification strategically integrates theoretical knowledge with practical
applications, preparing students for various roles in the IT sector. The IT program is structured to
address the growing complexity of the evolving technological landscape.

The Higher certificate in Information Technology (HCIT) program is a foundational stepping-stone


for students who wish to pursue further studies or enter the workforce. Graduates of this program
are well-prepared to articulate to the Diploma in IT (DIT) or the Bachelor of Science in IT (BSc IT)
qualifications, providing a seamless transition for those seeking to deepen their knowledge and
skills in specialized IT areas. Additionally, the program equips students with the essential
competencies for entry-level IT roles such as IT Support Technicians, Junior Web/ System
Developers, IT Administrators, etc.

The Diploma in Information Technology (DIT) is a comprehensive and practical program designed
to build a strong foundation in IT principles while equipping students with the hands-on skills
required to meet industry demands. Focused on both theoretical knowledge and applied
learning, this qualification prepares students for intermediate-level roles in IT and serves as a
stepping-stone for further academic progression or specialization. Graduates of this program are
well-prepared to articulate to the Bachelor of Science in IT (BSc IT) qualification. The curriculum
covers programming, networking, database management, system analysis etc., ensuring
graduates possess the competencies to solve real-world IT challenges effectively.

The Bachelor of Science in IT (BSc IT) program is structured to address the growing complexity of
the evolving technological landscape. Through carefully curated modules, students gain a deep
understanding of software development, database management, cloud computing,
cybersecurity, IT management, artificial intelligence, machine learning, networking etc.
Graduates of this program are well-prepared to articulate to the Bachelor of Science Honours in
IT qualification. The curriculum is designed to bridge the gap between academic learning and real-

1
world applications, thus fostering innovation and an entrepreneurial mindset. Students are
encouraged to participate in research and practical learning.

The programming focus within the IT qualification exemplifies academic innovation and
professional alignment. By integrating a diverse range of programming languages with practical
application, the curriculum prepares students to excel in the rapidly evolving tech industry. The
program aligns with industry courses from globally recognized leading tech giants, such as Oracle,
AWS, IBM, etc ensures that graduates possess the credentials to validate their expertise in
software development and cloud-based technologies. This blend of foundational knowledge,
practical experience, and industry-standard courses prepares students for immediate
employment and establishes a strong basis for long-term career advancement in software
development.

Programming 511 serves as a critical introduction to programming using Python, laying a strong
foundation for first-year students to develop essential coding skills and logical problem-solving
abilities. This module equips students with a comprehensive understanding of programming
concepts, including variables, control structures, functions, and basic file operations, while
fostering a hands-on approach to writing and debugging code.

2
Chapter One: INTRODUCTION TO COMPUTERS AND PROGRAMMING

LEARNING OUTCOMES
After reading this Section of the guide, the learner 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.

1.1.1 Understanding How Computers Work

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 Storage and Manipulation

Computers use binary (0s and 1s) to represent data. This binary system is the basis of data storage
and manipulation in computer systems. Through a combination of hardware and software,
computers can process this binary data to perform calculations, data analysis, and various other
tasks.

3
1.1.2 High-level Programming Languages

High-level programming languages, such as Python, are designed to be closer to human language,
making them more accessible and easier to learn for beginners and professionals alike. These
languages abstract the complexities of binary code and hardware specifics, allowing
programmers to focus on solving problems rather than the intricacies of machine-level
instructions. By providing a more intuitive interface, high-level languages empower developers
to write, debug, and maintain code more efficiently.

Advantages of High-Level Languages

High-level languages offer several key advantages that make them a preferred choice for
programming:

1. Improved Readability: The syntax of high-level languages is often clear and


straightforward, resembling natural language, which makes the code easier to
understand and share.

2. Easier Debugging and Maintenance: With a simplified structure and comprehensive error
messages, these languages enable quicker identification and resolution of issues.

3. Cross-Platform Compatibility: Most high-level languages are designed to run on multiple


platforms without modification, enhancing their flexibility and usability across different
environments.

4
1.1.3 Introduction to Python

It is an ideal programming language for beginners due to its simplicity and readability. Python is
versatile, widely used in web development, data science, artificial intelligence, and more. Python
offers two primary modes of operation, catering to different stages of development and use
cases:

Interactive Mode

Interactive mode allows users to type Python commands directly into an interpreter and receive
immediate feedback. It is particularly useful for beginners, learning purposes, or testing snippets
of code.

Script Mode

In script mode, python code is written in a file, which can then be executed as a complete
program. This mode is ideal for developing more comprehensive and structured applications.

IDLE Environment

IDLE (Integrated Development and Learning Environment) is Python’s default development


environment, designed to make programming approachable and efficient, especially for
beginners. It provides a user-friendly interface that allows users to write, debug, and execute
Python scripts seamlessly. With features like syntax highlighting, auto-completion, and a built-in
interactive shell, IDLE simplifies the process of learning and experimenting with Python code. Its
lightweight nature and ease of use make it a preferred starting point for those new to
programming.

5
Figure 1.1 A word processing program and a presentation program (Gaddis, 2021)

Figure 1.1 Shows a basic network made up of host computers connected, they share resources
such as files. These devices can talk to each other using a computer language called the binary
code which consists of 1s and 0s in a specific sequence that describe exactly what they want to
“say”.

1.2 Hardware and Software


Understanding Computer Hardware
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.

6
Figure 1.2 Typical components of a computer system (Gaddis, 2021)

Central Processing Unit (CPU)


The Central Processing Unit (CPU), often referred to as the brain of a computer, is integral to
executing program instructions. It performs fundamental arithmetic, logical, and input/output
operations that drive the functioning of the system. In Python programming, the CPU plays a
critical role by interpreting and executing Python code line by line, with its efficiency directly
influencing the program's runtime speed. Historically, CPUs have evolved significantly, with one
of the earliest examples being the ENIAC, the first programmable computer built in 1945. Despite
its massive size—8 feet tall, 100 feet long, and weighing 30 tons—it laid the groundwork for
modern computing advancements.

7
Figure 1-3 The ENIAC computer (Gaddis, 2021)

The Role of Memory and Storage in Computing


In modern computing, microprocessors are significantly smaller and more powerful than their
predecessors, enabling efficient handling of memory and storage components. Two key memory
types—main memory (RAM) and secondary storage—play distinct but interconnected roles in
computer operations.

Main Memory (RAM)

8
Main memory, or Random Access Memory (RAM), temporarily stores data that the CPU actively
uses or processes. In Python programming, RAM holds Python programs and their variables
during execution. The amount of available RAM directly impacts the performance of Python
applications, particularly when dealing with large datasets or memory-intensive tasks.

Secondary Storage
Secondary storage, such as hard drives and solid-state drives (SSDs), provides persistent data
storage. Unlike RAM, the data stored in secondary storage remains intact even after the
computer is powered off. This storage medium is crucial for Python programming as it stores
Python scripts and files long-term. Python programs frequently interact with secondary storage,
reading from and writing to files, ensuring data persistence beyond the runtime of the program.
Python, while fundamentally a software tool, operates in close synergy with hardware
components for optimal performance. The efficiency of Python programs relies heavily on
hardware resources such as the CPU, RAM, and secondary storage. These components ensure
smooth execution, memory management, and data handling in Python-based applications.

Together, RAM and secondary storage enable efficient data management and execution in
Python and other programming environments, illustrating the synergy between memory and
processing power in modern computing.

1.3 Software Aspect

Python’s Interaction with Hardware

Python’s capabilities are inherently tied to the hardware it runs on. Efficient CPU processing
allows for faster interpretation and execution of Python scripts. Adequate RAM ensures that
Python programs, especially those working with large datasets or complex computations,
perform without bottlenecks. Secondary storage provides the persistence needed to store

9
Python files and outputs beyond runtime. These hardware resources collectively influence
Python's overall performance.

Think Point: Can you identify other input devices that Python programs can
interact with?

Output Devices in Python Programming


Output devices are essential in visualizing and interacting with data processed by Python
programs. They are critical for debugging, data analysis, and creating user-friendly interfaces.

Monitor
As a primary output device, monitors display results from Python programs. Using GUI libraries
like Tkinter or PyQt, Python can create applications with rich visual interfaces displayed on
monitors.

Printer
Python can interact with printers to convert digital data into physical outputs, such as formatted
documents or reports.
Output devices bridge the gap between software processes and tangible results, enhancing the
usability of Python programs in real-world applications.

1.3.1 Software

Software is a non-physical yet vital aspect of computing, comprising system software and
application software. Python interacts with and contributes to both categories.

1. System Software
System software refers to a collection of programs designed to manage and control the hardware
components of a computer and provide a platform for other software to run. It acts as an
intermediary between hardware and user applications, ensuring the efficient operation of a
computer system.

10
a) Operating Systems
The backbone for running Python interpreters and Integrated Development Environments (IDEs)
like PyCharm or Visual Studio Code. The operating system manages the underlying hardware to
support Python execution.
b) Utility Programs
System management tools and antivirus programs often leverage Python scripts for automation
and functionality enhancement.
c) Software Development Tools
Python itself serves as a software development tool, enabling developers to create, test, and
modify various applications.

2. Application Software
Application software consists of programs designed to perform specific tasks or solve particular
problems for users. Unlike system software, it directly serves the user's needs and typically
operates on top of the operating system. Python is widely used to develop application software
tailored for specific tasks, including:
a) Productivity Software: Word processors, spreadsheets, and presentation tools like
Microsoft Word, Excel, and PowerPoint.
b) Web Browsers: Applications like Google Chrome and Mozilla Firefox for accessing the
internet.
c) Specialized Software: Programs for graphic design (e.g., Adobe Photoshop), web
development (e.g., Dreamweaver), or data analysis (e.g., Tableau).
d) Entertainment Software: Games and media players

1.4 How Computers Store Data


Understanding data storage is crucial for Python programmers, especially when dealing with data
types and memory management.

a. Bytes and Bits

11
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.

b. 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.

Figure 1-5 Think of a byte as eight switches

1.5 Storing Numbers in Python


Python's ability to handle numerical data is rooted in the binary system, a foundational concept
in computing.

12
1.5.1 Introduction to Binary System

Binary, the language of computers, uses two states: 'on' (1) and 'off' (0). This system underpins all
modern computing by representing information in combinations of 0s and 1s. In digital
electronics and computing, information is represented using two states: 'on' and 'off'.

Binary Numbering System

Binary numbers consist of digits called "bits," with each bit’s position representing an increasing
power of 2. For instance, in the binary number 1011, the rightmost bit equals 20, the next 21, and
so forth. Python can efficiently process binary data.

Decimal to Binary Conversion

Python simplifies conversions between decimal (base-10) and binary (base-2) using the bin()
function. For example, bin(10) returns 0b1010, where 0b denotes a binary number.

Binary Arithmetic in Python

Python supports binary arithmetic (e.g., addition(+), subtraction(-), multiplication(*), and division
(/)) and bitwise operations (e.g., AND (&), OR (|), XOR (^), NOT (~), left shift (<<), and right shift
(>>)). These functionalities allow for advanced manipulation of binary data.

Practical Applications

Binary concepts in Python are vital for encoding data, performing file I/O operations, and
managing system-level interactions. Understanding binary enhances Python’s use in developing
robust, low-level applications.

13
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

1.5.2 Storing Characters in Python

Characters in Python are stored as binary numbers, a practice that facilitates efficient processing
and storage.

14
Binary Representation

Every character, including letters and symbols, maps to a unique binary code. For instance, the
ASCII code for uppercase 'A' is 65, stored as the binary number 01000001.

ASCII: The Character Encoding Standard

ASCII is a widely used standard, encoding 128 characters, including English letters and control
characters. Python leverages this standard through the ord() and chr() functions, enabling easy
conversion between characters and their ASCII values.

Python and Character Encoding

Python extends beyond ASCII to support Unicode, accommodating characters from multiple
languages and symbols. Developers can explore encoding concepts by converting strings to ASCII
values or creating ASCII art in Python.

1.5.2 Advanced Number Storage

Python efficiently handles advanced numerical representations using binary.

Two’s Complement Encoding

This encoding method represents negative numbers in binary, enabling seamless arithmetic
operations.

Floating-Point Notation

For real numbers with fractional parts, Python uses floating-point notation. This precision is
crucial for scientific computations and graphics rendering.

How a Program Works

The CPU processes instructions written in machine language, the binary form of code. Machine
language programming is complex, but assembly language simplifies it using mnemonic codes.
An assembler translates these codes into machine-readable formats. Python, as a high-level
language, abstracts this complexity, allowing developers to focus on problem-solving.

15
High-level languages like Python rely on compilers and interpreters to convert source code into
machine language. While a compiler translates the entire program at once, an interpreter
processes it line by line, offering real-time feedback.

Figure 1-10 Compiling a high-level program and executing it

An interpreter is a program that both translates and executes the instructions in a high-level
language program.

Figure 1-11 Executing a high-level program with an interpreter

16
Figure 1-12 SPYDER IDLE

1.6 Review Questions


1.1 What is a program?
1.2 What is hardware?
1.3 List the five major components of a computer system.
1.4 What part of the computer actually runs programs?
1.5 What part of the computer serves as a work area to store a program and its
data while the program is running?
1.6 What part of the computer holds data for long periods of time, even when
there is no power to the computer?
1.7 What part of the computer collects data from people and from other devices?
1.8 What part of the computer formats and presents data for people or other devices?

1. 9 What amount of memory is enough to store a letter of the alphabet or a small

17
number?
1. 10 What do you call a tiny “switch” that can be set to either on or off?
1.11 In what numbering system are all numeric values written as sequences of 0s
and 1s?
1.12 What is the purpose of ASCII?
1.13 What encoding scheme is extensive to represent all the characters of all the languages
in the world?
1.14 What do the terms “digital data” and “digital device” mean?
1.15 A CPU understands instructions that are written only in what language?
1.16 A program has to be copied into what type of memory each time the CPU
executes it?
1.17 When a CPU executes the instructions in a program, it is engaged in what
process?
1.18 What is assembly language?
1.19 What type of programming language allows you to create powerful and complex
programs without knowing how the CPU works?
1.20 Each language has a set of rules that must be strictly followed when writing a
program. What is this set of rules called?
1.21 What do you call a program that translates a high-level language program into
a separate machine language program?
1.22 What do you call a program that both translates and executes the instructions
in a high-level language program?
1.23 What type of mistake is usually caused by a misspelled key word, a missing
punctuation character, or the incorrect use of an operator?
1.24 What fundamental set of programs controls the internal operations of the computer’s
hardware?
1.25 What do you call a program that performs a specialized task, such as a virus
scanner, a file compression program, or a data backup program?
1.26 Word processing programs, spreadsheet programs, email programs, Web

18
browsers, and game programs belong to what category of software?

Multiple Choice
1. 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
d. the CPU
4. Today, CPUs are small chips known as _____.
a. ENIACs
b. microprocessors
c. memory chips
d. operating systems
5. The computer stores a program while the program is running, as well as the data
that the program is working with, in _____.
a. secondary storage
b. the CPU
c. main memory
d. the microprocessor

19
6. This is a volatile type of memory that is used only for temporary storage while a
program is running.
a. RAM
b. Secondary storage
c. The disk drive
d. The USB drive
7. A type of memory that can hold data for long periods of time—even when there is
no power to the computer––is called _____.
a. RAM
b. main memory
c. secondary storage
d. CPU storage
8. 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
9. A video display is a(n) _____.
a. output device
b. input device
c. secondary storage device
d. main memory
10. A _____ is enough memory to store a letter of the alphabet or a small number.
a. byte
b. bit
c. switch
d. transistor
11. A byte is made up of eight _____.

20
a. CPUs
b. instructions
c. variables
d. bits
12. In a(n) _____ numbering system, all numeric values are written as sequences of 0s
and 1s.
a. hexadecimal
b. binary
c. octal
d. decimal
13. A bit that is turned off represents the following value: _____.
a. 1
b. −1
c. 0
d. “no”
14. A set of 128 numeric codes that represent the English letters, various punctuation
marks, and other characters is _____.
a. binary numbering
b. ASCII
c. Unicode
d. ENIAC
15. An extensive encoding scheme that can represent the characters of many of the
languages in the world is _____.
a. binary numbering
b. ASCII
c. Unicode
d. ENIAC
16. Negative numbers are encoded using the _____ technique.
a. two’s complement

21
b. floating-point
c. ASCII
d. Unicode
17. Real numbers are encoded using the _____ technique.
a. two’s complement
b. floating-point
c. ASCII
d. Unicode
18. The tiny dots of color that digital images are composed of are called _____.
a. bits
b. bytes
c. color packets
d. pixels
19. If you were to look at a machine language program, you would see _____.
a. Java code
b. a stream of binary numbers
c. English words
d. circuits
20. In the _____ part of the fetch-decode-execute cycle, the CPU determines which
operation it should perform.
a. fetch
b. decode
c. execute
d. immediately after the instruction is executed
21. Computers can only execute programs that are written in _____.
a. Java
b. assembly language
c. machine language
d. C++

22
22. The _____ translates an assembly language program to a machine language program.
a. assembler
b. compiler
c. translator
d. interpreter
23. The words that make up a high-level programming language are called _____.
a. binary instructions
b. mnemonics
c. commands
d. key words
24. The rules that must be followed when writing a program are called _____.
a. syntax
b. punctuation
c. key words
d. operators
25. A(n) _____ program translates a high-level language program into a separate
machine language program.
a. assembler
b. compiler
c. translator
d. utility

True or False
1. Today, CPUs are huge devices made of electrical and mechanical components such
as vacuum tubes and switches.
2. Main memory is also known as RAM.
3. Any piece of data that is stored in a computer’s memory must be stored as a binary
number.
4. Images, like the ones you make with your digital camera, cannot be stored as binary

23
numbers.
5. Machine language is the only language that a CPU understands.
6. Assembly language is considered a high-level language.
7. An interpreter is a program that both translates and executes the instructions in a
high-level language program.
8. A syntax error does not prevent a program from being compiled and executed.
9. Windows, macOS, iOS, Android, and Linux are all examples of application
software.
10. Word processing programs, spreadsheet programs, email programs, Web browsers,
and games are all examples of utility programs.

24
Chapter Two: PYTHON FUNDAMENTALS

LEARNING OUTCOMES
After reading this Section of the guide, the learner 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
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

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.
25
➢ 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 log

Fig 2.1 Program development life cycle

Steps in Program Design:

1.Understand the Task

➢ This involves comprehending the program's purpose, often derived from client
requirements.

2. Determine Steps to Perform the Task

➢ Developing an algorithm, which is a series of logical steps to achieve the task.

Example: Program to Calculate Gross Pay

I. Obtain the number of hours worked.


II. Determine the hourly pay rate.
III. Multiply hours by the pay rate to calculate gross pay.
IV. Display the gross pay result.
Pseudocode

Pseudocode is an informal, non-executable way of outlining a program's logic. It helps


programmers focus on the design without getting bogged down by syntax.

Example of Pseudocode

26
I. Input the hours worked.

II. Input the hourly pay rate.

III. Calculate gross pay (hours worked × hourly rate).

IV. Display the gross pay.


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.

Fig 2.2 Common flowchart symbols

27
Common Flowchart Symbols

1. Rectangle: A process or operation.

2. Diamond: A decision point in the program.

3. Arrow: The direction of process flow.

4. Terminal: Marks the start or end of the flowchart.

5. Process: An action or operation.

6. Decision: A point where the flow diverges based on a condition.

7. Connector: Links different parts of the flowchart.

Example of Flowchart for the pay calculating program

Flowchart
Steps Pseudocode

Start Start

1.Obtain the number of hours 1.Input the hours worked.


worked.
2.Input the hourly pay rate.
2.Determine the hourly pay
3.Calculate gross pay (hours
rate.
worked × hourly rate).
3.Multiply hours by the pay
4.Display the gross pay.
rate to calculate gross pay.
4.Display the gross pay result.

Fig 2.3 Example of Flowchart for the pay calculating program

28
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.

2.3 Input, Processing, and Output

Computer programs typically perform these three crucial steps:

➢ Input Reception: Gathering data from external sources like keyboard input.43
➢ Processing: Performing operations on the received input.
➢ Output Generation: Producing results based on the processed data.

Figure 2-3 The input, processing, and output of the pay calculating program

Input
In Python, Input refers to the process of gathering data from the user or an external source for the
program to use. This is typically done using the input() function, which prompts the user to enter
information. The data entered is then treated as a string by default, but it can be converted into
other data types such as integers or floats if needed. Input is essential for creating interactive
programs, allowing users to provide the necessary data for further processing. For instance, a
program might ask for the user’s age using age = int(input("Enter your age: ")).

Processing

29
Processing is the stage where the input data is manipulated, calculated, or analyzed to produce a
desired result. This involves applying logic, performing calculations, or executing algorithms to
transform the input into meaningful information. Processing can include tasks such as summing
numbers, sorting lists, or evaluating conditions. For example, a program might use the user's input
age to determine if they are eligible to vote by checking if the age is greater than or equal to 18.
This step is the core logic of a program, where the actual work happens.

Output

Output is the final stage in the program, where the results of the processing are conveyed to the
user. Python typically uses the print() function to display output on the screen. The output can be
text, numbers, or even graphical representations, depending on the program's design. This step
ensures the user receives feedback or the final result of the program's logic. For example, after
processing the user’s age, the program might display the message "You are eligible to vote." or
"You are not eligible to vote." Output completes the cycle of interaction, making the program's
results visible and actionable for the user.

2.4 Displaying Output with the print Statement

In Python, print is a built-in function used for displaying output To display "Python Programming",
use print ("Programming"). The argument passed within the parentheses is the data to be
displayed on the screen.
Outputting Names of African Countries:
Code Output

30
Strings in Python are sequences of characters used as data. When a string appears directly in
code, it's called a string literal. Strings can be enclosed in single, double, or triple quotes Use
double quotes if the string contains a single quote (apostrophe) and vice versa.

Code Output

2.5 Comments
Comments are non-executable statements that help explain and annotate code. They do not
affect the program's execution and are ignored by the Python interpreter. Comments are
essential for making code readable and maintainable, especially in collaborative projects or when
revisiting code after a long time.

Types of comments
a. Single-line Comments
Single-line comments in Python begin with a hash symbol (#) and extend to the end of the line.
They are used to explain a specific line of code or provide quick annotations.
Code Output
No output

16

31
b. Multi-line Comments
Multi-line comments are enclosed within triple quotes (''' or """). They are useful for writing
explanations or documentation that span multiple lines.

Examples:

Best Practices for Using Comments


➢ Be concise: Use comments to clarify why a particular approach is used, not what the code
does (the code itself should be self-explanatory).
➢ Use single-line comments for quick notes and multi-line comments for detailed
explanations.
➢ Avoid over-commenting, which can clutter the code and make it harder to read.

Key Differences

32
2.6 Variables
Variables in Python are named locations in memory for storing data values. Use the assignment
operator = to assign values to variables. Python automatically determines the type of variable
based on the assigned value. Variables are fundamental in Python programming as they allow
you to store, retrieve, and manipulate data. Using the assignment operator (=), you can easily
define and reassign variables to suit your program's needs. Their flexibility and dynamic typing
make Python a powerful and easy-to-use language for both beginners and professionals.

Syntax Code example

Naming Rules

When naming variables in Python, it is essential to follow specific rules to ensure the code is valid
and clear. These rules help prevent errors and make the program easier to read and maintain.
These words have special meanings in Python and using them as variable names will lead to
syntax errors. Variable names are case-sensitive in Python. This means age, Age, and AGE are
treated as three distinct variables. Spaces are not allowed within variable names. They must be a
single continuous string of characters.

➢ 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.

33
1. Must Begin with a Letter or Underscore (_):

➢ Variable names should start with a letter (a-z, A-Z) or an underscore (_).
➢ They cannot start with digits.

2. Can Include Letters, Digits, or Underscores After the First Character:

o After the first character, variable names can contain any combination of letters, digits,
or underscores.

• Letters (a-z, A-Z)

• Digits (0-9)

• Underscores (_)

3. Should Not Be a Reserved Word in Python:

o Reserved words (keywords) in Python, such as for, while, if, and global, cannot be
used as variable names because they have predefined meanings in Python.

4. Case-Sensitive:

o Variable names in Python are case-sensitive. This means age, Age, and AGE are treated
as three different variables.

34
5. Cannot Contain Spaces:

o Variable names must be a single continuous string without spaces. Use underscores
(_) to separate words if needed.

Conventions for Enhanced Readability

It is a common practice to use lowercase letters with underscores separating words for variable
names. This format enhances readability, especially for longer names. Alternatively, the
CamelCase naming convention can be used, particularly in contexts where it aligns with the
surrounding code's style (e.g., certain class names). In CamelCase, each word or abbreviation in
the middle of the phrase begins with a capital letter, with no intervening spaces or punctuation.

Lowercase CamelCase

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.

35
2.7 Displaying Multiple Items with the print Statement

In Python, the print() function is a versatile tool used to display data on the screen or other
standard output devices. It allows you to output multiple items, variables, or results in a flexible
manner. Here's an overview of how to use it effectively:

1. Basic Multiple Printing

The print() function can display multiple items by separating them with commas. This feature is
helpful when you want to output text alongside variable values or results.

Code Output

2. Displaying Variables

You can display the values of variables directly within a print() statement by including them as
arguments.

Code Output

36
3.Using end Parameter

The end parameter in the print() function specifies what to print at the end of the output. By
default, end is set to '\n' (newline character), but you can change it to space, comma, or any other
string.

Code Output

4. Using sep Parameter:

The sep parameter defines the separator between multiple items in the print() statement. By
default, it is a single space (' '), but it can be customized. In the example below, the sep parameter
is set to " | ", replacing the default space between items.

Code Output

5.Variable Reassignment

In Python, variables can be reassigned to new values using the assignment operator (=). Once a
variable is assigned a new value, it refers to this value until it is reassigned again.

Example 1 Example 2

37
Example 2

➢ The variable temperature is assigned the value 25.

➢ In memory, temperature points to the value 25.

➢ The variable temperature is reassigned the value 30.

➢ At this point, temperature now references 30, and the old value 25 is no longer
accessible through the program.

➢ The old value (25) remains in the computer's memory temporarily, even though the
variable no longer references it.

➢ Python's garbage collector periodically identifies such unreferenced values and


removes them from memory, ensuring efficient memory management.

In Python, when a variable is reassigned a new value, the old value is still stored temporarily in
the computer's memory. However, since the variable no longer references the old value, it
becomes inaccessible and cannot be used by the program. Python's garbage collection
mechanism eventually removes this unreferenced value from memory to free up space.

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

38
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.

2.8 Numeric Data Types and Literals

2.8.1 Understanding Numeric Literals

In programming, a numeric literal is a direct representation of a number in the code. In Python,


numeric literals are categorized into different data types based on their format and the kind of
number they represent.

Types of Numeric Literals:

1. Integer (int)
39
➢ 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.52
➢ Examples: 1.5, 3.1415, 5.0.

2.8.2 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

In these examples, 1 is identified as an integer (int), and 1.0 as a floating-point number (float).

Storing Strings with the str Data Type

The String Data Type (str):

40
In Python, strings are sequences of characters used to store textual data. The str data type
represents strings. Strings in Python are enclosed in quotes, which can be single ('...'), double
("..."), or triple-quoted ('''...''' or """...""" for multi-line strings).

2.8.3 Creating and Using Strings

String Operations

Strings in Python are objects and come with various built-in methods for manipulation, such as
upper(), lower(), strip(), split(), etc. Strings are immutable, meaning once they are created, their
contents cannot be changed.

Reassigning a Variable to a Different Type

41
2.8.4 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:

Code

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

42
value3 = 7.0

value4 = 7

value5 = 'abc'

After execution, the Python data types are:

value1: <class 'int'>54

value2: <class 'float'>

value3: <class 'float'>

value4: <class 'int'>

value5: <class 'str'>

2.8.5 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:

Code Output
What is your name? John
Hello, John

This code will prompt the user with "What is your name?" and store the user's response in the
name variable.

43
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:

Code Output
What is your age? 25
You are 25 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()

Code Output

44
What is your name? John
What is your age? 25
What is your income? 50000.75
Here is the data you entered:
Name: John
Age: 25
Income: 50000.75

In Python, the following are the basic mathematical operators:

2.8.6 Performing Calculations

Example

45
Integer Division

Integer division is the behavior that results when an integer is divided by another integer resulting
in the answer being an integer as well.

For Example:

Code

46
2.8.7 Operator Precedence
In Python, the order of operations (precedence) for mathematical operators is determined by
the following rules:

1. Parentheses (()) first


2. Exponentiation (**) second
3. Multiplication (*), division (/), and floor division (//) are next, evaluated from left to right.
4. Addition (+) and subtraction (-) last, evaluated from left to right.
Here is an example to demonstrate the operator precedence in

Python: a = 5 b =3 c = 2

result = a + b * c ** 2

47
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

Grouping with Parentheses

Source: Gaddis (2021) page 58

2.8.9 The Exponent and Remainder Operators

** is the exponent operator. Its purpose is to raise a number to a power.

For Example: a = 2 b = 3 c = a **b

print(c) # Output: 8

% is the remainder operator. Its purpose is to perform division and return the remainder.

For Example: leftover = 17 % 3 #remainder is 2

Converting math formulae to programming statements

48
2.8.10 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.

float() and int() are two of python’s built in functions.

int(item): You pass an argument to the int() function and it returns the argument’s value

converted to an int.

float(item): You pass an argument to the float() function and it returns the argument’s value

converted to a float.

For example:

x = 27.9

y = int(x) # y will be assigned 27

x = -12.9

49
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)

2.8.11 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.

50
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.

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

51
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 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.

52
Output

My name is John and I am 32 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:

Code Output

53
My name is John Doe and I am 30 years old.

This gives the same output as the format() method.

2.9.3 Formatting Numbers

Float-point Numbers, without formatting the number can be displayed with up to 12 significant
digits. The % symbol is a string format operator when the operand on the left side of the % is a
string. A formatting specifier is a special set of characters that specify how a value should be
formatted.

For example:

Code Output

54
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:

Code Output

55
Example:

Code Output

Here, d specifies that the value should be formatted as a decimal integer. Specifying a Minimum
Field Width. The %d formatting specifier is used for formatting an integer while the %s specifier
is used to format a string.

Summary of Formatting Specifiers

For example:

Code Output

56
Named Constants

Named constants are values that don't change throughout the execution of a program. While
Python does not have a direct mechanism for declaring named constants, a common convention
is to use all capital letters with underscores to indicate that the variable should not be changed.

For example:

PI = 3.14159265358979323846

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 named tuple.

57
Output

The area of a circle with radius 5 is 78.53975

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?

2.10 Review Questions


2. 1 Who is a programmer’s customer?

2. 2 What is a software requirement?

2. 3 What is an algorithm?

2. 4 What is pseudocode?

2. 5 What is a flowchart?

58
2. 6 What are each of the following symbols in a flowchart?

• Oval
• Parallelogram
• Rectangle

2.7 What are the three operations that programs typically perform?

2.8 What is an IPO chart?

2.9 What is a sequence structure?

2.10 What is a string? What is a string literal?

2.11 A string literal is usually enclosed inside a set of what characters?

2.12 What is a variable?

2.13 Summarize three common rules for naming variables.

2.14 What variable naming convention do we follow in this book?

2.15 Look at the following pseudocode statement:

Input temperature

What happens when this statement executes?

2.16 Who is the user?

2.17 What is a prompt?

2.18 What two steps usually take place when a program prompts the user for input?

2.19 What does the term user-friendly mean?

2.20 What is an assignment statement?

2.21 When you assign a value to a variable, what happens to any value that is

already stored in the variable?

59
2.22 Summarize the mathematical order of operations, as it works in most programming

languages.

2.23 What is the purpose of the exponent operator?

2.24 What is the purpose of the modulus operator?

2.25 What two items do you usually specify with a variable declaration?

2.26 Does it matter where you write the variable declarations in a program?

2.27 What is variable initialization?

2.28 Do uninitialized variables pose any danger in a program?

2.29 What is an uninitialized variable?

2.30 What is external documentation?

2.31 What is internal documentation?

2.32 What are the two general types of comments that programmers write in a

program’s code? Describe each.

Multiple Choice Questions

1.A error does not prevent the program from running, but causes it

to produce incorrect results.

a. syntax

b. hardware

c. logic

60
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. d. program graph67

5. A is a sequence of characters.

a. char sequence

b. character collection

c. string

61
d. text block

6. This symbol marks the beginning of a comment in Python. a. &

b. *

c. **

d. #

7. Which of the following statements will cause an error?

a. x = 17

b. 17 = x

c. x = 99999

d. x = '17'

8. Which built-in function can be used to convert an int value to a float?

a. int_to_float()

b. float ()

c. convert ()

d. int()

9. What is the difference between floating-point division and integer division?

10. What is a magic number? Why are magic numbers problematic?

11. Complete the following table by writing the value of each expression in the Value
column:

Expression Value 6 +

3 * 568

12 / 2 − 4

9 + 14 * 2 − 6

62
(6 + 2) * 3

14 / (11 − 4)

9 + 12 * (8 − 3)

12. What value will be assigned to result after the following statement executes? result = 9

// 2

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

• The distance the car will travel in 15 hours

63
Chapter Three: Decision Structures and Boolean Logic

3.1

LEARNING OUTCOMES
After reading this Section of the guide, the learner should be able to:

• Write programs that use the if statement.


• Write programs that use the if-else statement.
• Compare strings in Python.
• Use nested decision structures and the if-elif-else statement in programs.
• Implement programs using logical operators.
• Utilize Boolean variables in programming.

Introduction
Decisions in programming are made using decision structures and conditions. In this chapter, you
will learn about relational operators, Boolean expressions, and decision structures. The control
flow of a program will be explored using the if, if-else, and if-elif-else statements. Additionally,
this chapter covers nested decision structures, logical operators, and the effective use of Boolean
variables in programming.

3.2The if Statement
A control structure determines the order in which a set of statements execute.

Sequence Structure

A sequence structure executes statements in the order they appear. For example:

64
The three statements above are executed in the order in which they appear. 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 64 common ways to
implement a decision structure is with an if statement.

Decision (Selection) Structure

A decision structure executes a set of statements only if a specified condition is true. The if
statement is the most common way to implement a decision structure.

Syntax Example

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".

Diamond symbol represents a true/false condition Single alternative decision structure provides
only one alternative path of execution.

65
Figure 3.1 A simple decision structure Decision (selection) structure:

3.2.1 Boolean Expressions and Relational Operators

A relational operator checks whether a specific relationship exists between two values. 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 (True or False).

Program example

66
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.

67
Source: Gaddis (2021) Page 125

3.3 The if-else Statement


An if-else statement provides two paths of execution. One path executes if the condition is true,
and the other executes if the condition is false.

Example:

Syntax Example

Figure 3-2 A dual alternative decision structure

68
Figure 3-3 Conditional execution in an if-else statement Source: Gaddis (2021) Page 125

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.

3.4 Comparing Strings

Strings can be compared using relational operators (==, !=, <, >, etc.). Comparisons are case-
sensitive.

Syntax Example

Output:
The strings are not equal.

Case-insensitive Comparison:

69
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.

3.4.1 Other String Comparisons

In addition to determining whether strings are equal or not equal, you can compare two strings
to determine if one is greater than or less than the other lexicographically (i.e., based on the
dictionary order of their characters). This can be done using the greater than (>) and less than (<)
operators.

Code Example Output

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.)

70
➢ A blank space is represented by the number 32.

➢ When a program compares characters, it actually compares the codes for the characters.

3.5 Nested Decision Structures and the if-elif-else Statement


Nested decision structures allow multiple conditions to be checked in sequence.

Figure 3-4 A nested decision structure

71
This program evaluates whether a bank customer qualifies for a loan based on two predefined
conditions: their annual salary and years of employment. It begins by defining constants for the
minimum salary (MIN_SALARY) and minimum years of employment (MIN_YEARS), making the
criteria easy to modify. The program then collects user input for their annual salary and years of
employment, converting the values into appropriate data types (float and int) for accurate
comparisons. Using a nested if structure, the program first checks if the user's salary meets or
exceeds the minimum requirement. If this condition is true, it proceeds to verify if the user's
employment duration satisfies the required years. If both conditions are met, the user is informed
they qualify for the loan. Otherwise, specific messages explain why they do not qualify, whether
due to insufficient salary or inadequate employment duration. This logical flow ensures clear
decision-making and user-friendly feedback, highlighting the effective use of conditional
statements to manage multiple evaluation criteria.

The if-elif-else Statement: This allows multiple conditions to be checked more efficiently.

72
Syntax Example

Output: 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.

73
Input:
The program prompts the user to enter their
score as an integer.

Decision Logic:

The if-elif structure checks the score against


multiple ranges:
• < 50: Grade F.
• < 60: Grade D.
• < 70: Grade C.
• < 80: Grade B.
• < 90: Grade A.
• >= 90: Grade A+ (handled by the final
else block).

3.6 Logical Operators


Logical operators are crucial in controlling program logic by combining or negating conditions.
The and operator requires that both conditions in a compound expression evaluate to True for
the entire expression to be True. If either condition is False, the expression evaluates to False,
which affects whether a block of code within an if statement executes. On the other hand, the or
operator only requires at least one condition to be True for the entire expression to evaluate to
True. If all conditions are False, only then will the expression evaluate to False. These operators
fundamentally alter the flow of execution in a program by determining which code block is
executed based on the truth values of the conditions. This flexibility allows developers to handle
complex decision-making scenarios effectively, enabling programs to respond dynamically to
various inputs and conditions

74
The and Operator

Output:
Both conditions are True

In this example:

• x < 10 evaluates to True.

• y > 5 evaluates to True. Since both conditions are true, the and operator returns True, and
the code inside the if block executes.

The or Operator

75
Example

Output:
At least one condition is True

In this example:

• x < 10 is True.

• y < 5 is False. Since at least one condition is true, the or operator returns True, and the if
block executes.

Boolean Compound Boolean expressions using logical operators

76
Output:
The temperature is in
the danger zone.

• temperature < 20 is True.

• minutes > 12 is True. Both conditions being true cause the if block to execute.

The not Operator

The not operator negates the truth value of a Boolean expression. If the expression evaluates to
True, applying not will make it False, and vice versa. This is particularly useful when you want to
execute a code block if a condition is not met.

Output:
x is not less than 10

The condition x < 10 evaluates to True, but the not operator negates it to False. As a result, the
else block is executed.

Another use case is when you want to ensure that a condition is not true, such as when a
temperature value exceeds a threshold:

77
Checking Numeric Ranges with Logical Operators

In Python, logical operators like <, >, <=, >=, ==, and != are combined with and/or to check if a
number falls within or outside a specific range. Proper use of logical operators ensures that your
program handles range checks efficiently and avoids logical errors.

Below are examples illustrating different scenarios:

1. Checking a Value Within a Range 2. Checking a Value Outside a Range

The first example: both conditions (x >= 20 and x <= 40) must be true for the message to be
printed. This ensures that the value of x is between 20 and 40, inclusive.

Second example: the or operator ensures that the message is printed if x is either less than 20
or greater than 40.

3. Logical Error 4. Validating a Value Within a Specific Range

Output: Output:
Number is within the range 0 to 10

78
There is a logical error because a number cannot simultaneously be less than 20 and greater than
40. The condition will always evaluate to False.

3.7 Boolean variable


A Boolean variable is a type of variable that can store only one of two possible values: True or
False. These values are essential in programming as they represent the truth or falsity of a
condition, allowing for logical decision-making in code. Boolean variables are commonly used in
control structures, such as if statements, to guide the program's flow depending on whether a
condition evaluates to True or False.

Basic Boolean Variables Boolean in Control Structures

Output:
Flag is set to True
The variable flag above controls the execution flow of the if statement. If flag is True, the first
branch executes; otherwise, the else branch executes.

Example 3: Using Boolean Variables to Track Conditions

The program above evaluates whether the sales variable meets a threshold. Depending on the
condition, the Boolean variable sales quota_met is set to True or False.

79
3.8 Review Questions
3.1 What is a control structure?
3.2 What is a decision structure?
3.3 What is a single alternative decision structure?
3.4 What is a Boolean expression?
3.5 What types of relationships between values can you test with relational
operators?
3.6 Write a pseudocode If-Then statement that assigns 0 to x if y is equal to 20.
3.7 Write a pseudocode If-Then statement that assigns 0.2 to commission if
sales is greater than or equal to 10,000.
3.8 How does a dual alternative decision structure work?
3.9 What statement do you use in pseudocode to write a dual alternative decision
structure?
3.10 When you write an If-Then-Else statement, under what circumstances do
the statements that appear between Else and End If execute?
3.11 If the following pseudocode were an actual program, what would it display?
If "z" < "a" Then
Display "z is less than a."
Else
Display "z is not less than a."
End If
3.12 If the following pseudocode were an actual program, what would it display?
Declare String s1 = "New York"
Declare String s2 = "Boston"
If s1 > s2 Then
Display s2
Display s1
Else
Display s1

80
Display s2
End If
3.13 How does a dual alternative decision structure work?
3.14 What statement do you use in pseudocode to write a dual alternative decision
structure?
3.15 When you write an If-Then-Else statement, under what circumstances do
the statements that appear between the Else clause and the End If clause
execute?
3.16 Convert the following pseudocode to an If-Then-Else If statement:
If number == 1 Then
Display "One"
Else
If number == 2 Then
Display "Two"
Else
If number == 3 Then
Display "Three"
Else
Display "Unknown"
End If
End If
End If
3.21 What is a compound Boolean expression?
3.22 The following truth table shows various combinations of the values true and
false connected by a logical operator. Complete the table by circling T or F to
indicate whether the result of such a combination is true or false.
Logical Expression Result (circle T or F)
True AND False TF
True AND True T F

81
False AND True T F
False AND False T F
True OR False T F
True OR True T F
False OR True T F
False OR False T F
NOT True T F
NOT False T F
3.23 Assume the variables a = 2, b = 4, and c = 6. Circle the T or F for each of the
following conditions to indicate whether its value is true or false.
a == 4 OR b > 2 T F
6 <= c AND a > 3 T F
1 != b AND c != 3 T F
a >= -1 OR a <= b T F
NOT (a > 2) T F
3.24 Explain how short-circuit evaluation works with the AND and OR operators.
3.25 Write an If-Then statement that displays the message “The number is valid”
if the variable speed is within the range 0 through 200.
3.26 Write an If-Then statement that displays the message “The number is not
valid” if the variable speed is outside the range 0 through 200.

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

82
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
88
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
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?

83
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:89
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.
• 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.

84
• 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.

85
Chapter Four: REPETITION STRUCTURES

LEARNING OUTCOMES
After reading this Section of the guide, the learner 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

4.2 Introduction to Repetition Structures

Repetition structures (also known as loops) allow you to execute a block of code multiple times.
There are two types of loops 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.

Condition-Controlled and Count-Controlled Loops

86
A true/false condition is used in a condition-controlled loop to limit how many times it iterates. A
count-controlled loop only loops back a predetermined number of times

4.3 The while Loop: a Condition-Controlled Loop


condition:

statement

statement etc

Figure 4-1: The logic of a while loop Source:


Gaddis (2021) Page 171

Example:
count = 0 while
count < 5:
print(count)
count+= 1

Output

87
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.

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.
10. The following example is found on page 172 of the prescribed textbook.

88
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

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

89
3

The above code will print the numbers 1 through 5 on separate lines.

Here is an explanation of this code:

4.5 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.

90
The 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

• 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.

for num in range(5):

print (num)

91
Output

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

Here is another example:

for num in range(5):

print(‘Dings’)

Output

Dings

Dings

Dings

92
Dings

Dings

The following program uses a loop to display a table showing the numbers 1 through 10 and

their squares.

# Print the table headings. print('Number\tSquare') print('------- ')

# 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

93
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?

• The range function generates a sequence of numbers from 1 to 10 (range(1, 11)).

• The for loop iterates over this sequence, with the loop variable number taking on each

value in turn.

• In each iteration, the loop calculates the square of number by raising it to the power of

2 (number**2), and stores the result in the square variable.

• Finally, the loop uses an f-string to print the number and its square, separated by a tab

(\t) character, on a single line.

Generating Lists that Range from Highest to Lowest

for num in range(5, 0, -1):

print (num)

Output

• 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).

94
• 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?

4.6 Calculating a Running Total


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.

95
• 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.

4.6.1 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

Source: Gaddis (2021) page 191

4.7 Sentinels

A sentinel in Python is a special value used to indicate a specific condition, such as the end of a

96
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.

# This program displays property taxes. TAX_FACTOR =

0.0065 # Represents the tax factor. # Get the first lot number.

print('Enter the property lot number or enter 0 to end.')

lot = int(input('Lot number: '))

# Continue processing as long as the user # does not enter

lot number 0.

while lot != 0:

# Get the property value. value = float(input('Enter the property value: '))

# Calculate the property's tax

tax = value * TAX_FACTOR

# Display the tax. print(f'Property tax: ${tax:,.2f}')

97
Get the next lot number.

print('Enter the next lot number or enter 0 to end.') 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

Research: How can you use a loop for input validation? Use an example of a relevant Python

program to explain this concept

4.8 Nested Loops


Nested loops in Python refers to the usage of one or more loops inside another loop. The inner
loop runs to completion for each iteration of the outer loop. This allows for the processing of a
series of elements in a series of nested iterations. The syntax for a nested loop in Python

is: for outer_loop_variable in outer_loop_iterable:

98
# code in the outer loop for inner_loop_variable in

inner_loop_iterable:

# code in the inner loop

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.

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

99
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 =

2i*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

100
Problem: Write a program that displays a rectangular pattern of asterisks and a triangle of
asterisks using nested loops

4.9 Review Questions


4.1 What is a repetition structure?

4.2 What is a condition-controlled loop?


101
4.3 What is a count-controlled loop?

4.4 What is a loop iteration?

4.5 What is the difference between a pretest loop and a posttest loop?

4.6 Does the While loop test its condition before or after it performs an iteration?

4.7 Does the Do-While loop test its condition before or after it performs an

iteration?

4.8 What is an infinite loop?

4.9 What is the difference between a Do-While loop and a Do-Until loop?

4.10 What is a counter variable?

4.11 What three actions do count-controlled loops typically perform using the

counter variable?

4.12 When you increment a variable, what are you doing? When you decrement a

variable, what are you doing?

4.13 Look at the following pseudocode. If it were a real program, what would it

display?

Declare Integer number = 5

Set number = number + 1

Display number

4.14 Look at the following pseudocode. If it were a real program, what would it

display?

Declare Integer counter

For counter = 1 To 5

102
Display counter

End For

4.15 Look at the following pseudocode. If it were a real program, what would it

display?

Declare Integer counter

For counter = 0 To 500 Step 100

Display counter

End For

4.16 Look at the following pseudocode. If it were a real program, what would it

display?

Declare Integer counter = 1

Constant Integer MAX = 8

While counter <= MAX

Display counter

Set counter = counter + 1

End While

4.17 Look at the following pseudocode. If it were a real program, what would it

display?

Declare Integer counter = 1

Constant Integer MAX = 7

While counter <= MAX

Display counter

103
Set counter = counter + 2

End While

4.18 Look at the following pseudocode. If it were a real program, what would it

display?

Declare Integer counter

Constant Integer MIN = 1

For counter = 5 To MIN Step –1

Display counter

End For

4.19 A program that calculates the total of a series of numbers typically has what

two elements?

4.20 What is an accumulator?

4.21 Should an accumulator be initialized to any specific value? Why or why not?

4.22 Look at the following pseudocode. If it were a real program, what would it

display?

Declare Integer number1 = 10, number2 = 5

Set number1 = number1 + number2

Display number1

Display number2

4.23 Look at the following pseudocode. If it were a real program, what would it

display?

Declare Integer counter, total = 0

104
For counter = 1 To 5

Set total = total + counter

End For

Display total

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

A c -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

105
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

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.

106
Algorithm Workbench

1. Design a While loop that lets the user enter a number. The number should be multiplied

by 10, and the result stored in a variable named product. The loop should

iterate as long as product contains a value less than 100.

2. Design a Do-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 whether

they wish to perform the operation again. If so, the loop should repeat; otherwise

it should terminate.

3. Design a For loop that displays the following set of numbers:

0, 10, 20, 30, 40, 50, . . . , 1000

4. Design a loop that asks the user to enter a number. The loop should iterate 10 times

and keep a running total of the numbers entered.

5. Design a For loop that calculates the total of the following series of numbers:

1+++___+

30

29

28

30

6. Design a nested loop that displays 10 rows of # characters. There should be 15 #

107
characters in each row.

7. Convert the While loop in the following code to a Do-While loop:

Declare Integer x = 1

While x > 0

Display "Enter a number."

Input x

End While

8. Convert the Do-While loop in the following code to a While loop:

Declare String sure

Do

Display "Are you sure you want to quit?"

Input sure

While sure != "Y" AND sure != "y"

9. Convert the following While loop to a For loop:

Declare Integer count = 0

While count < 50

Display "The count is ", count

Set count = count + 1

End While

10. Convert the following For loop to a While loop:

Declare Integer count

For count = 1 To 50

108
Display count

End For

Programming Exercises

1. Bug Collector

A bug collector collects bugs every day for seven days. Design a program that

keeps a running total of the number of bugs collected during the seven days. The

loop should ask for the number of bugs collected for each day, and when the loop

is finished, the program should display the total number of bugs collected.

2. Candy Factory

A machine at a candy factory can produce 80 chocolate bars per minute. Design

a program that uses a loop to display the number of chocolate bars the machine

can produce in 10, 15, 20, 25, and 30 minutes.

3. Budget Analysis

Design a program that asks the user to enter the amount they have to spend for a

month. A loop should then prompt the user to enter each expense for the month,

and keep a running total. When the loop finishes, the program should display the

amount that the user is over or under budget.

4. Sum of Numbers

Design a program with a loop that asks the user to enter a series of positive

numbers. The user should enter a negative number to signal the end of the series.

After all the positive numbers have been entered, the program should display

their sum.

109
5. Tuition Increase

At one college, the tuition for a full-time student is $6,000 per semester. It has

been announced that the tuition will increase by 2 percent each year for the next

five years. Design a program with a loop that displays the projected semester

tuition amount for the next five years.

6. Distance Traveled

The distance a vehicle travels can be calculated as follows:

Distance = Speed × Time

For example, if a train travels 40 miles per hour for three hours, the distance traveled

is 120 miles. Design a program that asks the user for the speed of a vehicle

(in miles per hour) and how many hours it has traveled. It should then use a loop

to display the distance the vehicle has traveled for each hour of that time period.

Here is an example of the output:

What is the speed of the vehicle in mph? 40 [Enter]

How many hours has it traveled? 3 [Enter]

Hour Distance Traveled

1 40

2 80

3 120

110
Chapter Five: FUNCTIONS

LEARNING OUTCOMES
After reading this Section of the guide, the learner 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.

5.1.1 Divide and Conquer

Divide and conquer is a popular algorithm design paradigm that involves breaking down a

problem into smaller, subproblems and solving each of them individually. The solutions of

111
the subproblems are then combined to solve the original problem. In Python, divide and

conquer algorithms can be implemented using functions

Figure 5-1 Using functions to divide and conquer a large task

Source: Gaddis(2021) page 220

the subproblems are then combined to solve the original problem. In Python, divide and

conquer algorithms can be implemented using functions.

Figure 5-1 Using functions to divide and conquer a large task

Source: Gaddis(2021) page 220

112
5. 1.2 Benefits of Using Functions

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.

Encapsulation: Functions allow for encapsulating implementation details and exposing

only the necessary information to the rest of the program, promoting modularity and

separation of concerns.

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.

5. 1.3 Defining and Calling a Function

Function Names

• No Python key words allowed

• Contains no spaces

• The first character must be an underscore (_) or one of the letters a through z.

• Use the letters a through z, A through Z, numerals 0 through 9, or underscore after the

first character.

113
• Characters in uppercase and lowercase are different.

Examples of good function names include get_pay, get_gross_amount, calculate_overtime,

print_receipt, and so on.

Defining and Calling a Function

In Python, you can define a function using the "def" keyword, followed by the function name

and a set of parentheses that may contain parameters.

def function_name(): #function header

statement

statement etc.

This is the basic syntax of a function in Python.

"function_name" is the name of the function, which should be descriptive and follow the

naming conventions for variables in Python (lowercase with words separated by

underscores).

• "statement" represents one or multiple lines of code that perform a specific

task. These statements are executed when the function is called.

• 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 "()"

114
Figure 5-2 The function definition and the function call

Source: Gaddis(2021) page 224

Indentation in Python

5.1.4 Void Function

A void function in Python is a function that does not return a value. It is defined using the def

keyword, followed by the function name and parameters, and concluded with the return

statement without any value or with the pass statement. A void function can perform

operations, print results, and change the state of its arguments, but it does not return a

115
value to be assigned to a variable or used as an expression.

Example of a void function:

Output

In this example, the greet function takes a parameter name and prints a greeting message using
it, but it does not return a value.

Here is an example of a program with two functions: main and message

Code

116
Output

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.

117
5.1.4 Pausing Execution Until the User Presses Enter

In Python, you can use the input function to cause a program to pause until the user presses

the Enter key.

input('Press Enter to see Step 1.')

This statement displays the prompt 'Press Enter to see Step 1.' and pauses until the user

presses the Enter key.

Using the pass Keyword


118
In Python, the pass keyword is used as a placeholder for code that has not been implemented

yet. It is also used when a statement is required syntactically but you do not want any

command to execute.

For example, consider the following code:. The pass keyword is ignored by the Python115

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?

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.

5.1.5 Local Variables

Variables declared inside a function are called local variables. They can only be accessed within
the function in which they are declared and are not accessible from outside the function.

Here's an example program to demonstrate the use of local variables in Python:

Code

119
Output

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.

5.2 Passing Arguments to Functions


An argument is any piece of data that is passed into a function when the function is called. A
parameter is a variable in a function definition that is used to receive values from the caller
of the function. When a function is called, the values passed as arguments are assigned to
the corresponding parameters in the function definition.

Example:

120
Code 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.

121
➢ The show_double function takes one argument, number, and multiplies it by 2 to get the
result.
➢ The show_double function then prints the result.
➢ Finally, the main function is executed, which triggers the execution of the show_double
➢ function.

5.2.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.

• Finally, the main function is executed, which triggers the execution of the show_double

function.

5.2.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.

5.2.2 Passing Multiple Arguments

Code Output

122
8

➢ The function calculate takes two parameters a and b, calculates their sum, and prints the
result.
➢ The main function calls calculate(3, 5), so a is 3 and b is 5.
➢ The sum of 3 and 5 is 8, and it gets printed when calculate is executed.

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.

Code Output

Default Arguments: These are the arguments that have a default value in the function

123
definition. If these arguments are not passed when the function is called, their default value
is used.
Example

Code Output

Think Point: What would be the effect of reversing the order of arguments passed to a function

when is it called?

For example,

Code Output

124
Code

125
Code

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

126
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.

5.2.3 Mixing Keyword Arguments with Positional Arguments

In Python, you can mix keyword arguments (also known as named arguments) with positional
arguments when calling a function. Keyword arguments are arguments that are passed to a
function by explicitly specifying the name of the argument and its value, while positional
arguments are passed to a function by their position in the argument list.

Example:

Code

Output

127
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)

Think Point: When are keyword arguments useful?

5.3 Global Variables and Global Constants

5.3.1 Global Variables

In Python, global variables are variables that are defined outside of any function and can be

accessed from anywhere in the code, including inside functions. Global variables are defined

using the global keyword. For example:

Code

128
5.3.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:

Code

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 aconvention
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:

129
Code

For the following reasons, limit the use of global variables:

➢ Debugging is challenging when using functions that depend on global variables.


➢ Functions that use global variables are usually dependent on those variables.
➢ A program is difficult to understand when it uses global variables.

5.3.3 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

Code

130
Code

➢ 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

131
➢ 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.

132
5.4 Review Questions
5.1 What is a function?

5.2 What is meant by the phrase “divide and conquer”?

5.3 How do modules help you reuse code in a program?

5.6 In most languages, a module definition has what two parts?

5.7 What does the phrase “calling a module” mean?

5.8 When a module is executing, what happens when the end of the module is

reached?

5.9 Describe the steps involved in the top-down design process.

5.10 What is a local variable? How is access to a local variable restricted?

5.11 What is a variable’s scope?

5.12 Is it usually permissible to have more than one variable with the same name in

the same scope? Why or why not?

5.13 Is it usually permissible for a local variable in one module to have the same

name as a local variable in a different module?

5.14 What are the pieces of data that are passed into a module called?

5.15 What are the variables that receive pieces of data in a module called?

5.16 Does it usually matter whether an argument’s data type is different from the

data type of the parameter that it is being passed to?

5.17 Typically, what is a parameter variable’s scope?

5.18 Explain the difference between passing by value and passing by reference.

133
Multiple Choice

1. A group of statements that exist within a program for the purpose of performing a

specific task is a(n) __________.

a. block

b. parameter

c. module

d. expression

2. A benefit of using modules that helps to reduce the duplication of code within a

program is __________.

a. code reuse

b. divide and conquer

c. debugging

d. facilitation of teamwork

3. The first line of a module definition is known as the __________.

a. body

b. introduction

c. initialization

d. header

4. You __________ the module to execute it.

a. define

b. call

c. import

134
d. export

5. A __________ point is the memory address of the location in the program that the

computer will return to when a module ends.

a. termination

b. module definition

c. return

d. reference

6. A design technique that programmers use to break down an algorithm into modules

is known as __________.

a. top-down design

b. code simplification

c. code refactoring

d. hierarchical subtasking

7. A __________ is a diagram that gives a visual representation of the relationships

between modules in a program.

a. flowchart

b. module relationship chart

c. symbol chart

d. hierarchy chart

4. A variable that is visible to every function in a program file is a .

135
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:
my_function(3, 2, 1)

136
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.

137
Chapter Six: 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

6.2 Types of Files


There are two main types of files: text and binary.

138
Text files: These are files that contain text data, such as a plain text file, a CSV file, or a JSON file.
Text files can be opened and read using the built-in open function in Python, and the contents
can be processed using string methods

Binary files: These are files that contain binary data, such as an image, audio, or video file. Binary
files can be opened and read using the built-in open function, but the contents must be processed
using binary methods, such as reading and writing bytes.

6.3 File Access Methods


File access methods refer to the way in which data is retrieved from a file stored on a storage

device, such as a hard drive or an SSD. There are two main types of file access methods: sequential
and direct.

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

139
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.

6.4 Opening a File


It takes the file name and mode (read, write, or append) as arguments, and returns a file object
that you can use to read or write the file.

The open function:

General format:

file_variable = open(filename, mode)

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.)

Table 6-1 Some of the Python file modes

Source: Gaddis (2021) page 307

Examples of statements used for opening a file.

customer_file = open(‘customers.txt’, ‘r’)

140
The code creates a file object for the file customers.txt in read mode ('r'). The open function is
used to open a file in Python, and it takes two arguments: the name of the file, and the mode in
which the file should be opened. In this case, the mode is 'r', which stands for "read." The open
function returns a file object, which can be used to access the contents of the file.

Here is another example:

sales_file = open(‘sales.txt’, ‘w’)

6.5 Opening a File


Writing to a file: To write to a file, you open it in write mode ("w") or append mode ("a"). In write
mode, the contents of the file are overwritten, while in append mode, new data is added to the
end of the file. Here's an example that writes a string to a file in write mode:

For example:

file = open("example.txt", "w")

file.write("This is some data.")

file.close()

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.

6.6 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("example.txt", "r")

141
contents = file.read()

print(contents)

file.close()

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.

• The initial read position is at the beginning of the file.


• When you call the readline method on the file object for the first time, the read position
advances to the end of the first line. In other words, the read position is now at the
beginning of the second line.
• When you call the readline method again, the read position advances to the end of the
second line, and so on, until you reach the end of the file.
• This way, the read position keeps advancing to the next line each time the readline
method called, allowing you to read the contents of the file line by line.

6.7 Closing a file


It is important to close a file after you are done with it to free up resources. You can do this by
calling the close method of the file object. 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

142
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")

# Write some text to the file


file.write("This is line 1.\n")
file.write("This is line 2.\n")
file.write("This is line 3.\n")
# Close the file file.close()

# Open the file in read mode

file = open("example.txt", "r")

# Read and print the contents of the file

contents = file.read()

print(contents)

# Close the file

file.close()

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 the contents to

143
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")

# Write some text to the file


file.write("This is line 1.\n")
file.write("This is line 2.\n")
file.write("This is line 3.\n")
# Close the file
file.close()

# Open the file in read mode

file = open("example.txt", "r")

# Read and print the contents of the file, line by line

line = file.readline() # read first line

line = file.readline() # read second line

line = file.readline() # read third line

# Close the file


file.close()

144
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")

# Write some text to the file

file.write("This is line 1.\n")

file.write("This is line 2.\n")

file.write("This is line 3.\n")

# Close the file

file.close()

# Open the file in read mode

file = open("example.txt", "r")

# Read and print the contents of the file, line by line

line = file.readline()

while line:

print(line)

line= file.readline()

# Close the file

file.close()

145
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 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.

6.8 Concatenating a Newline to a String


In Python, you can concatenate a newline character to a string using the string literal \n.
Forexample:

string = "This is a string" string_with_newline = string + "\n" print(string_with_newline)

Output

This is a string

Reading a String and Stripping the Newline From It

You can strip the newline character from the end of a string using the strip method. For example:

string_with_newline = "This is a string\n"

stripped_string = string_with_newline.strip()

print(stripped_string)

146
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.

string_with_newline = "This is a string\n"

stripped_string = string_with_newline.rstrip("\n")

print(stripped_string)

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.

Here is another example:

# This program reads the contents of the #

philosophers.txt file one line at a time.

def main():

# Open a file named philosophers.txt.

infile = open('philosophers.txt', 'r')

147
# Read three lines from the file

line1 = infile.readline()

line2 = infile.readline()

line3 = infile.readline()

# Strip the \n from each string.

line1 = line1.rstrip('\n')

line2 = line2.rstrip('\n')

line3 = line3.rstrip('\n')

# Close the file. infile.close()

# Print the data that was read into memory.

print(line1)

print(line2)

print(line3)

# Call the main function. if _ _name_ _

== '_ _main_ _':

main()

Output

John Locke

David Hume

Edmund Burke

148
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.

6.9 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')

# Verify that the data was written to the file with open('file.txt', 'r') as

f:

149
print(f.read())

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.

6.10 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.

outfile.write(str(num1) + ‘\n’)

infile = open(‘number.txt’, ‘r’) # readline

method reads strings

string_input = infile.readline()

# built-in function int converts string to an integer

value = int(string_input)

150
Figure 6-1 The numbers.txt file viewed in Notepad

Here is another example: # Open the file for reading with

open('numbers.txt', 'r') as file: # Read the first line from

the file line1 = file.readline() # Read the second line

from the file line2 = file.readline() # Read the third line

from the file line3 = file.readline()

# Strip the newline character from each line

line1 = line1.rstrip('\n')

line2 = line2.rstrip('\n')

line3 = line3.rstrip('\n')

# Convert each line to a numeric value

number1 = float(line1)

151
number2 = float(line2)

number3 = float(line3)

# Add the numbers together

sum = number1+ number2 + number3

# Print the sum of the numbers

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.11 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.

152
Figure 6-2 General logic for detecting the end of a file Using Python’s for Loop to Read Lines

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.

for variable in file_object:

statement

statement etc.

Example:

# Open the file for reading with

open('numbers.txt', 'r') as file:

# Initialize a variable to keep track of the sum

sum = 0

# Loop over each line in the file

for line in file:

# Strip the newline character from the line

153
line = line.rstrip('\n')

# Convert the line to a numeric value

number = float(line)

# Add the number to the sum


sum += number
#Print the sum of the numbers
print('The sum of the numbers is:', sum)

• 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.

154
6.12 Review Questions
6.1 Where are files normally stored?

6.2 What is an output file?

6.3 What is an input file?

6.4 What three steps must be taken by a program when it uses a file?

6.5 In general, what are the two types of files? What is the difference between

these two types of files?

6.6 What are the two types of file access? What is the difference between these two?

6.7 When writing a program that performs an operation on a file, what two file associated

names do you have to work with in your code?

6.8 In most programming languages, if a file already exists what happens to it if

you try to open it as an output file?

6.9 What is the purpose of opening a file?

6.10 What is the purpose of closing a file?

6.11 Generally speaking, what is a delimiter? How are delimiters typically used in

files?

6.12 In many systems, what is written at the end of a file?

6.13 What is a file’s read position? Initially, where is the read position when an

input file is opened?

6.14 In what mode do you open a file if you want to write data to it, but you do not

want to erase the file’s existing contents? When you write data to such a file, to

what part of the file is the data written?

Multiple Choice

155
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

156
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

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 names.txt 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

157
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.

158
References
Gaddis, T. (2021). Starting out with Python. 5th Global Ed. United Kingdom: Pearson

Education. ISBN: 9781292408637

Matthes, E. (2021) Python Crash Course: A Hands-On, Project-Based Introduction to Programming. 3rd
ed. No Starch Press.

Zelle, J. (2022) Python Programming: An Introduction to Computer Science. 4th ed. Franklin, Beedle &
Associates.

Severance, C.R. (2021) Python for Everybody: Exploring Data in Python 3. 2nd ed. CreateSpace
Independent Publishing Platform.

Sweigart, A. (2023) Beyond the Basic Stuff with Python: Best Practices for Writing Clean Code. 1st ed. No
Starch Press.

Saha, D. (2022) Python Programming and Numerical Methods: A Guide for Engineers and Scientists. 1st
ed. Academic Press.

Gupta, S. and Chopra, R. (2021) Core Python Programming. 3rd ed. BPB Publications.

Shaw, Z.A. (2020) Learn Python 3 the Hard Way: A Very Simple Introduction to the Terrifyingly Beautiful
World of Computers and Code. 1st ed. Addison-Wesley.

Maruch, S. and Maruch, D. (2021) Python Programming for Beginners. 1st ed. Wiley.

Bader, D. (2021) Python Tricks: A Buffet of Awesome Python Features. 2nd ed. Addison-Wesley
Professional.

Summerfield, M. (2020) Programming in Python 3: A Complete Introduction to the Python Language. 2nd
ed. Addison-Wesley.

Guttag, J. (2021) Introduction to Computation and Programming Using Python: With Application to
Computational Modeling and Understanding Data. 3rd ed. MIT Press.

Beazley, D.M. and Jones, B.K. (2021) Python Cookbook: Recipes for Mastering Python 3. 3rd ed. O'Reilly
Media.

159
Moore, M. (2021) Mastering GUI Programming with Python: Develop Impressive Cross-Platform GUI
Applications with PyQt. 2nd ed. Packt Publishing.

Wood, A. (2022) Python for Data Analysis: Data Wrangling with Pandas, NumPy, and SQL. 2nd ed.
O'Reilly Media.

Python.org. (2019). The Python Tutorial — Python 3.8.0 documentation. [online] Available

at: https://docs.python.org/3/tutorial/.

160
Programming 511 is a prerequisite for Programming 512 in the second semester, Programming
511 ensures that students acquire the foundational knowledge and skills needed to advance to
more complex programming concepts. By mastering the fundamentals in this module, students
are well-prepared to deepen their expertise in Python and explore advanced topics, enabling
them to develop more efficient, robust, and practical software solutions as they progress in their
academic journey.

In your second year, you will embark on a journey of learning other programming languages and
technologies, including C++ and optionally Internet Programming, which blends PHP, HTML, CSS,
and SQL. In addition, you will engage with other specialized modules such as Networks, and
Business Management etc broadening your skill set and preparing you for the demands of the
industry.

The IT qualification at Richfield College stands as a beacon of academic innovation and


professional readiness. It equips students with the skills and credentials necessary for thriving in
the IT industry. By combining foundational knowledge, practical expertise, and global recognition,
the program not only prepares students for immediate employment but also sets them on a
trajectory for long-term career success.

161

You might also like