Programming 511 Study Guide
Programming 511 Study Guide
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
LEARNER GUIDE
PREPARED ON BEHALF OF
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 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:
1.1 Introduction
The first section of this topic provides an insight into the functioning of computers, data storage
and manipulation, and the rationale behind using high-level languages for programming. Key
concepts such as Python programming, interactive and script modes, and the IDLE (Integrated
Development and Learning Environment) are introduced.
Computers are integral to our daily lives, found in various forms such as desktops, laptops,
smartphones, and embedded systems in appliances and vehicles. Their versatility stems from the
ability to be programmed to perform a myriad of tasks. At the core, a computer is a machine that
processes data and executes instructions.
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.
High-level languages offer several key advantages that make them a preferred choice for
programming:
2. Easier Debugging and Maintenance: With a simplified structure and comprehensive error
messages, these languages enable quicker identification and resolution of issues.
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
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”.
6
Figure 1.2 Typical components of a computer system (Gaddis, 2021)
7
Figure 1-3 The ENIAC computer (Gaddis, 2021)
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.
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?
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
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.
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 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.
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.
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
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 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 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.
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.
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.
An interpreter is a program that both translates and executes the instructions in a high-level
language program.
16
Figure 1-12 SPYDER IDLE
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
➢ This involves comprehending the program's purpose, often derived from client
requirements.
Example of Pseudocode
26
I. Input the hours worked.
27
Common Flowchart Symbols
Flowchart
Steps Pseudocode
Start Start
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.
➢ 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.
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:
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.
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.
➢ Case-sensitive.
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.
o After the first character, variable names can contain any combination of letters, digits,
or underscores.
• Digits (0-9)
• Underscores (_)
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.
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
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:
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
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
➢ 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.
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
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.
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.
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.
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).
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).
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.
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.
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'>.
programs.
Think Point:
value1 = 99
value2 = 45.9
42
value3 = 7.0
value4 = 7
value5 = 'abc'
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.
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
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:
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
print(c) # Output: 8
% is the remainder operator. Its purpose is to perform division and return the remainder.
48
2.8.10 Data Type Conversion
➢ 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.
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
x = -12.9
49
y = int(x) # y will be assigned -12
y=7
In Python, statements can be broken down into multiple lines by using the line continuation
character ( \ ).
For example:
var1 = 1 var2 = 2
var3 = 3 var4 = 4
print(result)
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
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:
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)
Here's an example:
Output
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
For example:
Output
1, 2, 3
1. Concatenation:
You can concatenate strings using the + operator, and you can convert non- string values to strings
using the str function.
52
Output
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
Output
3. Using f-strings: You can also use f-strings, which are a more recent way to format strings
Code Output
53
My name is John Doe and I am 30 years old.
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.
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
57
Output
In this example, the named constant PI is used in the calculation of the area of a circle. The value
of PI is not expected to change, so it is created as a named constant. The radius is given a value
of 5 and the area of the circle is calculated using the formula PI * (radius**2). The result is then
printed to the console
Think point: Despite named constants being mutable, why is it important to use them
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?
Input temperature
2.18 What two steps usually take place when a program prompts the user for input?
2.21 When you assign a value to a variable, what happens to any value that is
59
2.22 Summarize the mathematical order of operations, as it works in most programming
languages.
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.32 What are the two general types of comments that programmers write in a
1.A error does not prevent the program from running, but causes it
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
b. *
c. **
d. #
a. x = 17
b. 17 = x
c. x = 99999
d. x = '17'
a. int_to_float()
b. float ()
c. convert ()
d. int()
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:
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
A car is traveling at 70 miles per hour. Write a program that displays the following:
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:
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.
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:
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)
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
Example:
Syntax Example
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.
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.
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.
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.
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:
74
The and Operator
Output:
Both conditions are True
In this example:
• 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.
76
Output:
The temperature is in
the danger zone.
• minutes > 12 is True. Both conditions being true cause the if block to execute.
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.
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.
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.
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.
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:
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
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.
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
statement
statement etc
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.
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.
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
Statement
statement etc.
print (num)
Output
89
3
The above code will print the numbers 1 through 5 on separate lines.
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:
print (num)
Output
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.
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:
print(num)
Output
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.
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 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
• Finally, the loop uses an f-string to print the number and its square, separated by a tab
print (num)
Output
• The range function generates a sequence of numbers from 5 to 1 (range(5, 0, -1)), counting
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?
and updating it in each iteration of the loop. Typically, two components are used in programs
running_total += number
• 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.
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
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.
0.0065 # Represents the tax factor. # Get the first lot number.
lot number 0.
while lot != 0:
# Get the property value. value = float(input('Enter the property value: '))
97
Get the next lot number.
print('Enter the next lot number or enter 0 to end.') lot = int(input('Lot number: '))
Output
$32.50.
Lot number: 0
Research: How can you use a loop for input validation? Use an example of a relevant Python
98
# code in the outer loop for inner_loop_variable in
inner_loop_iterable:
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:
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.
loop: j = 1 i * j = 1 inner
loop: j = 2 i * j = 2
...
inner loop: j = 10 i * j = 10
= 1 i * j = 2 inner loop: j =
2i*j=4
...
inner loop: j = 10 i * j = 20
...
loop: j = 1 i * j = 10 inner
loop: j = 2 i * j = 20
...
100
Problem: Write a program that displays a rectangular pattern of asterisks and a triangle of
asterisks using nested loops
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.9 What is the difference between a Do-While loop and a Do-Until loop?
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
4.13 Look at the following pseudocode. If it were a real program, what would it
display?
Display number
4.14 Look at the following pseudocode. If it were a real program, what would it
display?
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?
Display counter
End For
4.16 Look at the following pseudocode. If it were a real program, what would it
display?
Display counter
End While
4.17 Look at the following pseudocode. If it were a real program, what would it
display?
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?
Display counter
End For
4.19 A program that calculates the total of a series of numbers typically has what
two elements?
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?
Display number1
Display number2
4.23 Look at the following pseudocode. If it were a real program, what would it
display?
104
For counter = 1 To 5
End For
Display total
Multiple Choice
that it repeats.
a. Boolean
b. condition
c. decision
d.count
a. Boolean
b. condition
c. decision
d. count
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
a. error traps
b. doomsday loops
d. defensive loops
7. True/False
To calculate the total number of iterations of a nested loop, add the number of iterations of
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
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
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.
4. Design a loop that asks the user to enter a number. The loop should iterate 10 times
5. Design a For loop that calculates the total of the following series of numbers:
1+++___+
30
29
28
30
107
characters in each row.
Declare Integer x = 1
While x > 0
Input x
End While
Do
Input sure
End While
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
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
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
6. Distance Traveled
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.
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:
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.
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
the subproblems are then combined to solve the original problem. In Python, divide and
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.
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
Function Names
• 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.
In Python, you can define a function using the "def" keyword, followed by the function name
statement
statement etc.
"function_name" is the name of the function, which should be descriptive and follow the
underscores).
• 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
114
Figure 5-2 The function definition and the function call
Indentation in Python
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.
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.
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
This statement displays the prompt 'Press Enter to see Step 1.' and pauses until the user
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
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.
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.
Code
119
Output
As you can see, the local variable local_variable is defined inside both functions first_function
and second_function.
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.
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.
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
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
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.
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
Problem: Explain whether the following function call will cause an error for the above
program:
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
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
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
A value-returning function in Python is a function that returns a value to the caller. The return
def function_name():
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.8 When a module is executing, what happens when the end of the module is
reached?
5.12 Is it usually permissible to have more than one variable with the same name in
5.13 Is it usually permissible for a local variable in one module to have the same
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
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
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
c. debugging
d. facilitation of teamwork
a. body
b. introduction
c. initialization
d. header
a. define
b. call
c. import
134
d. export
5. A __________ point is the memory address of the location in the program that the
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
a. flowchart
c. symbol chart
d. hierarchy chart
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
137
Chapter Six: FILES
LEARNING OUTCOMES
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
• Retrieving data from a file = “reading data from” the file Input file = file
that data is read from
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.
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.
General format:
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
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.
For example:
file.close()
File_variable.write(string)
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.
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:
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:
contents = file.read()
print(contents)
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
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:
file.close()
line = file.readline()
while line:
print(line)
line= file.readline()
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.
Output
This is a string
You can strip the newline character from the end of a string using the strip method. For example:
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.
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.
def main():
147
# Read three lines from the file
line1 = infile.readline()
line2 = infile.readline()
line3 = infile.readline()
line1 = line1.rstrip('\n')
line2 = line2.rstrip('\n')
line3 = line3.rstrip('\n')
print(line1)
print(line2)
print(line3)
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.
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('file.txt', 'a') as f:
# 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.
outfile.write(str(num1) + ‘\n’)
string_input = infile.readline()
value = int(string_input)
150
Figure 6-1 The numbers.txt file viewed in Notepad
line1 = line1.rstrip('\n')
line2 = line2.rstrip('\n')
line3 = line3.rstrip('\n')
number1 = float(line1)
151
number2 = float(line2)
number3 = float(line3)
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.
statement
statement etc.
Example:
sum = 0
153
line = line.rstrip('\n')
number = float(line)
• 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.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
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
6.11 Generally speaking, what is a delimiter? How are delimiters typically used in
files?
6.13 What is a file’s read position? Initially, where is the read position when an
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
Multiple Choice
155
1. A file that data is read from is known as a(n) .
a. input file
b. output file
d. binary file
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
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
158
References
Gaddis, T. (2021). Starting out with Python. 5th Global Ed. United Kingdom: Pearson
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.
161