0% found this document useful (0 votes)
392 views135 pages

Computer Programming Manual v3.5 28082020 (For Instructional Purposes Only)

Uploaded by

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

Computer Programming Manual v3.5 28082020 (For Instructional Purposes Only)

Uploaded by

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

COMPUTER FUNDAMENTALS

&
PROGRAMMING (Using Python)

Engr. Darcy Roy G. Francisco


Engr. Marinella T. Tose

COLLEGE OF ENGINEERING

1|Page
Computer Fundamentals and Programming Using Python

WESTERN MINDANAO STATE UNIVERSITY


Copyright © by Western Mindanao State
University All rights reserved. Published 2020
Printed in the
Philippines ISBN
No part of this publication may be reproduced or
distributed in any form or by any means, or stored in a
database or retrieval system, without
prior written permission of WESTERN
MINDANAO STATE UNIVERSITY

This version of the module we dedicate in memory


of a great mentor, Dr. Cielito Conti-Olegario,
who taught us the bits and bytes of Computer Engineering and of life.

2 |Page
Computer Fundamentals and Programming Using Python

Contents
BACKGROUND OF THE MODULE (What is the module about?)............................6
COURSE MODULE OUTCOMES...............................................................................7
I. Introduction to Computer System and Organization........................................8
What is a Computer?...................................................................................................9
Types of Computers...................................................................................................10
Features of a Computers...........................................................................................11
Computer Hardware and Software..........................................................................12
Computer System Organization...............................................................................14
Main Components of a Computer System.............................................................16
Computer Number System and its Types...............................................................23
Number System Conversions..................................................................................26
Arithmetic Operation................................................................................................30
II. Application Software and the Internet.............................................................36
Application Software..................................................................................................38
Word Processing Software.......................................................................................40
Spreadsheet Software...............................................................................................42
The Internet.................................................................................................................44
Communication over the Internet...........................................................................44
Exploring the Internet...............................................................................................46
Societal Issues and the Future of the Internet.......................................................47
II. Introduction to Computer Programming..........................................................50
What is Computer Programming?...........................................................................52
Process of Program Design.......................................................................................55
III. Introduction to Algorithm Analysis and Design.............................................57
Designing Algorithms using Pseudocodes............................................................59
Designing Algorithms using Flowcharts..................................................................61
IV. Introduction to Python Programming Language............................................66
Programming Using Python.....................................................................................67
Basic Programming Terms........................................................................................69
Programming Exercises 1..........................................................................................70
Programming Exercises 2..........................................................................................70
V. Python Basics..........................................................................................................72
3 |Page
Computer Fundamentals and Programming Using Python

Programming Exercises 3..........................................................................................80


Programming Exercises 4..........................................................................................81
Programming Exercises 5..........................................................................................82
Variable Initializations and Constants......................................................................83
Programming Exercises 6..........................................................................................85
Programming Exercises 7..........................................................................................87
Arithmetic Expressions and more Assignment Statements..................................89
Programming Exercises 9..........................................................................................92
Programming Exercises 10........................................................................................93
Programming Exercises 11........................................................................................94
VI. CONTROL STRUCTURES (SELECTION)...............................................................95
If statement.................................................................................................................98
Programming Exercise 12.......................................................................................101
Programming Exercise 13.......................................................................................101
Programming Exercise 14.......................................................................................105
Programming Exercise 15.......................................................................................105
Nested if...else statement (if... elif.... else Statement)......................................106
Programming Exercise 16.......................................................................................108
VII. Repetitive Control Structures........................................................................110
Algorithm Exercises 4..........................................................................................114
WHILE LOOP STATEMENT.......................................................................................116
Program Simulation.................................................................................................118
Programming Exercises 17......................................................................................118
FOR LOOP STATEMENT...........................................................................................119
Programming Exercise 18.......................................................................................122
Programming Exercises 21......................................................................................125
Parameters and arguments.....................................................................................129
Sample program output..........................................................................................131
Programming Exercises 22......................................................................................131
Programming Exercises 23......................................................................................133
Programming Exercises 24......................................................................................134
Bibliography...............................................................................................................135

4|Page
Computer Fundamentals and Programming Using Python

BACKGROUND OF THE MODULE (What is the module about?)

Welcome to your first computer class! This subject will provide you with the basic
knowledge on computer concepts as well as develop your skills in basic computer programming.
This will also help you understand the technology better and its use in the society and in the
profession of your choice.

The basic knowledge and skills in computer technology and computer programming has
become one of the vital roles in creating competitive leaders of society. The society itself has
transformed to adapt to the changes in technology. One of such recent developments in
technology is the use of the social networking media such as Facebook, Twitter, Instagram, and
others. Now, you are able to interact and collaborate with other individuals despite the cultural
differences and geographical distances.

The skills and knowledge in the use of this technology will not only help you communicate
better amongst your social circle but will also help you professionally in the future. The business
and professional industry have incorporated technology into their processes. Technology in the
industry has helped create a more productive and efficient environment. These fields in the
industry will need people like you who are capable and skilled to manage their processes with the
use of technology.

Moreover, the skills that you will gain in computer programming will place you one step
ahead over your peers in the industry. As future engineering graduates of WMSU, you will not only
be users of technology but you can also be one of the creators and developers of future
innovations in technology. Instead of using apps in Facebook, you can be the one to create such
apps where people might use in their work or just purely entertainment. But most importantly, you
will be able to innovate solutions that will contribute and address to societal needs.

This subject will build the foundation of your basic computer technology knowledge and
programming skills. This module, as part of the subject, will be your guide throughout the topics
and exercises that will be covered for this semester. For each section, you will be provided with a
list of topics and objectives. Make sure that at the end each section, you are able to meet the
objectives through the exercises given. This will help you be ready for the succeeding topics. Your
instructor will also facilitate your learning throughout the entire subject.

So, enjoy and have fun learning!

5|Page
Computer Fundamentals and Programming Using Python

COURSE MODULE OUTCOMES

At the end of this course, the student must be able to:

1. Understand basic information technology concepts;


2. Use application software and the Internet properly;
3. Acquire proficiency in algorithm development using high-level programming language;
4. Use high-level language and programming applicatons in solving engineering problems.

For each of the topic section in this course module, objectives are identified aligning with the above
outcomes.

6|Page
Computer Fundamentals and Programming Using Python

I. Introduction to Computer System and Organization

Concept of a Computer
System

Computers, nowadays, have become a common device at work, school and at home. You might
already have a general knowledge of what a computer is. But have you ever used a computer? If
you answered yes, that’s great! You have a good start. If you answered no, do not worry. You
might not know it yet, but maybe all along you already have a computer right at your fingertips!

One of the most popular innovations that man has ever built is the computer. You might have
watched a movie or a show in TV where robots walk around like humans? Or maybe humans
almost like robots? Think of Iron Man! Well, in reality, there are already robots developed, and
through Artificial Intelligence, soon it will probably think and act like us. For now, it is only limited
to the imagination of the movie creators of what a possible future will be like. But you will never
know. Some of the technology that we have now, like your mobile phone, used to only be a
possible future decades or centuries ago.

The robots might be so advanced, but its development comes from the same basic concept of
computer technology that we have now. From the personal desktop computers, the computer
technology has evolved to a lot of other innovations like laptops, mobile phones, smart phones,
tablets, and the like. These innovations in technology have made most of humans’ work easier and
definitely, faster!

Objectives:

At the end of this section, you should be able to:


1. define a computer system and organization;
2. explain the types and features of a computer;
3. identify and differentiate one computer component from another;
4. Identify different number system; and
5. convert values between base number system.

Topic Outline:
I. Introduction to Computer System Organization
a. Concept of a Computer System
b. Computer Hardware and Software
c. Components of a Computer System
II. Data representation and Number System
a. Types on number system
b. Conversion between number systems
c. Number Systems Arithmetic Operations

7|Page
Computer Fundamentals and Programming Using Python

Try This!

Do you currently have a computer? A mobile phone? Now, take a look around your home and list down all the gadge

Think Ahead!

Consider the gadgets or appliance below and identify if it is a computer or not. Write a check (✔)
on the appropriate column.

Items A Computer Not a Computer


Smart Phone
Laptop
Tablet
Scientific Calculator
Television
Watch

Read and Ponder!

The use of electronic devices has greatly affected how people do their tasks. You might know how
to compute using pen and paper, but the calculator makes it easier to compute bigger numbers
and faster. You might go to a friend’s house and tell him/her the latest news but text messaging or
calling using mobile phones makes it more convenient. Any employees in a company can create
their documents and store it manually in a cabinet somewhere but the creation, editing, and
retrieval using a personal computer not only makes it faster, it also makes management of files
hassle-free and almost error-free.

What is a Computer?

So, what exactly is a computer? A computer is a collection of electronic devices operating under a
set of instructions stored in its own memory. It accepts data (Input), manipulates the data
(Process), and outputs its results (Output), and stores these results for future use (Storage)
(Discovering Computers, 2002).

8 |Page
Computer Fundamentals and Programming Using Python

Figure 1.2 below illustrates these general tasks of a computer. The arrow between process and
storage means that results can be directly stored by the computer without displaying it to the user.
Just think of IPOS, i.e. Input, Process, Output, and Storage.

Accepts data
Process data to Produces results Store results
produce
Data are raw information Results may be a Results are
facts in a form
display on the stored in the
of text, sound,
Information is a screen, a sound computer’s own
image, or video
processed data from the memory or a
that is speakers, or a separate storage
meaningful to the hardcopy from device like your
user (such as the printer. thumb drives.
reports)

INPUT PROCESS OUTPUT STORAGE

Figure 1.1 IPOS: Tasks of a Computer

In the simplest sense, a calculator as well as a mobile phone may be considered as a simple
computer. You enter your data into the keypad, the device will process your data, and a result will
be displayed in the small screen. For some calculators, you can even save your previous
computations. Just exactly what we have mentioned before, computers at your own fingertips!

However, the term “computer” is now commonly associated with desktop or personal computers
(PC). With this, you can enter data in different formats such as texts, images, sounds, or videos… it
can process large amount of data… it can display outputs in different formats as well… and it can
store up huge data from megabytes (MB), to gigabytes (GB), to terabytes (TB). Some of the new
generation computers have also same capabilities or even better but comes in small packages like
laptops and tablets.

Types of Computers

In general, computers can come in different sizes depending on its specifications. It could come in
a form of a wristwatch or as big as the size of the classrooms or maybe even as big as a building. It
could also be used for different purposes. We could use PCs for personal use or supercomputers
for big science research.

Computers can be categorized based their operation and specifications. Specifications include its
size, speed of its computations, and the storage capacity. Figure 1.3 below shows the different
categories or types of computers.
COMPUTERS

Analog Digital Hybrid

Mainframe Computers
Super Computers Mini Computers MicroComputers

9 |Page
Computer Fundamentals and Programming Using Python

Figure 1.3 Types of Computers adopted from Computer Basics Guide (2009)

The following are the different types of computers (Fabien, 1999; HubPages, 2013;
Computers Basic Guide, 2009):

• Analog Computers – These are computing devices that use analog signals that are
represented a continuous range of values. It generally deals with physical variables such
as voltage, pressure, temperature, speed, etc. You can see some of these devices at
research institutes, hospitals, and flight centers.

• Digital Computers – These are computing devices that use electrical inputs, ON or OFF.
With these devices data are represented by 0s (OFF) and 1s (ON). Digital computers can get
more accurate and faster results. It is best suited for solving complex problems in
engineering and technology. The most popular example of this type of computer is PC.
▪ Super Computers – These computers are the best, in terms of processing capacity,
which means it is the fastest type of computer available. It can process about billions
of instructions per second. However, this is also the most expensive. These are
mainly used for complex scientific simulations and calculations like nuclear energy r,
stock analysis, and weather forecasting.
▪ Mainframe Computers – These computers are also considered high-speed
computers which can process about millions of instructions per second. Just like a
super computer, it is also expensive. It is mainly used for the applications in banking,
airlines, and railways.
▪ Mini Computers – These computers have lower speed than mainframes and also
less expensive. Sometimes it is considered as a small-scale mainframe. In general, it
is also capable of supporting multiprocessing system for about 200 users. It is mostly
used as servers some major business applications.
▪ Micro Computers – These are the most common type of computers used today. The
invention of single chip processors (CPU) creates cheaper but powerful
microcomputers. The most widely used amongst microcomputers are the desktop
computers or PC. Other devices such as laptops, handheld devices like tablets and
personal data assistants (PDA) also belong to this type.

• Hybrid Computers – These computers are very unique because they combine the
operations of analog and digital computers. They operate by using digital-to-analog
converter and analog-to-digital converter that will transform the data into a more suitable
form for either type of computation. These devices are mainly used for specialized task. An
example of this is the hospital’s ICU. The device measures the patient’s temperature, blood
pressure, and other vital signs. These data are converted into numbers using the digital
components of the device so that medical personnel will be able to monitor the values and
be able to send signal if there are abnormal values.

Features of a Computers

In whichever type, size, or configuration the computers may be, there’s no doubt that it is able to
make some complicated tasks simple. In general, it makes most of human’s tasks faster than any
other tool available. In the previous activity, you have list down some of the advantages that the
use of computers have contributed into our daily lives. Here are some of the features that made all
these advantages possible:
• Speed – As we have already mentioned before, computers works at a very high speed. We
are talking thousand (milliseconds), millions (microseconds), and billions (nanoseconds) of
instructions per second. Technically, it can read a book in a bat of an eyelash.

10 | P a g e
Computer Fundamentals and Programming Using Python

• Accuracy – Not only are computers fast, it is also accurate, not unless the user (you) gives a
wrong data or instruction. In this sense, computers are 100% accurate.
• Consistency – Unlike humans, computers can work efficiently continuously for many hours
without taking a rest. It also maintains its speed and accuracy. As long as it has power, it will
not stop working out of tiredness or fatigue.
• Versatile – Computers can do a variety of tasks from complex science simulations to simple
computations like playing your favourite games. It is used in variety of fields and industry.
• Storage – Computer can store large amount of data. Imagine the stacks of files and
documents in the office cabinets. The entire files and documents in your office can be
stored in a single flash drive which you can carry with you in your packets.
• Reliability – Since computers works fast, accurate, and consistent, you data and other works
may be easily assessable for future use. You can be assured that it will be available for you
when you need it.

See if you can do this!

Review your answers from the previous activity. Are there some items there that are not considered as a computer? Ex

Computer Hardware and Software

In the previous activity, you learn some basic concept of a computer and were able to classify and
identify computers. We further discuss the different types of computers based on their size,
processing speed, and storag and, importantly, its uses. With these, you were able to see both the
physical components of computer as well as the application component through the functions in
which it is used for. In computer terms, these components of computer are called the hardware
and software.

Try This!

Let us take a closer look into your devices, that is, your mobile phones and/or Pcs/laptops. You can investigate just on

11 | P a g e
Computer Fundamentals and Programming Using Python

Think Ahead!

Can you identify which are hardware and software components? Can you differentiate one from
the other? In the table below, list down the parts of the devices under the Hardware column and
the applications used for the devices under Software column. List as much items as you want.

Hardware Software

Check if you were able to identify clearly the hardware from the software components by
referring to the descriptions on the next page. If you have some doubts in your list, consult with
your instructor.

Think About This!

A computer will be worth useless without either one of these components: Hardware and Software.
The hardware consists of the “hard” components of the computer, that is, the electronic or
mechanical part of the computer. So, if you listed the physical parts or devices that you have seen,
then, you are on the right track! Hardware is further divided into smaller components, that is, input

12 | P a g e
Computer Fundamentals and Programming Using Python

and output devices, processing units, and storage devices (see section on Computer System
Organization).

On the other hand, the software consists of the “soft” components also called programs. These are
the applications that you use to do your work or tasks. These programs are also a set of
instructions that you feed into the computer in which the computer works on (see What is a
Computer Program? section for more details). If you were able to list on some of these
applications, you are doing a great job!

There are three (3) types of software, namely, System Software, Application Software, and
Program Software.
• System softwares are programs that control and maintain the operations of the computer
and its devices. It includes all operating systems, such as Windows OS, Ubuntu, Linux, and
Mac OS, and utility programs, such as computer management.
• Application software are programs that perform specific tasks for the user. It includes
application to create and manage word or text documents, spreadsheets, and presentations
such as Microsoft Office and Open Office. Web browsers, such as Chrome, Mozilla and
Internet Explorer, and games are also considered as application softwares. We will explore
basic application software later in this moule (see section Application Software and the
Internet)
• Program software also called programming languages or development tools. These are
programs used to create other programs or applications. It includes Java, C#, PHP, and C++
among others. For this subject, you are going to use program software, C++ programming
language, to create your own programs.

Try to review the applications that you have listed as softwares. Were you able to identify all types
of software? Which type have you identified the most? Which type have you identified the least or
maybe have not identified at all? You can explore the devices more to look for more of these types
of applications.

From the definitions of hardware and software, we can conclude that for a device to be considered
a computer, it must have the hardware and software components. Software cannot run on itself. It
needs a hardware where you place or install the software. Also, the hardware cannot run on itself.
Without the software installed, it would just be another matter that occupies space.

In a sense, a computer can be likened to a human being, the physical body as hardware, the
thoughts, ideas, and feelings as software. Can you already imagine robots as classmates? Although
a possible future, it will take more complex and extensive artificial intelligence as well as high-end
innovations in electronic devices to create just that. Think: the processing speed and storage of
supercomputers with a hundred times smaller than microcomputers chips. With these, you can
probably create robots that fly!

Computer System Organization

Now you know what a computer is and what it does, we will try to understand better how it
actually works through its individual components. The study of the interconnectivity of the
different computer components and how it performs its functions in a digital computer system is
called Computer Organization.

13 | P a g e
For Instructional Purposes Only
Computer Fundamentals and Programming Using Python

Try This!

To get to know more about computers, consider the personal computer and laptop below. Write
down the partsthat you can identify on the lines provided on each side and connect it to the parts
on the respective image.
Computer
Components List Laptop Components
List

(Images courtesy of btechfix.com and publicdomainpictures.net, respectively)

Think Ahead!

Given the components above and what we know of the characteristics of a computer, identify which
of these components are Input, Process, Output, and Storage devices by writing check (✔) on
the appropriate column.

You can place as the same item for components that are considered the same for computers and
laptops. You can use a separate sheet if you identify more components.

Type of Component
Component/s
INPUT PROCESS OUTPUT STORAGE

14 | P a g e
For Instructional Purposes Only
Computer Fundamentals and Programming Using Python

Read and Ponder!

Computers or the Computer System have different components and these componens interact
with each other to make possible what it does. May it be to play music, print a copy of your
document, or make your document. Understanding the computer system is understanding how it
is structured (i.e. Computer Organization).

The main components of a computer system consists of the Central Processing Unit,
Input/Output Devices, Memory, and System Bus (see Figure 1.1).

Central Processing Unit


Input Device Output Device

Memory System Bus

Figure 1.2 Main Components of Computer System

Main Components of a Computer System

The Central Processing Unit (CPU)

The central processing unit is responsible for the processing of data and controlling the system. It is
considered to be the brain of the computer system. A CPU consists of the Control Unit (CU),
Registers, and the Arithmetic and Logic Unit (ALU). These parts interact closely with each other to
process the instructions (as inputs) and produces the outputs (see Figure 1.3 below).

Figure 1.3 Parts of a Central Processing Unit

15 | P a g e
For Instructional Purposes Only
Computer Fundamentals and Programming Using Python

Specifically, each part does the following:


• Arithmetic and logic unit (ALU): The part of the CPU that process most of the arithmetic
and logic operations.
• Control Unit (CU): The part of the CPU that controls the flow of data within the
computer system. It is considered to be the traffic cop within the computer system.
• Registers: A type of memory found within the CPU. A capacity of this memory is quite
small compared to the capacity of other types of memory but the fastest in accessing data.
It stores data being processed by the ALU.

Memory

The memory is a component used to store data. Also known as storage devices. It is
another key feature of computers. There are two things that you should know about
computer storage: storage medium and storage devices or drives. The storage medium
is the physical media that holds data, instructions, and information for future use while
storage devices record and retrieve data from and to the storage medium (Discovering
Computers, 2002).

Categories of Memory

▪ Primary Storage – This is the storage that is directly accessible to the CPU of a
computer without any input/output channels. This is where currently used or
active data is stored. The following are different types of primary storages:

o Read-Only Memory – Data stored in this memory cannot be modified, hence,


it is termed as “read-only”. Data stored in this memory are standard or
programmed instructions created by manufacturers. ROM is non-volatile, that
is, data remains the same even after switching off the computer.

Figure 1.4 Read-Only Memory chips

o Random-Access Memory – It consists of integrated circuits that allowed the


stored data to be accessed at any order, hence, it is termed as “random”.
Data stored in this memory are temporary (or volatile), that is, all data stored
will lose after computer is switched off.

Figure 1.5 Random-Access Memory chipset

16 | P a g e
For Instructional Purposes Only
Computer Fundamentals and Programming Using Python

▪ Secondary Storage – This is the storage that is not directly accessible to the
CPU. It needs input/output channels for it to access the processing unit. Data
stored in this device are not currently in active use. Since it is not directly
accessible to CPU, it is slower than the primary storage but it has a higher storage
capacity. Examples of secondary storages are hard disk (included in the system
unit), USB flash drives, memory cards, and compact disc (see Figure 1.6). Data in
these storages are non-volatile. So, whatever you saved in this type storage will
be there even if you switch off the computer.

Figure 1.6 Sample Secondary Storages

Storage Devices

The most commonly used storage device is the hard disk drive and CD-ROM or CD-
RW drives. Hard disk contains plotters where data is stored. These plotters are
enclosed in a disk drive which reads and records data into the plotters or disk.
Compact Disc – Read-Only Memory (CD-ROM) drives reads data from compact disc
which usually contains music or movie files. While Compact Disc – Re-Writable (CD-
RW) records data into compact discs. Nowadays, most these drives are also
compatible for DVDs. Figure 1.7 shows the different kinds of storage devices.

Figure 1.7 Sample Storage Devices

Input and Output Devices

Input Devices

Input devices are any peripheral devices that is used to provide data in a form of
instructions to the computer. Data can be in a form of keystrokes, mouse clicks, touch
screens, barcodes, sounds, images, and videos among others. The table below are some
these input devices:

17 | P a g e
For Instructional Purposes Only
Computer Fundamentals and Programming Using Python

Table 1.1 Common Input Devices

Input Devices Description

It is the oldest and most widely used among the input


Keyboard devices. It contains keys that represent numbers, texts,
and other symbols. A key press or keystroke or a
combination of keys will send the signal to the system
unit that will be equivalent to a character or command.
Keyboards are connected through wire but nowadays,
there are already wireless keyboards that use Bluetooth
technology to send signal from keystrokes.

Mouse
It is a pointing device that detects movement relative to
the flat surface where it is placed. A click on the mouse or
movements on the trackball sends signal to the system
unit. An equivalent arrow (pointer) represents the
position on the screen. The mouse is used to control this
pointer by pointing, clicking, double clicking and
dragging objects across the screen. A trackball is also a
different variety of a mouse.

Microphone
It is an acoustic electronic sensor device that converts
sound into electronic signals. It is used to record sound or
to issue commands using voice recognition software. In
most cases, you can also find microphone in headsets.
Headsets already contain a microphone and speakers for
both ears. This makes it more handy more users.
Joysticks
It is similar to mouse in terms of controlling components
in the screen and navigation. This device is mainly used
for gaming purposes. It contains stick levers and buttons
to control the different characters in the game you are
playing. Joysticks are usually included in playstations but
not desktop computers. However, with the appropriate
port, this device can also be used in your PC.

Image
Scanners
It is used to analyses photographs, text documents,
handwritten documents or any other object and converts
them as digital images. These image files become virtual
copies of the hardcopy photos or documents which can
be stored, make copies, or even edited. Image files have
multiple formats such as JPEG, PNG, GIF, and BMP files
formats

18 | P a g e
Computer Fundamentals and Programming Using Python

Input Devices Description


Web Camera
It used as a real-time camera that reads in images through
its lens. It is mostly used to transmit real-time images in
Internet. It is also used to capture images converted as
image files or record videos converted into video files.
Video files also have multiple formats such as AVI, WMV,
MPEG, and MP4 file formats.

Graphic Tablets
It is used for graphic design and animation. It consists of a
touch sensitive screen that acts as sensor that sends
signals to the system unit. It also comes with a pen-like
device, called stylus. Using a stylus on this device, allows
you to draw images like you are writing or drawing on a
paper. The technology used for this device is greatly
similar to the touchscreen technology used in most smart
phones and tablets.

Barcode Reader It is an input device that converts a pattern of patterned


bars into numbers. Each pattern is assigned an equivalent
number value. This is mainly used in business like
supermarkets and stores to quickly input product codes
and other product information. It uses similar technology
with that of image scanners.

This list of input devices is just some of the most common input devices available. The list
does not include input devices that are already embedded into the main device, for
instance, touchpads on laptops that have same function as a mouse device. Another
example is the TV tuner which is installed as cards in the system unit. This device detects TV
signals so that you can use your computers as a television set. Your ordinary camera or
video camera can also be used as input devices. There are still other input devices in the
market that are waiting for you to be explored.

Output Devices

Output devices are any peripheral devices that are used to display or output information
after data is processed. The output or information is displayed in the form humans can
understand. These outputs can be in a form of images, videos, or text display and sounds
among others. The table below are some of these output devices:

19 | P a g e
Computer Fundamentals and Programming Using Python

Table 1.2 Common Output Devices

Output Devices Description


It is the one of the most widely used of all output
devices. Monitors are included in almost any devices
from desktop computers, laptops, tablets, to smart
Monitor phones. It mainly displays texts and images. From the
processing unit, it generates a temporary record, that
is, any text or image.

Display will disappear once the power is turned off.


Monitors vary in screen size, resolution, and dot pitch.

The higher the resolution of the monitor, the higher


the image quality it produced. The two (2) major types
of monitors are Cathode Ray Tube (CRT) and Liquid
Crystal Display (LCD). The figure on the left is an LCD
type, sometimes also called a Flat screen monitor. You
can see both LCD and CRT monitors in your computer
lab rooms.
Printer It is an output device used to produce a hard copy
of any documents both texts and images. If
monitors produce a temporary record, printers
produce a more permanent copy, i.e. a copy printed
on paper (hardcopy). There are many different kinds
of printers. The figure on the left is a type of inkjet
printer. This type of printer produces a copy by
spraying ink on paper. Some other types of printers
include dot matrix and laser printers.
Speakers It is an output device used to produce voice, music,
and other sounds processed and generated by the
system unit. It is connected through a sound card.
Speakers can also be in a form of earphones or
headsets (earphone with an attached microphone).
Some other small devices like laptops, tablets, and
mobile phones already embed speakers into their
device.
Speakers may also vary in their acoustic quality.
Projector It is an output device that produces text or image
display by projecting light into a surface. Monitors
only display output based on the size of its screen for
mainly a single user. Projectors, on the other hand, are
designed to display output for a larger group of
audience. It is mainly used for group presentations
and meetings. Most of the projectors are quite bulky,
but nowadays, smaller and handier projectors are
becoming more popular.
Plotters It is an output device that is similar to printers, that is,
it produces hardcopy text or image documents.
Plotters use pens to draw straight lines that produce
images, maps, charts, and blueprints. Unlike printers
which are mainly designed to print outputs mainly in a

20 | P a g e
Computer Fundamentals and Programming Using Python

Output Devices Description


standard paper document, plotters are used for larger
images. It is mainly used to print out engineering
designs or blueprints. Nowadays, it is commonly used
in graphics designs through tarpaulins and billboards.

Just like some other components, there are other devices available that are not included in
this list. And some, similar to input devices, are already embedded into the device itself.
There are already cameras that can immediately print pictures. It is important to know all
these devices to be able to determine the appropriate technology to use. All these
innovations are products of society’s demand to have a higher quality and a more
productive way of living.

System Bus

Sytem bus acts as communication link between the different computer components.
Data and informations are being transferred from one component to another. The
following are the different types of buses:
• Address Bus: A type of bus where addresses are being transferred. Only addresses
generated by by CPU uses the address bus.
• Data Bus: A type of bus used by the CPU to transfer data, data to be processed by
the CPU or data processed by the CPU.
• Control Bus: A type of Bus used by the CPU for control signals. Usually, control bus
bus are used for handshaking.

See if you can do this!

In various fields of study, a Mind Map is used to graphically describe concepts or ideas. It is used
as a tool that “helps structuring information, helping you to better analyze, comprehend,
synthesize, recall and generate new ideas” (Litemind, 2020).

For this activity, describe the concept of computer system and organization using a Mindmap.
You can use any of the available drawing or mind map tools (i.e. web or mobile applications) as
shown in the examples below. Share and present your final mind map with the class.

Figure 1.8.1 Mindmap of Computer Gaming using Lucid Charts via www.lucidchart.com

21 | P a g e
Computer Fundamentals and Programming Using Python

Figure 1.8.2 Mindmap of Computer Gaming using Mind Meister via


https://www.mindmeister.com/

Figure 1.8.3 Mindmap of Computer Gaming using miMind mobile application available via
PlayStore or AppStore

How is it working with mind map tools? Have you encountered such tools before? Software tools
like this make your work and tasks easier! You will get to know more software tools in engineering
as you slowly deal with its various topics and concepts, from circuitry to management. For this
module, however, we will work with standard productivity tools as well as programming tools as
we progress.

Computer Number System and its Types

We know by now that a computer system has various componets that interacts with each other to
perform what we want it to do. But how does it interpret our instructions as inputs? And how does
it know how to show its outputs?

Like all digital devices, computer is physically composed of electronics... lots and lots of electronics.
All the computer components that we have identified basically consists of electronics (e.g. circuits,
capacitors, resistors, wires, etc.). Electronic devices, such as the computers, only understands ON
and OFF, represented by 1 and 0, respectively. Therefore, we have to translate our instructions (i.e.
characters, numbers, files, etc.) in the form of 0s and 1s, we call these the Binary Digits (or bit).

The Binary Number System is just one of the number systems that we need to learn in order to
be able to understand the “language” of computers.

22 | P a g e
Computer Fundamentals and Programming Using Python

Try This!

Throughout our life, we learned about the letters of the alphabet and numbers. We also learn
how to compute numbers and make words out of the alphabet. Now, we will make a little
translation of some of these alphabets and numbers using bits.

Using the table below, create an equivalent “8-bit data” by using a series of 0s and 1s, for
instance, 0 is represented by 00000000 and 2 is represented by 00000010. (You may change this
representation as you wish). Make sure that no data must be the same for any of the characters.

0000000009 IJKLMNOP RSTUVWXY


100000001A Q Z
B
C
D
E
F
G
H

Now, you have your own Binary-to-Character translation!

Think Ahead!

Use your translation table above write the equivalent binary digit equivalent of your firstname. If
your name is more than ten (10) characters long, you can choose to write in your nickname or a
short-cut name. Write the age (2 characters) after your name (see example below). You can leave
the rest of the characters blank.

E 10011010
L 00001010
L 00001010
A 10101010
2 00000010
0 00000000

How do you like your name and age in Binary? Now, imagine that 0s and 1s is turning ON or OFF
your lights. You can start using your binarx digit name series to set up your Christmas lights.

23 | P a g e
Computer Fundamentals and Programming Using Python

Read and Ponder!

In the field of Computer Organization, there are various number systems used to interpret and
translate data. We already know one of these, the Binary Number System. As we have discussed
here, a CPU, for instance, composes of control units, ALUs, and registers which actually holds data
in the form of characters which then translates it to bits.

The number system is a technique used to represent numbers in the computer system architecture,
every value that you are saving or getting into/from computer memory has a defined number
system. The computer system architecture supports the following number systems:

Base 2 Base 10 Base 8 Base 16

Data is represented by only Data


2 digits:
is represented by 10 digits:
Data is represented by 8 digits:
Data is represented by 16 alphanume
1 and 0. 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5,
6, 7, 8, and 9 6, and 7 6, 7, 8, 9, A(10),
B(11), C(12),
D(13), E(14), and
F(15)

Binary Number SystemDecimal Number System Octal Number System Hexadecimal Number System

Figure 1.9. Summary details of the different Base Number Systems

The table below shows an example of a data representation based on the number system and how
it is used as assignment statements in C Language. You will know more about assignment
statements in the succeeding topics.

Table 1.3 Sample of data representation using the different number systems
Number System Example C Language assignment

Binary (10101010)2 int val=10101010;


Octal (252)8 int val=0252;

Decimal (170)10 int val=170;


Hexadecimal (AA)16 int val=0xAA;

To determine the number system that the current data represents, a subscript of the base is
indicated. As shown above, (252)8 means that 252 is an octal number (Base 8) while (170) 10 means
that 170 is a decimal number (Base 10). This is very important to remember as we move along
to converting one number system to the other or computing using different number systems.

24 | P a g e
Computer Fundamentals and Programming Using Python

Number System Conversions

In computer architecture, various components such as memory and resgisters process data in a
certain format following different number systems. To be able to understand these data in various
representations, conversions between number system is needed. The following are three (3) major
ways to do conversion:
• Decimal Number System to Other Base Number Systems
• Other Base Number Systems to Decimal Number System
• Other Base Number Systems to Other Base Number Systems

Decimal Number System to Other Base Number System

The following steps allow you to convert Decimal number system to other base number systems
convert a number system:
1. Divide the given number (i.e. Decimal Number) by the base of target base number system,
that is 2 for Binary (Base 2), 8 for Octal (Base 8), and 16 for Hexadecimal (Base 16) number
system.
2. Write the remainder from step 1.
3. Use the quotient as the new number and repeat step 1 until quotient is 0. The first
remainder is considered as the Least Signification Bit (LSB) and the last as a Most
Significant Bit (MSB).
4. Once the quotient is 0, write data representation from MSB to LSB.

The example below shows the application of the steps above converting the decimal number 2010
to binary, octal, and hexadecimal.

Decimal to Binary
base number to
convert to

given decimal
Least Significant Bit
20 / 2 = 10 remainder 0 (LSB)
number 10 / 2 = 5 remainder 0
quotients from 5 / 2 = 2 remainder 1
dividing the decimal 2 / 2 = 1 remainder 0 Most Significant Bit
number 1 / 2 = 0 remainder 1 (MSB)

Result (Decimal to Binary): 2010 = 101002

Decimal to Octal

20 / 8 = 2 remainder 4
2 / 8 = 0 remainder 2

Result (Decimal to Octal): 2010 = 248

25 | P a g e
Computer Fundamentals and Programming Using Python

Decimal to Octal

20 / 16 = 1 remainder 4
1 / 16 = 0 remainder 1

Result (Decimal to Hexadecimal): 2010 = 1416

Other Base Number System to Decimal Number System

The following steps allow you to convert from any other base number systems to Decimal number
system:
1. Determine the base value of the given number and the position of digits from LSB to MSB.
Note that the LSB is at position 0, next digit’s position is 1, next is 2, and so on.
2. Multiple the digit and the base value with the position as an exponent.
3. Add the results of the products from step 2.

We will use the result of the previous examples, that is, 101002 , 248 , and 1416 to convert to
decimal number and validate our results. Hint: It should arrive to the same value, 2010 .
Binary to Decimal

positions of the digits


digit’s position
4 3 2 1 0 is used as
(from LSB to MSB
exponent
given binary
number 10100
0 x 20 = 0 x 1 = 0
0 x 21 = 0 x 2 = 0
products of the
1 x 22 = 1 x 4 = 4 binary digits
0 x 23 = 0 x 8 = 0
1 x 24 = 1 x 16 = 16
Result in
2010 decimal number
base
value
Result (Binary to Decimal): 101002 = 2010

Octal to Decimal

1 0

24
4 x 80 = 4 x 1 = 4
2 x 81 = 2 x 8 = 16
2010 Result in
decimal number

Result (Octal to Decimal): 248 = 2010

26 | P a g e
Computer Fundamentals and Programming Using Python

Hexadecimal to Decimal
1 0

14
4 x 160 = 4 x 1 = 4
1 x 161 = 1 x 16 = 16
2010 Result in
decimal number

Result (Octal to Decimal): 1416 = 2010

Other Base Number System to Other (Non-Decimal) Number System

Since you already know how to convert to and from Decimal numbers, the following steps may be
easily applied for conversions in between other base number systems:
1. Convert the given base number to decimal number.
2. Convert the decimal number to the target base number.

Once again, we will use the results of the previous examples in converting binary and octal
numbers, 101002 and 248 respectively, to hexadecimal number.

Binary to Decimal Decimal to Hexadecimal


given binary number

10100
0 x 20 = 0 x 1 = 0 20 / 16 = 1 remainder 4 1416
0 x 21 = 0 x 2 = 0 1 / 16 = 0 remainder 1
1 x 22 = 1 x 4 = 4 Result to
0 x 23 = 0 x 8 = 0 Hexadecimal
Number
1 x 24 = 1 x 16 = 16
2010

Octal to Decimal Decimal to Hexadecimal

24
4 x 80 = 4 x 1 = 4 20 / 16 = 1 remainder 4 1416
2 x 81 = 2 x 8 = 16 1 / 16 = 0 remainder 1
2010 Result to
Hexadecimal
Number

27 | P a g e
Computer Fundamentals and Programming Using Python

Shortcut Method to Convert Octal and Hexadecimal Numbers to/from Binary


Numbers

We now know from the wys in converting in between base number systems may be done by
initially converting the number to decimal value. In the language of binary digits, octal numbers is
just a series of 3-bit data while hexadecimal numbers, a series of 4-bit data. Refer to the
details in Table 1.4.

Table 1.4. Examples of Octal & Hexadecimal Numbers using 3-bit and 4-bit notations
Number System Base Value
In Base 2 representation Examples In Binary Numbers
Octal 8 23 (or 3 bits) 101
58 111101
758 1001
9 11111001
Hexadecimal 16 24 (or 4 bits)
F9

Check the breakdown of the bits series below from the examples given above:
octal number
hexadecimal number
758
F 9 16 NOTE: Hexadecimal
character “F”is
equivalent to decimal
(3-bit digit) 111 101 1111 1001 num(b4-ebrit1d5ig,ith) ence,
1111 in binary

111101
binary number 11111001
binary number

As your guide, you can use the reference below for easy binary-decimal conversation. Just add the
equivalent numbers above for 1 bits and disregard 0 zero bits.
8 4 2 1 8 4 2 1 8 4 2 1 8 4 2 1
binary
digits
1111 0101 1010 1011
8+4+2+1 0+4+0+1 8+0+2+0 8+0+2+1

decimal
number 15 5 10 11
equivalents
In the same manner, you can also convert binary numbers to octal or hexadecimal numbers by
dividing the bits into groups of 3 or 4 bits. Example: Convert binary number 10111000102 to octal
and hexadecimal numbers (see solution below).

421
42 42 42 842 842 8421
1 1 1 1 1
binary
1 / 011 / 100 / 10 / 1110 / 0010
digits
010
2 14 2
1 3 4 2
decimal 2E216
13428
number
equivalents
28 | P a g e
Computer Fundamentals and Programming Using Python

Arithmetic Operation

Internally, in the Arithmetic Logic Unit (ALU), the CPU of a computer performs computations to
process inputs and generate the necessary outputs. To perform arithmetic operation with number
systems, numbers to be added or subtracted must be of the same number base. If numbers are
of different bases, one must be converted to the other to make their bases the same.

To make addition and subtraction easier with number system, it is much better to just consider the
numbers as decimal.

Addition with number system

In performing addition, the condition below must be applied:


• If the sum is equal or greater than the base of the numbers being added, subtract the
value of the base from the sum and add one (1) to the next higher digit (carry).

Examples:

Binary Addition
10112 + 10012
Steps:
Base = 2
1. 1 + 1 = 2 ; since 2 is equal to base, subtract 2 from sum and add 1 to the
next digit (carry)
1 carry value
10112
10012
0
2. Next digits to be added are 1 and 0 equals is 1 plus the carry, sum is 2;
again the sum is 2. Subtract 2 from sum and add 1 to the next digit
(carry).
11
10112
10012
00
3. Next is 0 plus 0 plus the carry. Sum is 1.
1
10112
10012
100
4. Lastly, 1 plus 1 is 2. Sum is equal to base, subtract 2 from sum and add 1
to the next digit (carry).
10112
10012
10100
5. The sum of 10112 plus 10012 is 101002

29 | P a g e
Computer Fundamentals and Programming Using Python

Octal Addition
370.348 + 456.708
Steps;
Base = 8
1. 4 + 0 = 4 ; since 4 is less than the base, condition cannot be applied
370.348
456.708
4
2. Next digits to be added are 3 and 7 equals is 10, sum is greater than base.
Therefore, subtract 8 from 10 and add 1 to the next digit.
1
370.348 carry value
456.708
24
3. Next is 0 plus 6 plus the carry. Sum is 7 and is less than base.
1
370.348
456.708
7.24
4. 7 plus 5 is 12. Sum is greater than base, subtract 8 from sum and add 1 to
the next digit (carry).
1
370.348
456.708
47.24
5. Lastly, 3 plu 4 plus the carry equals 8. Again, Sum is greater than base,
subtract 8 from sum and add 1 to the next digit (carry).
1
0370.348
0456.708
1047.24
6. The sum of 370.348 plus 456.708 is 1047.248

Subtraction with number system

With this method of subtraction, the minuend must be greater than the subtrahend. It is impossible
to subtract a bigger value from a smaller value.

Subtraction is done by first arranging the numbers in the column in such a way that the digits of
the same place are in the same column. Starting from the least significant digit, subtract the
subtrahend from the minuend. If the minuend is less than the subtrahend, 10 n is being borrowed
from the next higher digit.

Since subtraction is being performed with different number system, 10 n is still being borrowed but
with different value. For binary for example, 102 is 2 in decimal. 108 is 8 in decimal.

If 10n is borrowed, add its equivalent to the minuend. Subtract the subtrahend from the minuend
just like performing decimal subtraction.

30 | P a g e
Computer Fundamentals and Programming Using Python

Example:

Binary Subtraction
10112 - 10012

Arrange the given numbers in columns;


10112 minuend
10012 subtrahend

Steps:
Base = 2, therefore 102 is 2. Starting from the least significant bit;
1. 1-1=0;
10112
10012
0
2. Next digits to be subtracted 0 from
1. 10112
10012
10
3. Next is 0 minus 0, difference is 0.
10112
10012
010
4. Lastly, 1 minus 1 is 0.
10112
10012
00102
5. The difference of 10112 and 10012 is 102.

Hex (or Hexadecimal) Subtraction


370.3416 - 256.7016
Steps:
Base = 16, therefore 1016 is 16. Starting from the least significant bit;
1. 4-0=4;
370.3416
256.7016
4
2. Next digits are 3 minus 7. The subtrahend (7) is greater than the minuend
(3) and subtraction cannot be performed. 10 16 must be borrowed from the
next digit. Since the next digit is 0, borrow 10 16 from the next higher digit
and add 16 to value of the minuend. 7 will become 6, 0 will become 16.
Since 3 borrowed from 0, 16 will become 15 and 3 will become 19.
Subtraction can now be performed. 19 minus 7 is 12, which is C.
16
15 15 (carry)
borrow 6 16 6 16 16 6 16 19
3 7 0 . 3 416 3 7 0 . 3 416 3 7 0 . 3 416
2 5 6 . 7 016 2 5 6 . 7 016 2 5 6 . 7 016
4 4 C4
12 is C
in

31 | P a g e
Computer Fundamentals and Programming Using Python

3. Next is 15 minus 6 is 9.
15
6 16
3 7 0 . 3 416
2 5 6 . 7 016
9.C4

4. 6 minus 5 is 1.
6
3 7 0 . 3 416
2 5 6 . 7 016
19.C4

5. Lastly, 3 minus 2 is 1.
3 7 0 . 3 416
2 5 6 . 7 016
119.C4

6. Difference between 370.3416 and 256.7016 is 119.C416.

See if you can do this!

Part I. Convert the given values below to other base number systems. Specify on the space after
“Convert to:” the name of the number system you want to convert. And write your final answer on
the space after “Converted Value:”. Show your solution on the space provided for each conversion.

Given number #1: 20208

Convert to: Converted Value:

Convert to: Converted Value:

Convert to: Converted Value:

32 | P a g e
Computer Fundamentals and Programming Using Python

Given number #2: 202016

Convert to: Converted Value:

Convert to: Converted Value:

Convert to: Converted Value:

Part II. Perform the following operations and write your solution on the space provided for. You
can choose which of the given values you want to convert to perform the operation. Show the final
output in all the base number systems.

Operation #1: 20208 - 202010

Solution

33 | P a g e
Computer Fundamentals and Programming Using Python

Answer for #1

In decimal: In binary:
In octal: In hexadecimal:

Operation #2: 202016 + 111111001012

Solution

Answer for #2

In decimal: In binary:
In octal: In hexadecimal:

34 | P a g e
Computer Fundamentals and Programming Using Python

II. Application Software and the Internet

The World of Information


Technology

In the previous chapter of this module, we discussed in detail about computer, its use, and its
different components. Computers, however amazing, is just one of the great innovations of this
century. In the past decade, the concept of robots and artificial intelligence (AI) is not just present
in the movies but are already applied different fields. In this generation, most people are already
accustomed to being “online”; checking emails, social media, online games, video calls, and, now,
online classes! These developments in our daily tasks is made possible by information
technology.

Technological revolutions have progressed throughout history and much of the driving force of the
innovation from the 3rd Industrial Revolution (also known as the Digital Revolution, from the
invention of computers and Internet to automation an digitation with the use of electronics and
computers) to the current one, 4th Industrial Revolution (i.e. digital transformations with data
analytics, AI technology, IoT, among others), is the developments in information technology. You
can read more about the Industria Revolutions from the article titled “Timeline of Revolutions” by
Lucas Gregory (2019). “Information Technology is a general term that describes any
technology that helps produce, manipulate, store, and communicate, and/or disseminate
informtion.” (Williams and Sawyer, 2011). Our computers, mobile phones, and other digital
devices, applications software, as well as the Internet, are all part of information technology.

For this section, we will explore the applications of information technology by using some of the
most common application software available to us, that is, word and spreadsheet applications. In
addition, we will also explore the Internet, as the central core of IT and major form of
communications at this time.

Objectives:

At the end of this section, you should be able to:


1. use application software to create and format word and spreadsheet documents;
2. apply technical features, such as tables, images, and graphs/charts in creating word and
spreadsheet documents;
3. identify the uses of the Internet and the guidelines in being responsible Internet users; and
4. recognize issues related to the Internet’s impact in people’s lives.

Topic Outline:
I. Application Software
a. Word Processing
b. Spreadsheet
II. The Internet
a. Communication over the Internet
b. Exploring the Internet
c. Societal Issues and the Future of the Internet
35 | P a g e
Computer Fundamentals and Programming Using Python

Try This!

How familar are you of some application software and the Internet? From their icons, identify and
write the names the different application programs below the respective icon.

Think Ahead!

For this activity, you need to have any working Internet connection. We will get to know more about
the application software that we are going to use by following these steps:
1. Open the Internet browser available on your computer, laptop, tablets, or smart phone.
2. Type in the address box one of the most popular website, www.google.com.
3. Once the page is loaded, find the empty box and type in the keywords (below), one at
a time, and press enter.
4. You will now be directed to the list of results. Note the total number of results (“No.
of Results”) and the time. Write these details on the table below.
5. Now, click on the first result and write the address on the last column of our table.
Keywords No. of Results Time Address of the 1st result
“Word Document”
“Spreadsheet Document”
“The Internet”
“World Wide Web”
Your name

How many results were you able to get? 500? 1000? 10K? And how long did it take? Try to count
the number of results and the time it takes for you to count it. We know who is faster. Were the
results relevant, in particular, the first result? How about the results when you type your name?
Did it show you or someone else? It is, indeed, amazing how much information is available on the
Web. However, as citizens of the digital world, it is ever more important now to be aware of what
is relevant information and discern fact and truths over false (or fake) information.

36 |Pag
e
Computer Fundamentals and Programming Using Python

Read and Ponder!

The computers, with its many components and complex circuitry, is only as good as what it can do
to the users. To make our computer hardware usable, application software are developed.
Simply, application software, also known as “apps”, are programs designed for end-users.
Nowadays, application software comes in many forms, such as games for entertainment, a weather
app to check the weather forecast, or productivity tools to create documents or presentations.
Software applications, as part of information technology, is commonly used to produce and
manipulate data. Productivity tools, such as word and spreadsheet applications, are the most
commonly used software applications for students and faculty and which we will discuss further in
this chapter.

Apart from the productivity tools, the most commonly used application software is the Internet
browser. The Internet browsers (e.g. Chrome, Safari, Mozilla, etc.) acts as the doorway to the the
World Wide Web via the Internet. The Internet The Internet is a “global network of billions of
computers and other electronic devices” that “allows you to communicate and access information
from anywhere else in the world.” (GCF LearnFree.Org, 2020).

Application Software

Productivity tools or software are “any application people use to "produce" information. Virtually
any program used to create or modify a document, image, audio or video clip is productivity
software.” Some of the most common productivity tools are word processing and spreadsheet
software which are usually included in a “productivity suite” such as Microsoft Office, Libre Office,
Apache Office, and Google Docs among others.

Do you have any productivity tools installed? You can use the FREE ONLINE Office 365 Productivity
Tools using your WMSU email account!

Office 365 Education

Office 365 Education is a product of Microsoft that offers


Students and Educators access to Office 365 online for free. This
includes Word, Excel, PowerPoint, OneNote, and now Microsoft
Teams, plus additional classroom tools. It aims to support remote
learning using the more familiar tools as well as other
productivity tools equiped with cloud services.

1. Visit the Office 365 for Education page:


https://www.microsoft.com/en-us/education/products/
office
2. Enter your WMSU email account and press GET STARTED
(See Figure 2.1.1) IMPORTANT NOTE: Only the university
account (i.e. @wmsu.edu.ph) will have access to their free
online tools. If you do not know your WMSU email
account, request it here:
Figure 2.1.1 Starting with
https://forms.gle/7TYUX3V9nYvkVYJT8 or visit WMSU Office 365
website for the updated link.
37 |Pag
e
Computer Fundamentals and Programming Using Python

3. Select type of User: Student


4. Enter your account details. Make sure to
remember your password for future log-
ins to Office 365 (see Figure 2.1.2).
5. Check your email for the 6-digit
verification code. You will receive an
email like the one shown in below (Figure
2.1.3).

Figure 2.1.2 Account Details


Figure 2.1.3 Verification
Code sent via email

6. Enter the verification details and once done, click on Start link (see Figure 2.1.2). NOTE: In
case no verification code was sent, you can click on the “resend signup code” or double
check your email entry (in case, you still did not received any code).
7. Once sucessfully logged-in, productivity tools will already be available like Word and
Spreadsheets (see Figure 2.1.4). For the rest of the applications available under Office 365,
click on all apps. Application list is shown in Figure 2.1.5.

Figure 2.1.4 Office 365 Basic Applications

Figure 2.1.5 Office 365 Applications

Here’s an additional takeaway! Office 365 may also be used on your mobile devices! Just download the app fro

38 |Pag
e
Computer Fundamentals and Programming Using Python

Here are alternative office productivity tools program that you can use and explore:
• Libre Office: An open source application developed by The Document Foundation that can
be downloaded and use for free. The Document Foundation is a non-profit organization and
is composed of a community of developers who “believes in the principles of Free Software
and in sharing their work with the world in non-restrictive way”. You can download this
application for free at https://www.libreoffice.org/download/download/.
• Office Tools for MacOS/iOS: For most Apple users, iWork productivity tools application
that includes Pages and Numbers are already pre-installed with any of the purchased Apple
device. This tool is developed by Apple Inc. and may be downloaded in the AppStore.
• Apache Open Office: This is another open source application developed by The Apache
Foundation that can also be used for free. The Apache Foundation aims to “to provide
software for the public good”. You can download this application for free at
https://www.openoffice.org/download/.
• Google Docs: It is a free online productivity tool developed by Google LLC (or simply
Google). Google is one of the Big Four tech companies in USA alongside Apple, Microsoft,
and Amazon (Rivas, 2017). The Google Docs is accessible using any of your Google accounts
(i.e. @wmsu.edu.ph or @gmail.com). Similar to Microsoft’s Office365, it is only available
online with internet connectivity.

Word Processing Software

Word processing software (e.g. MS Word) is part of the productivity tools software that
allows user to create any form of documents which primary contains texts such as application
letters, memos, technical reports, or a simple journal. For this manual, we will explore Microsoft
Word as our main software tool. You can also use Text Document from Libre Office, Pages for
MacOS/iOS users, or Docs from Google Docs. They will have a different way of showing their
features but the functionality of these features are generally the same.

The following are the common features of the Word Processing software (GCF LearnFree.org, 2020):
• Formatting Texts – format texts within the document such as text font styles, sizes, color,
highlights (i.e. bold, italize, underline), and alignments.
• Page Layouts – sets the layout of the page to include page sizes, orientation, and margins.
• Spelling and Grammar Check – automatically checks for mispelled words or wrong
grammar within the text.
• Indents and Tabs – adds structure to the document and making it readable using proper
indentions and tabs.
• Line and Paragraph Spacing – improve the readablity of the document by setting lines
and paragraph spacing to fit into the page.
• Lists – organized list of items within the document using bullets and numbered lists. This is
useful in emphasizing list of points or giving steps or direction.
• Document breaks – create sections within the document to improve the layout by adding
line, page, section, and column breaks
• Columns – improve layouting by creating columns within the document similar to
newspaper or magazine layouts.
• Hyperlinks – create Internet links for easy access and reference to addtional information
available online.
• Shapes – add variety of shapes to the document to include circles, triangles, rectangles,
arrows, callouts, and other shapes. These could be used to create concept maps, diagrams,
or flowcharts.
• Textboxes and Word Arts - specially formatted texts treated similarly as shapes. This is
used to highlight certain texts for emphasis.
• Clip Arts and Pictures – insert clip arts (i.e. pre-defined images in the office gallery) or
pictures that are used to add illustrations to documents.
39 |Pag
e
Computer Fundamentals and Programming Using Python

• Styles and Themes – style is a predefined combination of font style, color, and size of text
that can be applied to selected text. A theme is a set of formatting choices that can be
applied to an entire document and includes theme colors, fonts, and effects.
• Headers and Footers – creates a header section of the document that appears at the top
margin and footer section that appears at the bottom margin. These are used to place in
document details like, name of the chapter, page numbers, or reference footers in formal
documents like technical reports and thesis.
• Comments – used to annotate or comment parts of documents that needs to be reviewed
or revised. This is usually used to review documents such as research prior to publication or
submission.
• Tables – use to organize and present data, in most cases, numerical data in a table format.
A table is a grid of cells arranged in rows and columns.
• SmartArt Graphics - use to illustrate and organize many different types of ideas. It allows
you to visually communicate information rather than simply using text. Illustrations can
enhance your document, and SmartArt makes using graphics especially easy.
• Mail Merge – a useful tool that will allow you to easily produce multiple letters, labels,
envelopes, nametags, and more using information stored in a list, database, or spreadsheet.

To go through these features, a step-by-step tutorial for MS Word 2010 designed by the
GCF Global is made available here: https://edu.gcfglobal.org/en/word2010/. A video
tutorial for each feature is also included. If you cannot access or have difficulty in
accessing the website, ask a copy of the procedure from your instructor.

See if you can do this!

Let’s get to know more about you! Using the word processing software, write your thoughts and
insights to the questions or question statements below by following the corresponding set of rules
and formats.
Section Details Rules / Format
Header
Your fullname, course, and Arial font style with size 10 and colored black; Bold; Right Align section

TitleTitle of your favorite movieFont style of your choice; Center alignment; Font size is your
current age; with your favorite color as the font color.
First paragraph
Write a story of how you At least 100 words; Font Style is Times New Roman with size
were born
Second Paragraph 12 and colored black; Left Align;
List three (3) best lessons Provide a short introduction before listing the lessons learned; learned from your parents

or guardians12 and colored black; Left Align


Third Paragraph
What have you done lately Describe your answer; At least 60 words; Font of your choice that is worth rememberi
Fourth
Using ten (10) words, Center Align; Lucida Handwriting font style with size 15; Font color of your choice
paragraph describe yourself.
ImageInsert a clip art or image Do not use a picture of you, your classmate, or other people. that describes youYou can use ava

Additional formatting requirements:


• Italize all positive words (i.e. appreciate, grateful, etc.)
• Strikethrough all negative words (i.e. disappointed, arrogant, etc.)

40 |Pag
e
Computer Fundamentals and Programming Using Python

• Bold all words pertaining to God or Higher Being


• Change the font color of the following words: love to red, hope to blue, and faith to

green. Be creative! Albert Einstein said it beautifully, “Creativity is intelligence having fun!”

Spreadsheet Software
Spreadsheet software (e.g. MS Excel) is part of the productivity tools software that allows user to
create spreadsheet documents in which data are organized in a table format. Each cell in the table
may contain a numeric, date, or text values. One of the most important feature of spreadsheets is
the creation of formulas that automatically computes for certain values in the table. It is used
mostly for computational data in statistics, finance, engineering, and data analytics among others.
Using the spreasheet software, charts and graphs for analysis are easily generated.

For this manual, we will explore Microsoft Excel as our main software tool. You can also use
Spreadsheet from Libre Office, Numbers for MacOS/iOS users, or Sheets from Google Docs. Similar
to the various word processing software, they will have a different way of showing their features
but the functionality of these features are generally the same.

At this point, you have already familiarized the features of the word processing documents. Some
of these features like formatting texts, page layouts, or SmartArt graphics are also included in the
spreadsheet software. Hence, we will focus into some of the features that is uniquely of the
Spreadsheet software (GCF LearnFree.org, 2020):
• Formatting Cells – use to format text and cells to include changing color and style of text
and cells, aligning texts, and applying special formatting to numbers and dates.
• Creating Formulas – use to calculate numerical information through creation of formulas.
A formula is an equation that performs a calculation. It can range from simple operations
(i.e. addition, subtraction, multiplication, or division of two cells) to complex mathematical
formula (i.e. interest rates, grades).
• Managing Worksheets – managing worksheets to help organize data and make it easier to
work with.
• Functions – are pre-defined formulas that can calculate shortens or simplifies basic
formulas such as summations, counts, averages of multiple cells.
• Sorting Data – arranges data alphbetically, from smallest to largest, or using other criteria
can help you find the information you are looking for more quickly.
• Outlining Data – it allows to group data that you may want to show or hide.
• Filtering Data – use to organize data in your worksheet into groupds and hide parts of it
from view. It allows to display a summarized data for quick analysis.
• Working with Charts – a tool used to communicate data graphically. Charts allow your
audience to see the meaning behind the numbers, and they make showing comparisons
and trends much easier.
• Sparklines – a convenient alternative to charts. Unlike a traditional chart, a sparkline is
placed inside a cell, allowing you to easily create a large number of sparklines (for example,
one on each row).
• Conditional Formatting – used to apply formatting to one or more cells based on the
value of the cell. It highlights interesting or unusual cell values, and visualize the data using
formatting such as colors, icons, and data bars.
• Pivot Table – used to make the data in your worksheets more manageable by summarizing
the data and allowing you to manipulate it in different ways. It is specially useful for
large and complex spreadsheets, but they can be used with smaller spreadsheets as
well.
• What-If Analysis – used to compute what-if analysis formula that can help you experiment
and answer questions with your data, even when the data is incomplete.
41 |Pag
e
Computer Fundamentals and Programming Using Python

To go through these features, a step-by-step tutorial for MS Excel 2010 designed by the
GCF Global is made available here: https://edu.gcfglobal.org/en/excel2010/. A video
tutorial for each feature is also included. If you cannot access or have difficulty in
accessing the website, ask a copy of the procedure from your instructor.

See if you can do this!

Now, let’s do a simple financial budgeting! Discuss with your parents or guardians your family’s
monthy, weekly, or daily expenses. List down the expenses for this month and categorize each
expense based on the following categories: Utility Bills, Clothes, Food, Gifts, Transportation, Rent,
Loan, Others. Also specify the cycle of the expense, that is, Monthly, Weekly, or Daily. Create a
worksheet using the spreadsheet application software with the expense details (columns A-D)
following the table below:
Worksheet A
A B C D E
1 Item Category Cycle Amount (in PHP) Sub-Total
2 Ex1. Electricity Utility Bills Monthly 550.00 (Auto-Compute)
3 Ex2. Water Utility Bills Monthly 200.00 (Auto-Compute)
4 Ex2. Fare Transportation Daily 100.00 (Auto-Compute)
5 Ex3. Grocery Food Weekly 400.00 (Auto-Compute)
6 OVERALL TOTAL EXPENSE (Auto-Compute)
Perform the following spreadsheet operations and requirements on your details:
• Follow the format specified in the above table with your choice of font style.
• Sort the data per category, alphabetically.
• Create the equivalent formula under column E for Worksheet A with the following conditions:
▪ If cycle is Monthly, sub-total is equal to the amount.
▪ If cycle is Weekly, sub-total is equal to the amount multiplied by 4.
▪ If cycle is Daily, sub-total is equal to the amount multiplied by 30.
▪ Overall Total Expense is equal to the sum of all sub-total amount of the all items.
• Create a column graph for Worksheet A that shows amount per item.
• Create a separate worksheet that contains the summary of expense per category following
the table below:
Worksheet B
A B
Category
Total Amount (Auto-Compute) (Auto-Compute) (Auto-Compute) (Auto-Compute)
Food
Transportation
Utility Bills
OVERALL TOTAL EXPENSE

• Create the equivalent formula under column B for Worksheet B with the following conditions:
▪ Total Amount is equal to the sum of the Sub-total amount of all items per
category from Worksheet A.
▪ Overall Total Expense is equal to the sum of all total amount per category
• Create a pie chart that shows the disribution of each category in the overall total expense.

Share your final worksheets to your parents/guardians and get their feedback!
42 |Page
Computer Fundamentals and Programming Using Python

The Internet

The Internet “began in 1969 as ARPANET (for ARPA, the Advanced Research Projects Agency of the
U.S. Department of Defense), with four linked-together computers at different universities and
defense contractors. From there the network expanded to 62 computers in 1974, 500 com-
puters in 1983, and 28,000 in 1987.” (William and Sawyer, 2011) Even until that time, the internet
was mainly used by researchers and academicians. With the development of the World Wide Web
in the early 1990s, the Internet has expanded for personal and commercial use. As published by
Clement (2020), “almost 4.57 billion people were active internet users as of July 2020,
encompassing 59 percent of the global population.” With this population, 3.96 billion are active
social media users. The rise of social media platforms has placed the Internet activity in a whole
new level. Along with the rise in users, issues on data privacy, cyber security, and online social
responsibilty becomes increasing more significant.

For this section, we will be discussing etiquettes in using the Internet as digital citizens, techniques
in exploring the Internet effectively, and socieal issues that affects it.

Communication over the Internet

Today, the impact of the Internet has been seen in the changes in normal transactions, as with
banks, shopping, and of course, online classes. And most of our communications whether at work
or with family and friends are done online using some of the most messaging and video
conferenicng applications like messenger, Viber, Zoom, Skype, among others. Indeed, our way of
communication with each other has greatly evolved with the Internet as a catalysts.

“You need to consider carefully the way you behave and act online as it defines what kind of a
'digital citizen' you are. This is not a series of simple dichotomous decisions that you have to make.
The way you choose to behave online requires you to think carefully about many decisions you
may usually take for granted. One useful way to look at this is to consider the idea of
‘netiquette’” (Shea, 2011 cited by University of Hull, 2020) or Internet Etiquette.

Shea (2011 cited in University of Hull, 2020) defined ten (10) principles of Internet etiquette of
neiquette to guide your communicaitions over various website communities to include the social
media platforms.

Ten Rules of Internet Etiquette


(University of Hull, 2020)

Rule 1: Remember the Human: “When you are online, it is sometimes easy to forget the human.
That is, the people you are interacting with online are real humans and not disembodied
usernames or profile pictures.” When you do not see the people you are interacting with, that is,
you do not see their reactions or the usual nuances in the conversations, it can be easier to
dehumanize other people. Always remember that there is another human on the other side. “You
should never say something to someone online that you would not say to him or her in person. It is
also useful to remember that online interactions are nearly always recorded and backed up. If you
act inappropriately, these recordings will serve as evidence against you.”

Rule 2: Be Ethical: “In life, people generally follow the law. It can however be easy to let your
ethics slip when online. Illegal streaming of movies, illegal downloading of music and copyright
43 |Pag
e
Computer Fundamentals and Programming Using Python

infringement is still breaking the law. It is the online equivalent of shoplifting.” technology is a great
tool to make our lives “easier”, we can also make mistakes easier. Even if it is practiced by many, it
still does not mean that it is good or that no harm is done. In some cases, it does not necessarily
associated with the law, just decency and consideration attuned to our ethical and moral values.

Rule 3: Know Where You Are: “Netiquette varies from website to website. What is acceptable in
one environment is not acceptable in another. For example, the way you behave on university
websites and discussion forums will be very different to how you behave on a social network like
Facebook.” You first have to see how people behave in the community, through their deiscussion
boards or posts and determine what is acceptable.

Rule 4: Respect Other People’s Time and Data Limits: “When you post anything online,
write an email or share a post it will take other people's time to read.” Shea (2011) argues
"it's your responsibility to ensure that the time they spend reading your posting isn't wasted".
Address your concerns to the appropriate and relevant people. Sending mass emails, for instance,
will take time from other people reading your message. Take your time to describe your concerns
clearly and identiying the relevant people who can address that, rather than posting it on your
Facebook wall.

“When considering data limits - or bandwidth (the information-carrying capacity of the


network), it is important to acknowledge storage and network speed limitations. This
issue is still very relevant as people may be accessing the internet via dial-up (slow),
mobile networks (variable), broadband or fibre optic.” Be conscious of the file size, at least,
make the effort to compress it. Downloading large files take time especially with low connectivity.

Rule 5: Make Yourself Look Good Online: “Make sure you are careful with what you
share. It is always advisable not to share anything embarrassing, illegal or
inappropriate.” Most of the hiring right now, loks into the public profile of their applicants to
check for their public image. “ People you have not even met may look you up online. Make sure to
always have a good impression and avoid undesirable postings or shares. Check your grammar
when posting and fact-check links when sharing.

Rule 6: Share Expert Knowledge: “Sharing is one of the principles behind the majority of
internet services. If you are knowledgeable in an area then you have something to
offer!” This is specially useful in community sites like, programming enthusiasts, animal/plant
lovers, or reasearch groups. You can share what you know to include the mistakes that you have
made. “You should never post anything disingenuous online. In the online environment, it is very
easy for untruths, errors and mistakes to become accepted as fact and propagated. You have
responsibility to ensuring the accuracy of your contributions. If you are sharing opinion or ideas,
make sure it is clear to your audience.”

Rule 7: Keep Disagreement Healthy: “People are always going to disagree and that is
healthy.” As a digital citizen, you will be interacting with people from different backgrounds,
cultures, gender, and all other human facets, and people will have different ideas and opinions.
Maintain respect even during disagreements. “Never reduce the discussion to personal issues and
avoid inappropriate language. If you are going to provide negative comments, ensure they are
constructive and useful.”

Rule 8: Respect Other People’s Privacy: “When you are networked to someone on a
website like Facebook or LinkedIn, you may be given privileged access to information
about him or her and what he or she shares. You need to ensure you do not breach

44 |Pag
e
Computer Fundamentals and Programming Using Python

anyone's wishes by sharing any of the content they have made available to you.” The law
and basic ethics will tell you that you are not to use or share someone’s personal information
without their consent.

Rule 9: Don’t Abuse Your Power: “If you are an administrator or facilitator for any
online environment, make sure you do not abuse the privilege of access that your
position may give you.” You are tasks to set decorum to the community.

Rule 10: Be Forgiving of Other People’s Mistakes: “People will make mistakes when
they are new to online environments. Everyone has to start somewhere, so try and be
forgiving of other's mistakes.” This relates to the very first rule of being human. Some people
are still navigating and needs assistance.

So, are you following this principles of Internet Etiquette? Or are you one of those practicing bad
netiquette? At some point, we might have applied bad netiquette but these rules should always be
ur constant reminder as digital citizens.

Here are some useful additional links that can help you communicate well online:
• 10 Netiquette Guidelines Online Students Need to Know, Asheley Brooks (January 28,
2019) avaiable here: https://www.rasmussen.edu/student-experience/college-life/netiquette-
guidelines-every-online-student-needs-to-know/
• Social Media: A beginner’s guide, Digital Student, University of Hull available here:
https://libguides.hull.ac.uk/digitalstudent/beginnerssocialnetworks
• Email Basics, GCFLearningFree.org available here:
https://edu.gcfglobal.org/en/email101/introduction-to-email/1/

Exploring the Internet

As we have mentioned at the start of this section, the rise of the users are in billions(!) and the
amount of resources and information online are countless, remember how many search results did
you get on our Google search? It will take a lifetime or more to read all those results. It is therefore,
wise to know the techniques and strategies of getting relevant information on the net.

The following are the Internet basics that you need to know when you explore the web (GCF
LearnFree.org, 2020):
• Connecting to the Internet: First and foremost, you have to “connect” or else you will be
left “offline”. You will need an access device (i.e. a computer or mobile phone), a means of
connection (e.g. WIFI, LAN, WAN, telephone line, cable hookup), and an Internet Access
Provider or ISP (e.g. Globe, PLDT, Smart, SkyCable). In most cases, the means of connection
is already provided by the Internet Access Provider.
• Understanding the Cloud: Imagine a cloud hanging over your head? Well, the popular
“cloud” was figuratively taken there. Which means that you can access or store any of your
data like it is a cloud hanging over your head. Cloud is simple the Internet, or specifically,
the Internte servers.
• Using a Webserver: A web browser is a type of application software that allows you to find
and view websites on the Internet. The most common Internet browsers include Google
Chrome, Mozilla Firefox, Chromium, Safari, Microsoft Edge, or Internet Explorer.
• Understanding Hyperlinks: Hyperlinks are used to navigate the Web. These are the
words that look the different from the rest of the text, something like this. When you click a
link, it will take you to a different webpage. In the example below, we're clicking a link to
learn more about the Dupont Circle neighborhood.

45 |Pag
e
Computer Fundamentals and Programming Using Python

• Downloading and Uploading: Downloading means receiving data or a file from the
Internet on your computer. Uploading means sending data or a file from your computer to
somewhere on the Internet.
• Using Search Engines: Search engines, like Google.com and DuckDuckGo.com, allows to
easily search information on the Internet using keywords.

Go through each these Internet basics here: https://edu.gcfglobal.org/en/internetbasics/.


A video tutorial for each topic is included for your guidance. The Internet Basics tutorial is
designed by GCF Global.

Societal Issues and the Future of the Internet


Throughout this section, we were able to utilize the different application software using our devices
and explore the information available in the Internet. According to Harold Gilliam (2003 cited in
Williams and Sawyer, 2011), “computers have invaluable uses for specialized work but we need to
question the assumption that whatever ails modern society can be cured by more information.” He
further states that many users “are hypnotized by the computer’s power to summon
endless arrays of facts—information without context, data with-out values, knowledge
without perspective.”

The rise of technology certainly changed our way of life which affects society as a whole and, in
turn, raises a lot of issues. How does fake news affect the perspective and perception of people?
Are you comfortable with individuals snooping at your public profile? Or someone pretending to
you on the social media accounts? These are just some of the questions that needs reflection when
we talk about the effects with the advancements in technology.

Williams and Sawyer (2011) identifies the following societal issues that arises from the use of the
Internet:

• Truth Issues (i.e. manipulation of sound and images in digital data): “The ability to
manipulate digitized output—images and sounds—has brought a wonderful new tool to
art. However, it has created some big new problems in the area of credibility, especially
for journalism. How can we know that what we’re seeing or hearing is the truth?” Truth
issues are also evident in the deliver of news or historical revisionism. How can you
distinguish an authentic newstory or article from fake news? This could swayed people’s
believes, ideas, and/or opinions for the benefit of an individual or organization.

• Security Issues (i.e. accidents, natural hazards, terrorism hazards, and crime): “Internet
users just don’t have “street smarts” about online safety, one survey found, and that makes
them vulnerable. And another study suggested that while users think they are able to
recognize when they are being manipulated, either legally or illegally, in fact they are quite
naïve. As one might expect, most Americans now believe that the government should do
more to make the internet safe, even though they don’t trust the federal institutions, such
as Congress and the Federal Trade Commission, that are responsible for creating and
enforcing the laws online.” One must be able to know how to protect itself from fraud or
cybercrimes. ut there is much that we as individuals can and must do to protect our own
security.

Go know more about the guidelines on Internet Safety, visit this tutorial:
https://edu.gcfglobal.org/en/internetsafety/. A video tutorial for each topic is included
for your guidance. The Internet Safety is designed by GCF Global.
46 |Pag
e
Computer Fundamentals and Programming Using Python

Currently, the Philippines has also two (2) key legislation or laws that aims to protect
inviduals from cybersecurity crimes as well as protect data privacy:
• Data Privacy Act of 2012 (RA 10173) available here: http://dict.gov.ph/wp-
content/uploads/2014/07/RA10173_DataPrivacyActof2012.pdf
• Cybercrime Prevention Act of 2012 (RA 10175) avaiable here:
http://dict.gov.ph/wp-content/uploads/2014/07/RA10175_CyberCrimePreventionActo
f2012.pdf

• Quality-of-Life Issues (i.e. environment, mental health, child protection, the workplace):
“What environmental concerns are created by information technology?” Apart from the
obvious use of electricity (i.e. consumption of more power), “many other environmental
challenges remain—for example, manufacturing and usage by-products, disposal by-
products, environmental pollution, and possible risks of nanotechnology”.
“What problems with isolation, gambling, and stress can derive from information
technology?... Automation allows us to go for days without actually speaking with or
touching another person, from buying gas to playing games.” Ironically, when someone gets
“online”, do you “get connected” or “disconnected” (i.e. isolated from the real world?). In a
Standford survey conducted by Norman H. Nie (Ibid) be predicted that “as internet use
becomes more widespread, it will have an increasingly isolating effect on society.” Other
issues that affect the quality of life is the proliferation of cyberbullying and child
pornography. In the Philippines, these are considered cybercrimes and are punishable under
the Cybercrime Prevention Act.

• Economic and Political Issues (i.e. employment and the haves/have-nots): “How may
technology affect employment and the gap between rich and poor?” The innovations in
technology, such as automation and robotics, brings a lot of opportunities to create a more
efficient society. However, these opportunities mean that some jobs are replaced by
machines or bots, in the case of automated customer service. The counterargument of this
is that new jobs are created, especially in the engineering and IT sectors to include system
designers, data anaysts, robotics engineers. According to Stewart Brand (Ibid), “if your job
has been replaced by a computer that may have been a job that was not worthy of a
human.”

“What is the “digital divide”?” In this age of technology, when gadgets is a norm, we tend
to forget that there are still individuals, in particular people living in Third World Countries,
who can not afford to have one. In this perspective, this technology only brings
opportunity to some while a disadvantage to others. How do we address this digital divide
in our society while embracing the progress of innovations?

REFLECTION: Have you encountered some of these issues? How are you able to handle it?
Are there other issues related to Information Technolgy that you or someone else have
encountered?

What is the Future of the Internet?

Mark Weiser (1991) said it wisely, “the most profound technologies are those that disappear. They
weave themselves into the fabric of everyday life
until they are indistinguishable from it.” The innovations of the current Industrial Revolution 4.0
that includes the Internet of Things (IoT) and artificial intelligence has already weave into our
society. From GPS-tracked devices, internet-controlled home appliances, or simply chatbots, has
been, in more than one ways, part of our daily life or routine.
47 |Pag
e
Computer Fundamentals and Programming Using Python

Rayome (2019) has list down the following top 10 emerging tehnologies of 2019:
• Internet of Things (IoT) • Robotics
• Artificial Intelligence • Biometrics
(AI) • 3D Printing
• 5G • Virtual Reality (VR) / Augmented Reality (AR)
• Serverless computing • Drones
• Blockchain

How much do you know of these emerging technologies? You can start by reading Rayome’s
article here https://www.techrepublic.com/article/top-10-emerging-technologies-of-2019/. You can
also search for each technology using any of the search engines available to you.

This wil help you get an idea what you can do for your future engineering design projects.

See if you can do this!

In your previous activity, you know that one single topic can bring in millions of test results. This
shows you a glimpse of how much information is out in the Internet cloud. How about you
contribute some of your insights and thoughts with the world?

1. Creating Personal Website using Google Sites


• Create your own personal page using Google sites! A step-by-step procedure written
by Allie Decker is available here: https://blog.hubspot.com/website/google-sites-
tutorial. IMPORTANT NOTE: Use your WMSU Gmail account to avail this feature of
Google.
• Choose a Portfolio template.
• Explore and design! Change the images and organize your menu and content.
• Have at least (2) categories: About Yourself and Reflections. You can add more if
you wish.
2. Create Your Content
• About Yourself must contain a page based your written output from your
word processing software activity.
• For the Reflection, answer the questions below and create a page that will contain
your insights. You can create separate pages for each question or just a page. You
can be creative as you want! Here are the questions
? How much do you value freedom of speech or expression in an online platform?
Should your ideas or opinions be censored by the government?
? What do you think is the negative effect of using computers? How can you
address these problems?
? How can you ensure that the information you share is accurate and complete?
? As future engineers, what innovations do you think the world needs right now?
3. Share Your Site
• Submit your link to the instructor and share your content to the class. [Optional] If you
have your social media account, you can also share your personal page for your
friends to see and enjoy reading your thoughts.

48 | P a g e
Computer Fundamentals and Programming Using Python

II. Introduction to Computer Programming

What is a Computer Program?

In today's environment, the use of technology and computer applications is everywhere! Most of
these technologies are run by computer programs. Every single day, you encounter some of these
computer programs. Let’s have a look at some of the most common computer programs that are
available right at your fingertips!

Objectives:

At the end of this section, you should be able to:

1. Describe what computer programs are.


2. Discuss what computer programming is and describe how computer programs are executed
in a computer
3. Identify the basic steps in designing a program and demonstrate understanding by writing
clear and detailed instructions for a procedure.

Topic Outline:

1. What is a computer program


2. Understanding the concept of computer programming
3. Understanding how a program runs in a computer
4. Techniques in Program Design

49 | P a g e
Computer Fundamentals and Programming Using Python

Try This!

Identify at least two (2) gadgets that you own personally or at home. It could be your
cellphone, mp3 player, or your desktop computer or laptops. Think of some of the
things that can be done with these devices.

Think Ahead!

Do you own a cellphone? If so, list at least two (2) things that you do with your cellphone?

List some of the applications you use in your cellphones.

Have you ever tried using desktop computers or laptops? If so, list at least two (2) things that you
do with your desktop computers or laptops.

List some of the applications you use in your desktop computers or laptops.

What are the other devices that you have identified? List at least two (2) things that you do with
these devices.

Most of the activities that you do with these devices like sending a text message, answering a call,
playing games, or checking your latest newsfeed on your Facebook account are made possible
with the use of computer programs. Your games, websites including Facebook and Twitter and
other applications that you use are already using are just simple examples of computer programs.

50 | P a g e
Computer Fundamentals and Programming Using Python

Read and Ponder!

Computer programs consist of a sequence of instructions or steps that the computer interprets and
executes. A single application, like Facebook, can consist of several small computer programs.
When you log-in, for instance, based on your username / e-mail address, the program will check if
you are a registered user. The program will also verify if your username and password match based
on the password that you also registered.

Ever played DOTA, HON, or Counter Strike? These role-playing and strategic games are also
examples of computer programs. The movements of the characters change of environment and
collection of items and scores consist of sets of instructions or collection of smaller programs.

Looking at these applications, you might think that they are complicated and time-consuming and
only the geniuses can develop. Well, they may be true except for one thing: even YOU can develop
a computer program as big as Facebook or as fun as DOTA. But we will start with creating small
programs first and progress later on. So, put on your thinking caps! This module will help you
create programs which can become big in the future.

What is Computer Programming?

Have you ever wondered how a simple click of a mouse lets your favorite character in your game
to move? Or how the arrow keys allow Pac-man to move from up, down, left, & right? It is because
programmers (or at least the programs they designed) have written specific instructions for these
behaviours to happen. A computer program is composed of a sequence of instructions, and these
instructions are written by the programmers including YOU in the future.

For now, you should be able to realize that computers are only as good as the programs that have
been created for them. They only do what they are told to do. That is, they only behave based on
how the computer program behaves or were designed and programmed.

Try This!

Have you ever played a computer game or game using your phones? This is your chance to get
into your fun side! For this activity, play the game that you enjoy most. Make sure that you
have read the instructions and how you will get the best scores.

51 | P a g e
Computer Fundamentals and Programming Using Python

Think Ahead!

What is the name of the game?

List down the steps or instructions on how to play the game:.

How do you get a score?

Did you enjoy the game? Did you get the highest score? You might observe that scores differ
based on how well you played the game. The program is written in such a way that you get higher
scores on certain moves or actions.

Read and Ponder!

Computer programming is simply describing the steps or writing down the steps to do something.
It is like solving a puzzle or cooking a meal. However, since the computer does not understand
English or any other human language, a specific programming language is used.

The programmer writes the instructions (called “source codes”) in the computer using a
programming language. There are numerous programming languages that can be used. Some
have specific targets and run only on particular computers. The set of source codes are also called
program code.

52 | P a g e
Computer Fundamentals and Programming Using Python

Figure 2.1 below shows the difference between instructions written English language and written as
program code. Throughout this module, you will learn how to create source codes using Python
programming language.

Steps in English language Program Code (in Python language)

1 Start
2 Output message “Hello
World!” print(”Hello World!”)
3End

Figure 2.1 Sample Program Code

However, it should be noted that the only language that the computer understands is machine
language, which only contains the characters 0 (represents OFF) and 1 (represents ON).

After the programmer writes the source codes in high level language (in programs like Python, C+
+, etc), the codes will be interpreted and translated into machine language (which is now what
we call the executable file and typically with . exe extension).

Figure 2 illustrates how the program code is executed in the computer.

Figure 2.2 Concept of Running a Program adopted from (Rippe, 2009)

53 | P a g e
Computer Fundamentals and Programming Using Python

Process of Program Design

You know by now that programs are just series of steps or instructions which you want the
computer to do. So, if you want to teach your friend how to bake a cake, you just have to give your
friend the recipe or the sets of instructions on how to do it. This means anyone, including YOU, can
write programs!

There are two (2) major phases that you go through when creating your program: (1) The Problem
Solving Phase and (2) the Implementation Phase.

The Problem-Solving phase is where you define the problem and identify the sets of instructions
on how you are going to solve the problem. For the above example, the problem is baking a cake
and the instruction is the recipe. In this phase, you are going to create algorithms and flowcharts
for the steps that you identified.

The Implementation Phase is where you convert your instructions to a series of source codes using
a programming language. For this course, we will be using Python as our programming language.

For each phase, you have to do simulations or tests to be able to verify if you have successfully
solve the problem at hand.

No matter what programming language you are going to use in the future, the solution or
instructions that you are going to create will be the same. Therefore, the key to creating a good
program is to be able to write specific and detailed sets of instructions that will be a clear solution
to the problem at hand.

See if you can do this!

Let us exercise your skills in writing step-by-step instructions. Remember the process you go
through during enrolment for this semester? Write down a detailed step-by-step procedure of the
enrolment process. Note: Write the procedure as if you are giving instructions to incoming WMSU
freshmen students.

Step No Instructions / Procedure


1

2
3
4
5
6
7
8

54 | P a g e
Computer Fundamentals and Programming Using Python

I
10

55 | P a g e
Computer Fundamentals and Programming Using Python

III. Introduction to Algorithm Analysis and Design

Concept of Algorithm

What comes to your mind when you hear the word “algorithm”? Robots? Mathematics? Science-
fiction? Did you know that algorithm exists every day in our lives? Signing into your Facebook or
Twitter accounts… changing the battery of your cellphones… ordering in a restaurant… or simply
baking a cake. What is common among all these? All of the things mentioned require us to follow a
series of steps before we can accomplish what we want to do. This sequence of steps to reach a
goal or achieve a desired output is called an algorithm.

Objectives:

At the end of this module, you should be able to:

1. Create algorithms for solving problems using simple English.


2. Express simple algorithms in a pseudocode form.
3. Express simple algorithms using flowcharts
4. Analyze and simulate pseudocodes & flowcharts

Topic Outline:

1. Understanding the concept of Algorithm


2. Writing Algorithms in Pseudocode format
3. Writing Algorithms in Flowcharts format
4. Algorithm Simulation

Try This!

Assuming you are the cashier in a grocery store and your customer orders 2 cartons of milk
worth Php90 each and 1 loaf of bread worth Php25. Your role now is to determine the total
amount that your customer needs to pay for the goods he wants to get.

56 | P a g e
Computer Fundamentals and Programming Using Python

Think Ahead!

What are the data or values needed to solve this problem?

Given the values, determine the steps to determine the output of this problem.

No. Steps
1

2
3
4
5
6

Now, you have just written your first algorithm! Isn’t it easy?

The data or variables that are needed and asked in the problem are the following:

Inputs: Price of milk, Price of bread, Number of cartons, Number of loaves of


bread
Output: Total Amount

There are many ways to write the algorithm for the example given. Is your algorithm similar to the
one below?

1 Input Price of milk = 90, Price of bread = 25


2 Input Number of cartons = 2, Number of loaves of bread = 1
3 Compute Total Price of Milk = 90 * 2
4 Compute Total Price of Bread = 25 * 1
5 Compute Total Amount = Total Price of Milk + Total Price of Bread
6 Output Total Amount

If your steps are similar above, you are very close to creating a good algorithm! Good job!

57 | P a g e
Computer Fundamentals and Programming Using Python

Read and Ponder!

Like the previous example, a typical algorithm has inputs, outputs, and a step-by-step process.
Your inputs are the values needed to solve the problem, and your outputs are the desired data or
values. In algorithm design, inputs are processed through a series of steps and an output is
produced.

Input Process Output

Figure 3.1 Example of a Typical Algorithm

Algorithms can be written and expressed in different ways. In programming, an algorithm can be
described in the form of a pseudocode or a flowchart. Pseudocodes do not follow any particular
computer language and are written in simple English. Sometimes, they contain common
mathematical expressions like =, *, +, -, and others. Some statements will test a condition
(if..then..else) and branch to a different part in the algorithm. Flowchart, on the other hand, uses
symbols in describing the steps. We first try to create algorithms in simple English which is more
familiar to you.

Designing Algorithms using Pseudocodes

Let’s say you are asked to write an algorithm for computing the area of the rectangle. First, identify
the needed input variables and expected output of this algorithm:

Inputs: length, width


Outputs: area of the rectangle

Below are the possible algorithms that you can create from this problem. Note that the words in
bold letters are the sets of variables either as inputs, outputs, or other computed values.
inputs

1 Input length, width


process 2 Compute area = length * width
3 Output area
outputs

Figure 3.2 Simple Algorithm with inputs and


outputs
58 | P a g e
Computer Fundamentals and Programming Using Python

In order to check if the algorithm solves our problem, you can simulate or test the steps that you
have created. To simulate, you can assign actual values to the input variables and follow the series
of steps that you have outlined to see if your algorithm accomplishes what it is supposed to do.

Sample Simulation. Assume that the length and the width of the rectangle are 10 and 8,
respectively.

Algorithm Simulation

1 Input length, width Input length = 10, width = 8


2 Compute area = length * Compute area = 10 * 8 = 80
width Output 80
3 Output area

You can test this further with other values. To be able to write an effective algorithm for a program,
identify the following characteristics that a good pseudocode must have (Balci et.al., n.d.):

1. Algorithms are well-ordered.


2. Algorithms have unambiguous operations. Steps are clearly defined and leave no room for
misinterpretation.
3. Algorithms have effectively computable operations
4. Algorithms produce results.

See if you can do this!

Algorithm Exercises 1

1. To enhance your knowledge in creating algorithms, group yourselves with 5 members


for every group. List each member’s scores from the last quiz. Write a general algorithm
for finding the average of the scores of five (5) individuals and output the computed
average. After you write the algorithm, test it with the scores that you listed as inputs.

No Steps
.
1

2
3
4
5
6

59 | P a g e
Computer Fundamentals and Programming Using Python

I
8
9
10

2. Using the same algorithm, individually simulate the steps using a different set of values.
Are the results of your algorithm correct? If yes, then you have created a well-written
algorithm. Good job! If not, you can analyse the problem again and refer to your
instructor for the correct answer.

Designing Algorithms using Flowcharts

Did you know that symbols can also be used as instructions? Have you seen some signs on the
streets and roads? The name and numbers of the streets… the left & right arrow directs… etc.
These signs are guides to places where you want to go. Isn't it easy to have a map with you when
you try to get to somewhere? Applications like Google maps can even tell you how fast you can go
to that place whether you will use a car, a bus, or just simply walk. Using a map, you will know
whether to go left or right.

From the previous section, you have learned how to create algorithms using pseudocodes. Now,
just like a map, you are going to use symbols to describe your instructions or algorithm.

Try This!

Review the scenario of the cashier in a grocery store. Also take note of the pseudocode that you
have created from that scenario. Using the symbols in Table 1, substitute your instructions with
the symbol it represent.

Table 3.1 Basic Symbols used in Flowchart


SYMBOLS DESCRIPTION
Start/End
The terminator symbol marks the starting or ending point of the system. It usually

Action or Process
A box can represent a single step ("add two cups of flour"). A step could also mean

Input/Output
Represents material or information entering or leaving the system, such as custom

60 | P a g e
Computer Fundamentals and Programming Using Python

Flow Line
Lines indicate the sequence of steps and the direction of
flow. It is used as a symbol to connect one symbol to the
next.
Decision
A decision or branching point. This may include
conditions like if and if-else. The points in the diamond
will represent the results or decision of the condition
(such as Yes/No) and which step it will take next based
on the decision.

Think Ahead!

1. Use the table below to draw up your flowchart. The pseudocode on the left is based on the
previous algorithm that we created. Draw the corresponding symbol for each line on the
right column. Note: The use of the terminator symbol is already included at the start and
end of the algorithm.

Line No ALGORITHM (using Pseudocode) FLOWCHART SYMBOL

1 Start Start

2 Input Price of Milk, Price of Bread

Input Number of cartons, Number of loaves of bread


3

4 Compute Total price of milk

5 Compute Total price of bread

6 Compute Total Amount

7 Output Total Amount

End
8 End

61 | P a g e
Computer Fundamentals and Programming Using Python

2. Draw the final flowchart for the algorithm by connecting all the symbols using the flow line
symbol.

YOUR FINAL FLOWCHART

Great! You have successfully created your first flowchart! Verify with your instructor if your
flowchart is similar to the equivalent flowchart for this algorithm.

Read and Ponder!

From the previous activities, you have learned that algorithms can be written either using
pseudocode or using symbols through flowcharts. Basically, flowchart is just a graphical
representation of an algorithm. You can say that flowchart is also an algorithm, in graphical
format.

In the previous flowchart, you have used symbols such as rectangles, oblongs, and rhombus. These
symbols describe the various operations (or instructions) in your algorithm. These symbols are
connected with arrows to indicate the flow of data or operations from one instruction to the next.

Let's take the problem on computing for the area of a rectangle. You know that you can write your
algorithms in multiple ways. Below, you can see how each algorithm can also be designed using
flowcharts.

62 | P a g e
Computer Fundamentals and Programming Using Python

Algorithm:

Line No Using Pseudocode Using Flowchart

1 Start
START

2 Input length, width Input length, width


For this symbol, you need to indicate if the
data or value is either an “Input” or “Output” data.
area = length * width
3 Compute area = length * width

For this symbol, no need to indicate “Compute” since the box

4 Output area Output area

END

5 End

The above flowchart uses the three (3) most basic symbols in flowcharting. These symbols are
mostly present in any program or flowchart.

See if you can do this!

Algorithm Exercises 2

Now, let us test your skills in writing algorithms. Identify the inputs and outputs for each problem
and create the algorithm using pseudocode and flowchart.

Problem: Create an algorithm that computes for the student’s final grade using the formula below:

FINAL GRADE = 40% (Midterm Grade) + 60% (Final Grade)

Input/s:
Output/s:

63 | P a g e
Computer Fundamentals and Programming Using Python

Algorithm:

Line Pseudocode Flowchart


No

64 | P a g e
Computer Fundamentals and Programming Using Python

IV. Introduction to Python Programming Language

The Beginnings of Python

You know by now that programs are just made up of sets of instructions. However, the computer
will only understand your instructions if it is written in a programming language. Different
programs can be written in different programming languages.

The most popular programming languages include Python, C++, Java, and C# among others.
Maybe these terms sound a bit alien to you for now. In the field of computer science, these are
common terms and soon will also be common terms to you. For this subject, we are going to use
Python.

Python is an interpreted programming language. It was developed by a Dutch programmer, Guido


Van Rossum. He wrote Python only as a hobby programming project back in the late 1980’s.

Python can be used to develop WEB Applications, Scientific and Numeric computing, GUI
Programming, Software Prototyping and Professional Trainings.

Why learn Python programming?

Python is a non-restrictive programming syntax. It has no explicit declaration. It is a state of the art
Object Oriented Programming Support and a powerful debugging.

Objectives:

At the end of this section, you should be able to:

1. Write your first “Hello!” program using Python environment


2. Run a program in Python
3. Create a simple Python program based on a given problem

Topic Outline:

1. The Beginnings of Python


2. Programming using Python
3. Basic Programming Terms
4. Layout of a Python Program

65 | P a g e
Computer Fundamentals and Programming Using Python

Programming Using Python

Let’s go back at what you have learned when creating your algorithm. You know that an algorithm
is just a set of instructions or a series of steps. So, when you create your algorithm and you think of
the series of steps to solve the problem, you are actually thinking of the procedure. This is what
we call procedural programming (also known as structured programming).

Python is actually a type of a structured programming language. Hence, it is very important that
you know how to write your algorithm, either in pseudocode or flowchart, before you write your
program. These instructions in your algorithm will already be equivalent to your program code,
also known as your source code.

Try This!

In this activity, your instructor will introduce you to the Python environment. You will be
demonstrated how to CODE and RUN your first program. For your first program, take note of the
following steps:

1. Write the program code below in your first Python file. NOTE: Do not anymore include
the line numbers. The numbers are only used to reference the line of codes in your
program.

1 x = input (“Enter your Name : “)


2 print (”Hello”,x)

2. Save your file as “Hello.py”.


3. Run your program. Consult your instructor when you encounter some errors.

Think Ahead!

1. When you run your program, what message was displayed?

2. Did you encounter some errors when you run your program? If so, what error message/s
was/were displayed?

66 | P a g e
Computer Fundamentals and Programming Using Python

3. After you successfully run your program, what output message was displayed?

Good job! You were now able to write your very first program! This time, you can do a little
modification to your program. Try to change “ Hello ”, x to “ Hello ”,x,” ! Hello, World! ”.

4. What is the new output message displayed?

5. How about this, change “Hello”,x,”! Hello, World!” to “Hello”,x,”! \nHello, World!”.
What is the difference between the previous output and the latest output message?

6. Add the following line of codes after Line 2 print “Hello”,x,”! Hello, World!”

print(”This is my first Python application”

7 What is the new output message displayed?

The “\n” is just one of the most common characters that you will be using when implementing your
programs. Any characters after “\n” will be written on the next line. Another way is to create
another print statement.

As you can see, the output of your program clearly depends on what you write on it. So, if you
write your
program incorrectly, then you will also get an incorrect output. We call this as GIGO or
Garbage In, Garbage Out.

Hence, it is important to simulate first your algorithm, to check whether it is ready to be


implemented in Python. From now on, aside from creating algorithms, you will also be using the
Python environment, so start getting comfortable with it! As for your first program, great job!

Read and Ponder!

The Hello! program that you have created follows the basic structure of any Python program code.

There are two (2) basic important things that you should be aware of when writing your
program code. First, Python program is case-sensitive. This means that the commands should
follow the character cases properly. For instance “print” in Line 3, should not be written as
“Print” or “PRINT”. Changing the cases, lower case to upper case or vice versa, will be
equivalent to a program error.

67 | P a g e
Computer Fundamentals and Programming Using Python

Second, Python is using a different principle. Instead of using certain characters or keywords in
grouping statements (e.g. {} for c / c++ and java, begin…end for pascal), block of codes in Python
are defined by indentation, which make Python program be structured.

All statements in-lined to the right belong to the same block of code, this means that statements
lined-up vertically belongs to the same block.

Basic Programming Terms

Before we proceed to the actual implementation of the functions and commands, we first have to
take a look at some of the terms used in programming languages.

o Reserved Words. These are words that are already used by the programming
language (C++). These words have special meaning to the language. Therefore, you cannot
use reserved words as your variable or identifier (see meaning of identifiers).

In our Hello, World! program, the reserve words are the following: input and print.

o Identifiers. These are names used to reference variables, functions, labels, and
various other objects that you define in your program. In creating identifiers, you must
consider the following:

• contains 1 to 32 characters
• first character must be a letter (a-z, A-Z) or an underscore (_)
• subsequent characters can be either letters (a-z, A-Z), numbers (0-9), or
underscore (_)

Examples of valid identifiers: count, _player1, first_player

Examples of invalid identifiers: !count, player.1, first..player

NOTE: Again, Python is case-sensitive, this means that lowercase characters are
considered different from their uppercase equivalents, that is, a is different from
A and count is different from COUNT.

o Syntax. It is the format or structure on how the source codes should be written.
There are certain rules that you should follow in writing your source codes for a particular
function.

o Semantics. In order to understand the syntax, you always refer to the semantics.
The semantics gives meaning or description to your syntax. It is important to take note of the
semantics, so that you will understand the syntax better.

You will encounter different syntax and semantics once you already start using different commands
and functions.

68 | P a g e
Computer Fundamentals and Programming Using Python

See if you can do this!

Programming Exercises 1

The algorithm below displays a given text. Create the equivalent Python program code for
this algorithm.

Algorithm Program

1 Start
2 Output message “It’s
more fun to learn
programming in using Python”
3 End

What will be the output for this algorithm?

Program Output:

Programming Exercises 2

Create an algorithm, either using pseudocode or using flowchart that will output your name,
course, and motto in life. Write the equivalent Python program for this algorithm. As your
guide, see the sample output below.

Sample Program Output:

Name : Bella Swan-Cullen


College: Engineering
Motto : Live life to the fullest
69 | P a g e
Computer Fundamentals and Programming Using Python

Your Program:

Algorithm Program

70 | P a g e
Computer Fundamentals and Programming Using Python

V. Python Basics

Variables, Input/Output Streams, and Assignment Statements

Most of the programs, just like Facebook, require the user to input certain data or information
before you can log-in or before you can search people from your friend list. And just like our
sample problem on the area of a rectangle, most other programs require certain computations and
validations. And besides, it would be a boring program if it will only display what you just typed.
Wouldn’t you agree?

Now, in order to be able to do some data entry and computations, you have to learn how to use
variables and assignment statements.

Objectives:

At the end of this section, you should be able to:

1. Use variables to store, manipulate, and retrieve data inputs.


2. Use different arithmetic operations and expressions in a Python program.
3. Create a Python program with computations based on a given problem.

Topic Outline:

1. Variables Declarations, Input/Output Streams, and Assignment Statements


2. Variable Initializations and Constants
3. Data Types
4. Arithmetic Expressions

Try This!

Say you are in a money changer business. One of your customers wants to convert a
100 US dollar bill to Philippine pesos. Assuming that $1 = PHP 41, how much will your
customer receive in exchange for his 100 US dollar bill?

71 | P a g e
Computer Fundamentals and Programming Using Python

Think Ahead!

1. What do you think are the inputs and outputs for this

problem? Input/s:
Output/s:

2. Assign names to your inputs (input variables) and outputs (output variables). Using these
variable names, create a formula that will be able to covert US dollar to Philippine Peso.

Input Variable/s:
Output Variable/s:
Formula:
Let us check if your variables are correct identifiers to be used in your program. The
following questions will determine if you have written a correct identifier or not:

• Does your variable name contain 1 to 32 characters?


• Is the first character of your variable name a letter (a-z, A-Z) or an underscore (_)?
• Are the subsequent characters (i.e. after the first character) in your variable
name contain either letters (a-z, A-Z), numbers (0-9), or underscore (_)?

If you answered “Yes” to all the questions above, then you can already use these variable
names into your program. Otherwise, you have to change your variable names to fit into
these criteria.

3. Once you already have your variable names, create the equivalent algorithm for this
problem. Your algorithm must be able to produce similar to the sample outputs below.

Sample Output 1:

MONEY CONVERSION This is a sample input.


For your algorithm, use
Bill in US dolla ($):1 Philippine Peso (PHP): 41 the input and output
variable names.

72 | P a g e
Computer Fundamentals and Programming Using Python

Sample Output 2:

Write your algorithm here:


MONEY CONVERSION
MONEY CONVERSION
Enter amount in US Dollar ($): 3
Equivalent in Philippine Peso (PHP):
123

73 | P a g e
Computer Fundamentals and Programming Using Python

You know by now that there are multiple ways to create your algorithm. In your output
messages, you can even write the texts in your own language (Tagalog, Chavacano, Bisaya,
etc.). If your algorithm is similar to the table below, then, great job!

Line No Algorithm

1 START
2 Output message “MONEY CONVERSION”
3 Output message “Enter amount in US Dollar ($): ”
4 Input dollarAmount
5 Compute pesoAmount = dollarAmount * 41
6 Output message “Equivalent Amount in Philippine Peso (PhP): ”
7 Output pesoAmount
8 END

Read and Ponder!

Are you ready to create programs that actually interact with the user? Right now, you have
already written algorithms that actually do this… but not yet an actual program. Most programs
that you are going to write will now contain the basic components: Inputs, Process, and
Outputs. Let’s take a look at these components on the Money Conversion algorithm.

OUTPUT STREAMS. On the previous activities, you created programs that display messages
using the print() statement. For this algorithm, you can use the print() statement to display
the texts or messages.

print() statement: command used to display text on the screen or display the
value of a certain variable.

The table below shows the format on how you are going to use print() statements. The syntax
shows the format, while the semantics shows the meaning of the format.

Output Streams
To display a text:
print(”write text here”)
To display the value of the variable:
Syntax print(identifier)
To display both value of the variable and text in one line:
print(”Value of data is ” , identifier)
You can write the text that you want to display inside the quotations.
Semantics
Identifier : variable_name

74 | P a g e
Computer Fundamentals and Programming Using Python

Using the syntax for Lines 2 & 3, the equivalent program code may be written as

print(”MONEY CONVERSION” )
print(”Enter amount in US Dollar ($): ” )

The “\n” is equivalent to new line, so all texts after “\n” will be displayed on the next line. You
can also write the two statements in one line using “\n”, that is,

print(”MONEY CONVERSION \n Enter amount in US Dollar ($): ”)

Both of these statements will result to this program output:

MONEY CONVERSION
\n Enter amount in US Dollar ($):

For Line 7, you are displaying the value of a variable instead of texts. You can use the same
print statement, but without the quotation marks. Hence, the equivalent program code for Line
7 is

print(pesoAmount)

You can also write both texts and variables in one line. For instance, Lines 6 & 7 may be written
as

print(“Equivalent amount in Philippine Peso (PhP) is ”, pesoAmount)

In this format, only a single print statement is used but it separates the text from the
variable with a comma “ , ”. Assuming that the computed value for pesoAmount is 41, this
line will have the program output below:

Equivalent amount in Philippine Peso (Php) is 41

If you want to add some texts after the pesoAmount, you can write it as

print(“Equivalent amount in Philippine Peso (PhP) is ”, pesoAmount , “.”)

In this code, we added a period after the variable. This line will have this output:
Equivalent amount in Philippine Peso (Php) is 41 .

A variable is an identifier that is used to name and store data values. In other programming
languages, variables must be declared first before it can be used.

The word dollarAmount and pesoAmount are the identifiers or variable names. Make sure
that your variables are proper identifiers.

75 | P a g e
Computer Fundamentals and Programming Using Python

INPUT STREAMS. If Python has print() statement to output texts or values, it also has input
statement to store values into a variable.

Input() statement: sets the variable equal to the values typed in at the keyboard.
In Python, the input statement is the input() function. The input() function has an
optional parameter, the prompt string. The prompt string is being printed
onscreen when the input function is executed or processed.

The table below will show you how to use input() statements.

Input Streams
Input function without parameter
identifier=input()
Syntax
Input function with a parameter
identifier=input(“prompt string”)
Identifier : any valid variable_name
Semantics
Prompt string : stringto be printed onscreen

For the Money Conversion algorithm, Line 4 accepts amount in US dollar and the value
is stored in the variable dollarAmount. Using the input function, the equivalent program
code is:

dollarAmount=input()

This input() function means that the input of the user will be stored or saved in the variable
dollarAmount. With this, you can use the value entered by the user for computation purposes.

ASSIGNMENT STATEMENTS. In the Money Conversion algorithm, a formula is used to convert


or compute for the equivalent amount in Philippine peso based on the US dollar input value.
Writing formulas in program code is very similar to any mathematical formula. In programming
terms, these mathematical formulas are called assignment statements.

Assignment Statements are statements that change the value of a


variable either by computation, operation, or simply assigning a
constant value.

In the conversion formula, an asterisk (*) is used to represent multiplication. In Python, we


also use the same symbol for multiplication (see Table 4.1 Arithmetic Operators). The assignment
statement table below will show you how to a create formula in your source codes.

76 | P a g e
Computer Fundamentals and Programming Using Python

Assignment Statements
Syntax identifier = expression;

Identifier : any valid variable name


Semantics
expression: this could be a constant or any combination of variables, operators, or constan

For this algorithm, the equivalent program code for the formula in Line 5 is:

pesoAmount = dollarAmount * 41;

In this assignment statement, the value of the variable dollarAmount is the value entered
by the user. This value is multiplied by the exchange rate which is 41. The resulting value will
then be stored in the variable pesoAmount.

Note that the formula, in program code, is exactly the same as in the algorithm. Table 4 shows
the arithmetic operators that are used in Python programming.

Table 5.1 Arithmetic Operators


Operat or Function

+ addition
- subtraction
* multiplication
/ division
% modulus (remainder)
** Exponent
// Floor division operator

You can refer to this table when you want to create equivalent assignment statements for your
formula. These operators are very similar to the operators used in a normal algebraic formula /
equations except the modulus, exponent and floor division operator.

The modulus operator (%) computes for the remainder when the two numbers are divided.

For example,
x = 7%6

In the above assignment statement, 7 will be divided by 6 and the remainder will be the value of
x, hence, x = 1. You will use of these operators once you deal with arithmetic expressions.

The exponent operator (**) computes for the value of a number raise to the power of.

For example,
x = 7**6

77 | P a g e
Computer Fundamentals and Programming Using Python

In the above assignment statement, 7 will be raised to the power of 6 and the equivalent value
of x, hence, x = 117649. You will use of these operators once you deal with arithmetic
expressions.

The floor division operator (%) computes for the floored value of the quotient when the two
numbers are divided (decimal point are removed).

For example,
x = 7//6

In the above assignment statement, 7 will be divided by 6 and the quotient will be the value
of x, hence, x = 1. You will use of these operators once you deal with arithmetic expressions.

MONEY CONVERSION PROGRAM CODE

Line no. 1Money Conversion Algorithm Money Conversion Program Code


2 START
Output message “MONEY CONVERSION”print(“MONEY CONVERSION”)
3 Output message “enter amount in US Dollar $ : “
Input dollarAmount Compute print(“enter amount in US Dollar $ : “)
pesoAmount=dollarAmount*41 Output Message “equivalent amount in Philippine Peso (Php): ” Output p
4 END dollarAmount=float(input()) pesoAmount=dollarAmount * 41
56

7 print(“equivalent amount in Philippine Peso


8 (PhP):”)
print(pesoAmount)

The table above shows the Money Conversion algorithm and its equivalent program code.
The lines on the algorithm are translated to input streams, output streams, variable
declarations, and assignment statements.

Try to make some modifications to this code and see how it affects your program. Also, try to
apply the other formats discussed here to see the differences in the outputs. Now, are you
ready to create a program similar to our Money Conversion Problem? Do the next activities to
exercise your programming skills! Enjoy!

78 | P a g e
Computer Fundamentals and Programming Using Python

See if you can do this!

Programming Exercises 3

Write a program (with algorithm) that will compute for the area of a triangle given its base and
height using the formula below. The output can be displayed in whole numbers (using int data
type).
Area of a triangle = 0.5 * base * height

Algorithm Program Code

79 | P a g e
Computer Fundamentals and Programming Using Python

Programming Exercises 4

You are planning to create a new account in a given bank. That bank offers 10% annual interest
rate to its clients. That is, if you have Php 100 in your account, you will have Php 110 after a
year. Write a program (with algorithm) that will allow you to calculate the total amount with
interest rate given the initial value of your account.

Sample Program Output:

BANK ACCOUNT DETAILS


Initial Value (Php) : 100
Amount after a year (Php) : 110
Algorithm Program Code

80 | P a g e
Computer Fundamentals and Programming Using Python

Programming Exercises 5

In an all-veggie pizza delivery company, it takes 15 minutes to make one pizza and 20 minutes
to deliver to their customers. Write a program (with algorithm) that will determine the total
delivery time (in hours and minutes) given the number of pizza being ordered. NOTE: You can
use as many variables as needed to solve this problem. Hint: You can use the modulus
operator to determine the equivalent number of hours.

Sample Program Output 1: Sample Program Output 2:

ALL-VEGGIE PIZZA DELIVERY ALL-VEGGIE PIZZA DELIVERY

No. of pizza ordered : No. of pizza ordered :


1 Total Delivery Time 3 Total Delivery Time
Hours - 0 Hours - 1
Minutes - 35 Minutes - 5

Algorithm Program Code

81 | P a g e
Computer Fundamentals and Programming Using Python

Variable Initializations and Constants

Have you ever heard of constants? In mathematics, you learned that variables, like x and y
and sometimes z, can have different values depending on what values you assign to it.
However, there are some values that are constant. These are values that rarely change and
sometimes never change.
There are a lot of constants around. The number of days in a week never changes. The number
of days in a year changes every after 4 years. In mathematics, the most popular constant is pi
π().Her,youwlibeatonhceyurpvios gambyiplentgvarb). Here, you will be able to enhance your previous programs by implementing variable
initializations and constants.

Try This!

In the previous programming exercises, you were able to use different variables to
assign values from the user (inputs) as well as for computation (assignment
statements). Consider the formula below based from the money conversion problem,

pesoAmount = dollarAmount * 41

identify the possible variables and constants.

Think Ahead!

Based from the given problem, which value in the formula always changes?

Which value remains constant regardless of the given dollar amount value?

Think of other constants that you use in formulas from the field of mathematics, physics,
economics… or just something you see on the market or in the internet. What are these
constants?

82 | P a g e
Computer Fundamentals and Programming Using Python

Read and Ponder!

In the Money Conversion problem, we assign dollarAmount as the US dollar amount input
from the user and pesoAmount as the converted value in peso. However, the number 41 is a
constant that value that we assign for the exchange rate. In programming, we can set this value
as part of the initialization or declared as a constant value.

VARIABLE INITIALIZATION. Variable initializations are used if you want that to already set an
initial value to a variable.

The table below shows the format in implementing variable initializations.

Variable Initialization
Syntax identifier = constant_value;

identifier: this indicates the name of the variable.

constant_value: any fixed value, that is, if the data type is an integer, the value could be any nu
Semantics (see Data Types for more on the size, value, and range of the data
types).

For this problem, you can declare a variable for the exchange rate (i.e. exchangeRate) and
assign 41 as its value. The equivalent program code for this is:
exchangeRate = 41

Using variable initialization, you can write this code in one line like this, exchangeRate = 41

This format already initializes the value of the exchangeRate to 41 upon declaration of the
variable. In your formula or assignment statement, instead of using the actual value (i.e. 41),
you can already use the new variable, that is,
pesoAmount = dollarAmount * exchangeRate;

If you have two (2) exchange rates: dollar to peso and euro to peso rates. Assign a variable for
each exchange rate. Let variables dollarToPeso and euroToPeso represent dollar to peso and
euro to peso rates, respectively. Assuming that 1 USD = Php41 and 1 Euro = Php54. The
initializations for these variables can be written as

dollarToPeso = 41
euroToPeso = 54

83 | P a g e
Computer Fundamentals and Programming Using Python

MONEY CONVERSION PROGRAM CODE (version 2)

Let’s modify our Money Conversion program using variable initializations.

Line no.Money
1 Conversion Algorithm START Money Conversion Program Code
2 Output message “MONEY CONVERSION”exchangeRate=41 print(“MONEY CONVERSION”)
Output message “enter amount in US Dollar $ : “
Input dollarAmount Compute
pesoAmount=dollarAmount*41 Output Message “equivalent amount in Philippine Peso (Php): ” Output p
3 END print(“enter amount in US Dollar $ : “)

4 dollarAmount=float(input()) pesoAmount=dollarAmount * exc


5
7
6 8 print(“equivalent amount in Philippine Peso
(PhP):”)
print(pesoAmount)
As you can see, the rest of the program is still the same. The difference is that a new variable
is created, an initialization is created, and the new variable is used in the formula. Variable
initializations are very useful when you want to set an initial value to the variable. Take note,
initial. It means that the value can still change inside your program.

See if you can do this!

Programming Exercises 6

Money Conversion (version 3): Review the program code for Money Conversion problem.
Modify the program (and algorithm) so that it will convert Dollar to Euro. Assuming that the
following are the given exchange rates:

1 Euro = Php 57
1 US Dollar = Php 49

The exchange rates must be declared as constants and with the initial value above. Other
variables must be declared and initialized to zero. See sample output for this problem below:

Sample Program Output:


MONEY CONVERSION
Enter amount in US Dollar: 100
Equivalent amount in Euro : 85

84 | P a g e
Computer Fundamentals and Programming Using Python

Algorithm Program Code

Try This!

Consider the algorithm below. This algorithm computes for the area of a circle.

1 START
2 Input the radius of a circle
Think Ahead!
3 Compute area of a circle = 3.14 * radius * radius
4 Output area of a circle
5 algorithm,
Given the above END what variables (either input or output) produce or accept a whole
number values?

What variables (either input or output) produces or accepts a real number or decimal values?

85 | P a g e
Computer Fundamentals and Programming Using Python

What variables (either input or output) produces or accepts a real number or decimal values?

As you can see, a simple algorithm can already have multiple types of data. Incorrect type of
data might produce an incorrect data or less precise data. For instance, an area of 1 is not equal
to 1.75.

Read and Ponder!

Not all data values are in whole numbers. Some data values are not even numbers, like your
name, gender, or course. These are data in a form of characters or texts.

Before choosing a data type, it is important to identify its use in the program. If the program
requires a number, determine if it is an integer or real numbers (i.e. decimal values).

The following are the five standard data types used in Python:

1. Numbers
2. String
3. List
4. Tuple
5. Dictionary

In Python, inputted values using the input() function are in String. Before it can be used as
numeric values, it must be converted into a numeric data type. This process is called type
casting.

Type casting is a way to convert a variable from one data type to another data type.

For now, let us just consider data types for number. For number data types, a variable can
either be;
1. int (integers)
2. float (floating point numbers)
3. complex numbers

Let’s try to implement some of these data types into your next exercises.

See if you can do this!

Programming Exercises 7

Write a program that will compute for the area of a circle given its radius. You can refer to the
previous algorithm for the formula. Note: Use the appropriate data type for the variables in this
problem.

86 | P a g e
Computer Fundamentals and Programming Using Python

Program Code

Programming Exercises 8

Money Conversion (version 4): Review the Money Conversion (version 3) from Programming
Exercises 6. Consider the new sets of exchange rates below:

1 Euro = Php 55
1 US Dollar = Php 41

Modify the program so that a more precise data is computed. The program must only accept
whole numbers as inputs.

Program Code

87 | P a g e
Computer Fundamentals and Programming Using Python

Arithmetic Expressions and more Assignment Statements

From the previous activities and exercises, you were able to create and implement formula
through simple assignment statements. You were able to use the arithmetic operators as part of
your assignment statement. However, not all formula is as simple as multiplication or addition
of two numbers. Some formula computes using more than two operators with more than two
variables. These long formulas are called arithmetic expressions. Here, we try to take a look
at different arithmetic expressions and how to implement them in your program codes.

Try This!

Consider the arithmetic expression below:


( ab+ c )
x= d−e
¿ ¿
Think Ahead!

Assuming that the values for the variables are the following:

a = 5, b = 4, c = 10, d = 7, e=2

Show your solution. Determine the steps on how to get the value of x.

Did you separate the computation for the expressions in the numerator from the
denominator? Did you apply the MDAS rule? That’s great thinking! Compare your
answers to that of your classmates and see how you differ in your answers.

88 | P a g e
Computer Fundamentals and Programming Using Python

Read and Ponder!

In most arithmetic expressions, we do not only use a single operator but a combination of
multiple operators. Since we have the modulus operator, we cannot simply use the MDAS
(Multiplication, Division, Addition, and Subtraction) rule. In C++, we follow a certain rule in how
to prioritize the computations in a given expression. We call this the precedence rule.

Exponentation gets done first, followed by multiplication and division (including // and %), and
addition and subtraction comes last.

PRECEDENCE RULE: ( ) , **, * , / , //, % , + , -

In a formula, the expression inside the parenthesis is computed first. Then, the priority of the
rest of operations will be based on the precedence rule, that is, multiplication, division,
modulus, addition, and subtraction as the last priority. For example,

x = 8 + (9-3) * 4 / 2

Using the precedence rule, the computation for the above assignment statement will be in the
following order:

□ Parenthesis : x=8+6*4/2
□ Multiplication : x = 8 + 24 / 2
□ Division : x = 8 + 12
□ Addition : x = 20

Hence, the value of x for this arithmetic expression is 20.

For our given sample formula in the activity, the numerator and denominator are computed
first and computed separately. In this case, you can use parenthesis to indicated that it should
be prioritized in the computation, that is,

x = (a * b + c ) / (d – e)

For the expression (a * b + c), a and b will be multiplied first and the product will be added to c.
Whatever the computed value is, it will be divided by the expression (d – e).

It is important that you know how to convert these arithmetic expression into Python
expression. The table below contains sample mathematical formula translated to a Python
expression.

Mathematics Formula C++ Expression

b2 – 4ac b*b-4*a*c
x(y+z) x*( y+z)
1 1/(x*x+x+3)
89 | P a g e
Computer Fundamentals and Programming Using Python

Mathematics Formula C++ Expression

x2 + x + 3

a+b (a+b)/(c–d)
c-d

MORE ASSIGNMENT STATEMENTS. Since we deal with expressions and assignment


statements, it is also important to note that the Python language has special shorthand coding
that simplifies assignment statements. The table below shows the format on how to write
shorthand assignment statements.

Shorthand Assignment Statements

identifier operator = expression

Syntax The above syntax is equivalent to


identifier = identifieroperator expression

Identifier: any valid variable name

Semantics expression: a formula that can consists of any combination of variables, operators, and constan

In writing your program, you might encounter computations that require the use and reuse of
variables. Assuming you want to count the number of times a user runs the code and you want
to assign this to variable count. You could create an assignment statement like this,
count = count + 1

Using the shorthand format, you can write it as, count += 1

The following are some other examples on the use of shorthand operations:

total = total - discount total -= discount


age = age % 50 age %= 50
total = total + (amount - discount) total += (amount - discount)

Depending on the problem at hand, you might need to change the value of a certain
variable which is dependent on its current value. You can practice and try to apply the
shorthand statements in your previous activities and exercises. When dealing with control
statements, this type of statements will really come in hand (see Flow of Control and Loops).

For now, you must already know the basics of writing a simple Python program. If you are not
yet comfortable, practice with more problems. Now, do the next exercises to apply the different
arithmetic expressions.

90 | P a g e
Computer Fundamentals and Programming Using Python

See if you can do this!

Programming Exercises 9

The area of a trapezoid is computed using the formula A = ½ h (b1 + b2) where h is the height,
b1 and b2 are the bases. Write a program (with algorithm) that will compute for the area of a
trapezoid.

Algorithm Program Code

91 | P a g e
Computer Fundamentals and Programming Using Python

Programming Exercises 10

A Fahrenheit temperature F can be converted to an equivalent Celsius temperature C according


to the following formula:

( ab+ c )
x= d−e
C = ¿
¿

Write a program that reads in a Fahrenheit temperature as a decimal number and outputs the
equivalent Celsius temperature.
Algorithm Program Code

92 | P a g e
Computer Fundamentals and Programming Using Python

Programming Exercises 11

In a retail store, they offer an anniversary sale for their specially designed T-shirts (A, B, and C).
For every Php 1000 total purchases, you will get a 5% discount on Shirt A. Assume that the
prices for Shirts A, B, and C are Php50, Php75, and Php100, respectively.

Write a program (with algorithm) that will accept the number of T-shirts purchase (or quantity)
for each kind and will display the total purchases, discounted amount, and the amount to be
paid (i.e. total purchase – discount).
Sample Program Output 1 (with 5% discount): Sample Program Output 2 (with 2 x 5% discount):

STORE ANNIVERSARY SALE STORE ANNIVERSARY SALE

Enter quantity for Shirt A: Enter quantity for Shirt A:


3 Enter quantity for Shirt 10 Enter quantity for Shirt
B: 2 Enter quantity for B: 8 Enter quantity for
Shirt C: 7 Shirt C: 10

Total Purchases: Php 1000 Total Purchases: Php 2100


Discounted Amount: Php Discounted Amount: Php
7.50 Total Amount: Php 50.00 Total Amount: Php

Algorithm Program Code

93 | P a g e
Computer Fundamentals and Programming Using Python

VI. CONTROL STRUCTURES (SELECTION)

Introduction to Control Structures


“Would you tell me, please, which way I ought to go from here?”
“That depends a good deal on where you want to get to”, said the Cat.
“I don't much care where--” said Alice.
“Then it doesn't matter which way you go,” said the Cat. (Carroll, 1865)

After having completed the previous section, you are now able to develop simple Python
programs. The capabilities of your programs, however, are limited. They can evaluate arithmetic
or Boolean expressions and show the appropriate result. However, what happens when you
want to do a program that requires the user to select between choices? For instance, if you
need to know if they want to continue or not?

You need knowledge on control structures. These control structures allow conditional
processing of statements. For these structures, the program checks the choice or input of the
user and executes statements that should be done when a certain choice is made. For instance,
the program asks the user whether they want to continue or not… If the user selects “yes” then
another set of constructions are executed. However, if the user selects “no”, logically, the
program should end.

These are the kinds of control statements available:

1. The single-selection statement (If )


2. The double-selection statement (if -else)
3. The multiple-selection statement (if – elif- else)

Objectives:

At the end of this section, you should be able to:

1. Make use of control structures selection in programming.


2. Compare the functions of the different conditions statements.
3. Perform the hands on activities
4. Create programs using control Structures Selection.

Topic Outline:

1. Introduction to Control Structures Selection


2. Applying Control Structures Selection
3. The multiple selection statement

94 | P a g e
Computer Fundamentals and Programming Using Python

Try This!

Assuming you want to identify the status of an individual whether he/she is a


minor or an adult, based on his/her age. The tasks include reading the age of the
individual.

Think Ahead!

What is the input needed to solve this problem?

What is the expected output for this problem?

At what age will you consider the individual an adult?

At what age will you consider the individual a minor?

Given the values, determine the steps to determine the output of this problem.

No. STEPS
1.
2.

3.
4.
5.

Now you have just written your algorithm! Great!


The data or variables that are needed and asked in the problem are the following:

Input : Reading the age of the individual.


Condition : 18 below is a minor, else 18 and above is an adult.
Output : Minor or Adult.

95 | P a g e
Computer Fundamentals and Programming Using Python

Algorithm :
1. Input the age of the
individual 2. if (age <= 18 )
3. display the message “Minor”
4. else
5. display the message “Adult”

If your steps are similar to this, you are very close to creating a good algorithm! Good Job!

Algorithm Exercises

3 Problem:

Modify your flowchart on Algorithm Exercises 2. This time, it should be able to determine if the
student passed or failed. The passing rate is 75 and above. You may also use the greater than (>)
or less than (<) operators for this condition. And it should also do computations for 1 or more
students. Simulate the algorithm for at least 2 students, one failed and one passed. Use your own
sets of values.

Student Midterm Grade Final Term


Grade
1
2

Algorithm:

Algorithm Simulation
Flowchart
Student 1 Student 2

96 | P a g e
Computer Fundamentals and Programming Using Python

Algorithm Simulation
Flowchart
Student 1 Student 2

Read and Ponder!

In the solutions of many problems, different actions must be taken depending upon the value
of the data. Examples of simple situations include calculating the area only if the measurements
are positive, performing a division only if the divisor is not zero. (Bronson, 1999)

If statement
The figure below shows the flow of instruction using an if-statement.

Figure 6.1 Flowchart of if statement

Declaration of if statement
If (test expression):
Syntax statements

if: this is a reserved word.


test expression: this indicates the condition is declared.
Semantics
statements: these statements are executed only if the test expression is true.

97 | P a g e
Computer Fundamentals and Programming Using Python

Example:

If (age >= 17 ):
print(”Minor”)

if test expression is true, then, statements for the body if, i.e, statements inside
parentheses are executed. But, if the test expression is false, the execution of the
statements of the body of if statements are skipped.

For above example, if age = 17 or less, then it will output “Minor”. Otherwise, there will be no
output.

The if selection statement is a single-selection statement because it selects or ignores a


single action (or, as we will soon see, a single group of actions). (Gibmonks, 2002)

Relational expressions are sometimes called conditions which checks the values using a
relational operator. Table 6.1 lists the different kinds of relational operators. This is very similar
to mathematical conditions.

Examples:
age> 30 size< = 50 temp> 36.5
4<5 flag == done id_number == 123
day != 4 2.0 > 3.3 hours> 40

The following are invalid:

size=<50 // operator out of order (i.e. equals sign first before less than sign)
2.0 >> 3.3 // invalid operator
flag = = done // spaces are not allowed

Relational operator Meaning Example


< Less than Age < 40

> Greater than Age > 18


<= Less than or equal to Age <= 40
>= Greater than or equal to Age >= 18
== Equal to Age == 60
!= Not equal to Age != 100
Table 6.1 Relational operator

Let's say you are asked to write a pseudocode/algorithm and its equivalent Python program
that prints a number entered by the user only if the entered number is negative.

Algorithm Source code


Display "Enter a number to check:" print(”Enter a number to check : “)
Input number number= input()
If (number < 0) if (number<0):

98 | P a g e
Computer Fundamentals and Programming Using Python

Algorithm Source code


Display the value entered, print(”\nNumber is = “ ,number)
Display “The if statement in Python programmingprint(”\nThe
is easy! if statement in Python programming is easy!”)

Output 1:

Enter a number to check: -2


Number = -2
The if statement in Python programming is easy!

When user enters -2 then, the test expression (number<0) becomes true. Hence, Number=-2 is
displayed on the screen.

Output 2:

Enter a number to check: 5


The if statement in Python programming is easy!

When the user enters 5 then, the test expression (number<0) becomes false. So, the statement
for body of if is skipped and only the statement not inside the if is executed.

Let’s try another example, you were asked to write a pseudocode/algorithm and its
equivalent Python program that guesses ATM Card PINs.

Algorithm Source code


Display "Guess my Pin number" print(”Guess my Pin number : ”)
Input number number=int(input())
If (number ==1234) if (number==1234):
Output “ You got it!” print(”You got it!”)

Output 1:

Guess my Pin number: 1234


You got it!

When the user enters 1234, then, the test expression (number==1234) becomes
true. Hence, The message “You got it!” displayed on the screen.

Output 2:

Guess my Pin number: 121

When the user enters 121, then, the test expression (number==121) becomes false.
So, the statement for body of if is skipped.

99 | P a g e
Computer Fundamentals and Programming Using Python

See if you can do this!

Programming Exercise 12

ABC department store is celebrating its 10 year anniversary. A way of thanking their customers
is by giving discounts. A customer can avail a 20% discount only if the amount purchased is
more than P 500.00.

Write the algorithm and program code that will accept as input the amount purchased and
compute then display discounted amount and the amount due of the customer.

Algorithm Program Code

Programming Exercise 13

The CDE mall will be having a raffle draw in connection to their 15 year anniversary. Customers
can get 5 free raffle tickets for every P 300.00 worth of purchase.

Write a program that will accept as input the amount purchased and outputs the number of
tickets the customer gets.

100 | P a g e
Computer Fundamentals and Programming Using Python

Program Code

If...else statement

The figure below shows the flow of instruction using an if...else-statement.

Figure 6.2 Flowchart of if...else statement

101 | P a g e
Computer Fundamentals and Programming Using Python

Declaration of if...else statement


if (test expression):
if Statements

else
Syntax
:
else Statements

If and else: these are reserved words.


test expression: this indicates the condition is declared.

Semantics statement: the if statements are executed if the test expression is true. Otherwise if the test e

Example:
if (age >= 17 ):
print(”Minor”)
else:
print(”Adult”)

The if...else statement is used, if the programmer wants to execute some code if the test
expression is true and execute some other code if the test expression is false.

The if...else statement is called a double-selection statement because it selects


between two different actions (or groups of actions). (Gibmonks, 2002)

For the above example, if age = 17 or less, the output is “Minor”. Otherwise, if the Age is
18 or greater than 17, the output is “Adult”.

Let’s say you were asked to write a pseudocode/algorithm and its equivalent Python
program to check whether the number entered by the user is even or odd.

Algorithm Source code


Display "Enter a number you want to check:" print(”Enter a number you want to check
:”)
Input number number=int(input())
Let x = number % 2; x= number % 2;
If (x ==0) if (x==0):
Output The value of the number and the word Even print(number” is Even”)
else else:
Output The value of the number and the word Odd print(number,” is Odd”)

102 | P a g e
Computer Fundamentals and Programming Using Python

Output 1:
Enter a number you want to check: 12
12 is Even

When user enters 12 then, 12 % 2 = 0, the test expression (x==0) becomes true.
Hence, The value of the number and the word Even is displayed on the screen.
Output 2:
Enter a number you want to check: 11
11 is Odd

When the user enters 11 then, 11 % 2 = 1, the test expression (x==0) becomes
false. The statement for body of else is executed. Hence, the value of the number
and the word Odd is displayed on the screen.

Let’s try another example, you were asked to construct a pseudocode/algorithm and its
equivalent Python program for determining the area of a circle, provided if the radius of
the circle is not a negative number.

Algorithm Source code


Display “Please type in the radius” print(”Please type in the radius:”)
Input radius radius=float(input())
If ( radius >=0) if (radius>=0.0):
Let area = 3.1416 * radius * radius; area = 3.1416 * radius *radius ;
Output “The area of the circle is =” and the value
print(”The
of thearea
areaof the circle is “, area)

else else:
Output “Sorry a negative radius is invalid” print(”Sorry a negative radius is invalid”)

Output 1:
Please type in the radius: 3.5
The area of the circle is 38.48

When user enters 3.5 then, the test expression (radius>=0) becomes true. Hence, The
equivalent area of the circle is displayed on the screen.

Output 2:
Enter a number you want to check: -3.2
Sorry a negative radius is invalid

When the user enters -3.2 then, the test expression (radius >=0) becomes false. The
statement for body of else is executed. Hence, the message “Sorry a negative radius is
invalid “ is displayed on the screen.

103 | P a g e
Computer Fundamentals and Programming Using Python

See if you can do this!

Programming Exercise 14

ABC department store is celebrating its 10 year anniversary. A way of thanking their customers
is by giving discounts. A customer can avail a 20% discount only if the amount purchased is
more than P 500.00. Otherwise, customer only gets a 5% discount.

Write the algorithm and program code that will accept as input the amount purchased and
compute then display discounted amount and the amount due of the customer.

Algorithm Program Code

Programming Exercise 15

The CDE mall will be having a raffle draw in connection to their 15 year anniversary. Customers
can get 5 free raffle tickets for every P 300.00 worth of purchase. If worth of purchase is less
than P 300.00, customer only gets 1 ticket for every P75.00 worth of purchase.

Write a program that will accept as input the amount purchased and outputs the number of
tickets the customer gets.

104 | P a g e
Computer Fundamentals and Programming Using Python

Program Code

Nested if...else statement (if... elif.....else Statement)


The figure below shows the flow of instruction using a nested if. else-statement.

Figure 6.3 Flowchart of nested if…else statement (if... elif.....else Statement)


(Diagram is courtesy of CodersForevers.com)

105 | P a g e
Computer Fundamentals and Programming Using Python

The if...else statement can be used in nested form when a serious decision is involved.

Declaration of nested if...else statement


If (test expression 1):
Statement1
elif (test expression 2): statement2
Syntax
else:
statement3

If , el if and else: these are reserved words.


test expression: this indicates the condition is declared.

Semantics statement: the statement 1 is executed if the test expression 1 is true. However if the test ex

Example:

if (age >= 17 ):
print(”Minor”)
elif (age<=59):
print(”Adult”)
else:
print(”Senior Citizen”)

How nested if...else works?


If test expression 1 is true, it will execute the code but, if it is false, the control of the program
jumps to the else if part and check test expression 2, then the process continues. If all the
conditions are false then, the else statement is executed.
For the above example, if age = 17 or less, the output is “Minor”. However, if the Age is than
17, and less than or equal to 59 the output is “Adult”. Otherwise the output is “Senior Citizen.

Let’s have an example of nested if else statement.

You were asked to write a pseudocode/algorithm and its equivalent Python program to relate
two integers entered by using == or > or < sign.

Algorithm Source code


Display “Enter two integers to check” print("Enter two integers to check")
Input numb1,numb2 numb1=int(input())
numb2=int(input())
If ( numb1 ==numb2) if(numb1==numb2):
Output “ Result” numb1 = numb2 print("Result ",numb1,” = “,numb2)
else if (numb1>numb2) elif (numb1>numb2):

106 | P a g e
Computer Fundamentals and Programming Using Python

Algorithm Source code


Output “Result” numb1 > numb2 print("Result ",numb1,” > “,numb2)
else else:
Output “Result” numb1 < numb2 print("Result ",numb1,” < “,numb2)

Output 1:
Enter two integers to check
5
3
Result: 5>3

Output 2:
Enter two integers to check.
-4
-4
Result: -4=-4
Output 3:
Enter two integers to check.
5
8
Result: 5<8

In this program, user is asked to enter two integers which are stored in variable numb1 and
numb2. Then, the value of numb1 and numb2 are to be checked, whether it is equal, less
than or greater than by using nested if else statement.

See if you can do this!

Programming Exercise 16

Write a program to compute for the amount to be paid by the customer in purchasing
items. The program will accept as inputs the price of the items and how many items
are bought. The customer can avail the 10% discount if and only of the number of
items bought is more than or equal to 100 but less than 150. If the number of items
bought is more than or equal to 150 but less than 200, the equivalent discount is 12%.
A discount of 15% can be availed if the number of items bought is more than or equal
to 200.

107 | P a g e
Computer Fundamentals and Programming Using Python

Program Code

108 | P a g e
Computer Fundamentals and Programming Using Python

VII. Repetitive Control Structures

Introduction to Repetitive Control


Structure

Have you observed the work of a cashier in a grocery store? How about a waiter in a
restaurant? Did you know that they are doing a repetitive process? For each customer, they ask
the same questions, get same sets of information, and follow the same computations. This
procedure is repeated for every customer until there are no more customers or their duty for
work is over.

A program code is considered to be a good code if it has a good algorithm and codes are
compact. You know by now that the compiler processes your codes line by line. So, the more
lines of codes you have the more time it requires for the compiler to process it. A program with
too much code lines cannot be considered a good program code especially if codes are being
repeated for several times. How can you eliminate repeated codes?

Repetitive Control statement is the structure you need to know to eliminate redundant codes.
Repetitive Control statement repeats execution of codes for several times depending on the
given condition.

These are the kinds of control statements available:


1. The while statement
2. The for statement

Objectives:

At the end of this section, you should be able to:

1. Use the syntax of the different repetitive statements in a program


2. Compare the different repetitive statements from one another
3. Select the best repetitive statement to be used in a certain problem
4. Create a program using the different repetitive statements

Topic Outline:

1. Introduction to Repetitive Control Structures


a. while statements
b. for statement

109 | P a g e
Computer Fundamentals and Programming Using Python

Try This!

Do you know anyone who is already working for a company or managing their
own business? It could be your parents, sister, brother, friends, or anybody you
know. Ask them of the nature of their job. And just like the job of a cashier or
waiter, ask them which part of their work is repeated (either repeated
daily, weekly, monthly, yearly, or at a certain given moment or period depending
on their job).

Think Ahead!

What is the nature of their work?

Which part(s) of their job are repeated?

List the factors that contribute to the repetition of their actions? When will they stop doing their
job?

The job of a cashier in the counter is repeated for each customer; however, not every job is
repeated in the same manner. Some jobs require them to create reports maybe daily, weekly,
monthly, and sometimes yearly depending on the nature of the job. In some cases, it’s not the
entire work that is repeated but only a part of the work.

The factors that you have identified are the conditions in which certain tasks are repeated or
not to be repeated. This is a very important aspect that you have to identify when dealing with
repetitive actions. Imagine the job of a cashier in the counter, without a certain condition (i.e. a
snack break or end of duty), they would be repeating the tasks forever. This also applies in
programming; you do not want your program stuck in an endless loop.

110 | P a g e
Computer Fundamentals and Programming Using Python

Algorithm design

Sample Algorithm (flowchart using decision symbol)

Line Using
No Using Flowchart
Pseudocode

START
1 Start

Input length, Input length,


2 width
width

Compute area area = length * width


3
= length *
width

4 Output area Output area

Message “Do Output “Do you want


you want to to compute for the
5 compute for the area of a rectangle
area of rectangle again? [Yes/ No]”
again?
*Yes/No+”
Input answer
6 Input answer

7 If answer is “Yes” For this symbol, equivalent


Yes If answer is arrows are drawn for the “Yes”
8 Goto Line 2 “Yes” and “No” options. “Yes” arrow
9 Else goes back to the first input
10 Goto Line 11 No symbol (equivalent to line 7:
Goto line 2) “No” arrow goes to
END the end of the program

11 End

For this flowchart, we use the decision symbol to represent the if statement on line 7. The
corners of decision symbol can be used to place the possible flow information and data. In this
example, the possible data flow is either a Yes decision or No decision.

111 | P a g e
Computer Fundamentals and Programming Using Python

Sample Simulation: Let us assume that we will compute for the area of two (2) rectangles. For
the first rectangle, the length and width is 10 and 8 respectively, and for the second rectangle, it’s
15 and 10 respectively. Since we are going to compute for the area twice ( repetition), we will be
using Algorithm 2.

As you can see for the first rectangle (first computation), the program does not end yet; instead,
you repeat the inputs for the second rectangle (second computation). You can test this further with
other set of values or repeat the computation multiple times.

112 | P a g e
Computer Fundamentals and Programming Using Python

Algorithm Exercises 4

Problem:

Recall the problem on computing for the area of a rectangle in lesson III. Modify its
algorithm to satisfy the condition below.

Write an algorithm that will compute for the area of a triangle given its base and height.
The algorithm must allow the user to compute for another set of data.

No. Steps
1

2
3
4
5
6
7
8
9
10

Simulate your algorithm using two (2) different measurements of triangles.

No. Triangle 1 Simulation Triangle 2 Simulation


1

2
3
4
5
6
7
8
9
10

113 | P a g e
Computer Fundamentals and Programming Using Python

Algorithm Exercises

5 Problem:

Modify your flowchart on Algorithm Exercises 2 to allow repetitive computations for the
students’ final grade. Your new algorithm should allow computations for 1 or more
students. Simulate the algorithm for 2 students with the following equivalent midterm and
final term grades:

Student Midterm Grade Final Term Grade


95
1 90 90
2 85

Algorithm:

Algorithm Simulation
Flowchart
Student 1 Student 2

114 | P a g e
Computer Fundamentals and Programming Using Python

Read and Ponder!

Repetitive control statements are also called a Repetitive control structure. Sometimes we
require a set of statements to be executed a number of times by changing the value of one or
more variables each time to obtain a different result. This type of program execution is called
looping.

WHILE LOOP STATEMENT

The first repetitive statement is the while loop statement. Below is the flow
diagram of while loop.

False
Test
Expression

True

Executable statement (s) loop

Continue
with the
next
statement

Figure 7.1 Flowchart of while statement

The diagram above shows that a condition is first evaluated. If the condition is true, the loop
body is executed and the condition is re-evaluated. Hence, the loop body is executed
repeatedly as long as the condition remains true. As soon as the condition becomes false, it
goes out of the loop and proceeds to the statement outside of the “while” loop. Table 7.1
below shows the syntax for the “while” loop.

Line No. Syntax Remarks

1 while (condition):
2 Statement_1 Indention indicates start of the loop. Statement 1 until last stateme
3 Statement_2
4 Statement_3
5 …
6 Last_statemen
t

Table 7.1 Syntax of while statement

115 | P a g e
Computer Fundamentals and Programming Using Python

SAMPLE PROGRAM

Find the sum of first ten natural numbers. Natural numbers are positive integers (whole
numbers).

How it works Program code


Initialize loop control variable n=1
Test of loop control variable while (n<=10):
total+=n
Update of loop control variable n=n+1
print(“sum of the first ten natural numbers is “, total)

Sample Problem with running program code (while loop)

A class of ten students took a quiz. The grades (integers in the range 0 to 100) for this quiz are
available to you. Determine the class average on the quiz.

Algorithm Design Program Code


1. initialize loop gCount = 1
control variable
2. initialize variable for tot_grade = 0
accumulation of
grade scores
while (gCount<=10):
3. start of loop quiz_score=int(input(“enter quiz grade of
4. accumulation of student “,gCount,” : ”))
grade scores tot_grade+=quiz_score;
5. update of loop
control variable gCount+=1
6. computation of
average / not grade_score_ave=tot_grade/(gCount=1)
included in the loop
7. display of output
print(“class average is “, grade_score_ave)

Sample Possible Output:

Enter quiz grade of student 1 : 98


Enter quiz grade of student 2: 76
Enter quiz grade of student 3: 71
Enter quiz grade of student 4: 87
Enter quiz grade of student 5: 83
Enter quiz grade of student 6: 90
Enter quiz grade of student 7: 57
Enter quiz grade of student 8: 79
Enter quiz grade of student 9: 82
Enter quiz grade of student 10: 94
116 | P a g e
Computer Fundamentals and Programming Using Python

Class average is 81

Program Simulation

gCounter=1
Initialize total=0
condition input totalincrement
(gradeCounter<=1 0) (grade gradeCounter
True True True True True )True
98 True True
gradeCounter=1 True True 76 98 2
gradeCounter=2 gradeCounter=3 gradeCounter=471 gradeCounter=5
174 3 gradeCounter=6 gradeCounter=7 gra
gradeCounter=1 0 87 245 4
gradeCounter=1 1 83 332 5
Average=81 90 415 6
57 505 7
79 562 8
82 641 9
94 723 10
817 11

False 817

See if you can do this!

Programming Exercises 17

Write a program that will accept as input an integer value. The program will then
determine and display all its factors.

Example:
Integer value : 9
Factors are : 1. 3, 9

117 |Pag
e
Computer Fundamentals and Programming Using Python

Program Code

FOR LOOP STATEMENT

Another repetitive statement is the for loop statement. Just like the first repetitive
statements, its main function is to repeat execution of statement(s) while the condition remains
true. for statement works like the while loop.

118 |Pag
e
Computer Fundamentals and Programming Using Python

for loop statement uses the range() function. The range() function can have a single argument,
two arguments and three arguments.

Line no. Syntax Remarks

1 for I in range (constant):


2 Statement_1 Indented statement indicates start
3 Statement ofloop.Statement_1until
4 Statement last_statement will be repeated
5 … depending on the constant,
value
starting
of theconstant-1
6 Last_statement from 0 to

Table 7.3a syntax of for statement using range() function with single argument

Line no. Syntax Remarks

1 for I in range (constant_1,constant_2):


2 Statement_1 Indented statement indicates start
3 Statement of loop. Statement_1 until last_statement will be repe
4 Statement
5 …
6 Last_statement constant_1 untilthevalue of
constant_2-1
Table 7.3b syntax of for statement using range() function with two argument

Line no. Syntax Remarks

1 for I in range (constant_1,constant_2,step):


2 Statement_1 Indented statement indicates start
3 Statement ofloop.Statement_1until last_statement will be repeat
4 Statement
5 … of
6 Last_statement of or
constant_2-1,incremented
decremented by the value of step
Table 7.3c syntax of for statement using range function with single argument

Example using range() function

for i in range (5): counts from 0 to 4


for I in range (1,5): counts from 1 to 4
for i in range (3,10): counts starting from 3 to 9
for i in range (1,10,2): counts 1, 3, 5, 7, 9
for i in range (12,4,-3): counts 12, 9, 6

119 | P a g e
Computer Fundamentals and Programming Using Python

SAMPLE PROGRAM

Here is an example of a countdown program using for loop:

How it works Program code


1. initialization is executed, i is set to 0. for i in range (5):
Initialization is done only once.
2. condition is checked. If value of i is still
within the range (within 0 to 4)
3. value of i will be printed if condition is still print(i)
true, still within the range
4. value of i will be incremented
automatically by 1until value of i will be outside of range ( greater than of equal to 5)

5. display “end of loop” print(“end of loop”)

Sample Possible Output:

0
1
2
3
4
end of loop

Program Simulation

initialize
i=0

condition Display increment y


(i<5) value of i by 1
y=0 true(loop 0 1
)
y=1 true(loop 1 2
)
y=2 true(loop 2 3
)
y=3 true(loop 3 4
)
y=4 true(loop 4 5
)
y=5 false(exit
loop)
Display “end
of loop”

120 | P a g e
Computer Fundamentals and Programming Using Python

See if you can do this!

Programming Exercise 18

A perfect number is number whose factors, excluding itself, is equal to the product of its
factors. The first perfect number is 6. The factors of 6 (excluding itself) are 1, 2 and 3 and the
product of these factors is 6.

Write a program to search and display for the second and third perfect number.

Program Code

121 | P a g e
Computer Fundamentals and Programming Using Python

Programming Exercise 19

Write a program to compute for the total amount to be paid by the customer in purchasing
items. The program should display a list of five (5) items with their corresponding prices. The
user selects items from the list and inputs the item number to be purchased (based on the list)
and the quantity for each item to be purchased. This action will be repeated until the user does
not select anymore items. The program will display the total amount to be paid by the
customer.

Program Code

122 | P a g e
Computer Fundamentals and Programming Using Python

Programming Exercise 20

Write a program that determines the factors of an integer value.

Program Code

123 | P a g e
Computer Fundamentals and Programming Using Python

Programming Exercises 21

Write a program that determines the greatest common factor of two integer values.

Program Code

124 | P a g e
Computer Fundamentals and Programming Using Python

VIII. FUNCTIONS

Introduction to Functions

After completing the previous sections, you are now equipped with the basics of Python
programming. You know that programs are created to solve problems. So far, you only created
small programs that solve a specific problem. However, most of the programs such as websites
or games composed of smaller programs that are joined and integrated to create one huge
application. It sounds complicated, right? And maybe you can already imagine thousands lines
of codes. In most cases, these huge applications are divided into chunks for easy programming
and management not just by a single programmer but also for a group of programmers. How?
Well, easy… functions!

Let’s take a look at your own television sets. Do you know how televisions are manufactured?
Production of television consists of several lines (of production) and each line is assigned for a
special task. At the end of each production line, outputs are being checked before proceeding
to the next production line. This is done to assure that the unit is functional.

In programming, you can also create programs chunk by chunk. Each chunk is a part of a huge
program. Each chunk is being tested of its functionality before embedding to the huge
program. These chunks are called functions. This programming technique is called the
modular approach.

Objectives:

At the end of this section, you should be able to:

1. Use predefined function(s) in a program


2. Create your own function
3. Write programs in modular approach
4. Use different types of parameters in a function

Topic Outline:

1. Introduction to Functions
2. Pre-defined Functions
3. Programmer defined Functions
4. Types of parameters

125 | P a g e
Computer Fundamentals and Programming Using Python

Try This!

During enrolment, after filling up the red form, how many steps have you undergone
before getting officially enrolled?

Think Ahead!

Why is enrolment process divided into steps?

If only one person is in-charge for the entire enrolment process, will the enrolment become
faster? Will the enrolment process have lesser error?

Read and Ponder!

A function is a subprogram that is executed when it is called from some point of the program,
it will not be executed unless it is called. The statement used to execute a function is called the
function call. A function call is an expression consisting of the function name followed by the
arguments enclosed in parenthesis.

One of the advantages of using functions to divide programming task into subtasks is that
different people can work on different subtasks. Also, it is easier to debug a program with lesser
lines of codes compared to a huge program.

There are two types of functions two namely:

1. Pre-defined function
2. Programmer Defined Function

Predefined Function

Python comes with libraries of Predefined functions that you can use in your program. These
Predefined functions are ready made function and has already been defined.

126 | P a g e
Computer Fundamentals and Programming Using Python

Built-in Modules in Python

The Python interpreter has a number of built-in functions. They are loaded automatically as the
interpreter starts and are always available. For example, print() and input() for I/O, number
conversion functions int(), float(), complex(), data type conversions list(), tuple(), set(), etc.

In addition to built-in functions, a large number of pre-defined functions are also available as a
part of libraries bundled with Python distributions. These functions are defined in modules. A
module is a file containing definitions of functions, classes, variables, constants or any other
Python objects. Contents of this file can be made available to any other program.

Built-in modules are written in C and integrated with the Python interpreter.

Python - Math Module

Some of the most popular mathematical functions are defined in the math module. These
include trigonometric functions, representation functions, logarithmic functions, angle
conversion functions, etc.

Some of the functions includes log(), exp(), pow(), sqrt(), ceil() and floor().

In addition, two mathematical constants are also defined in this module.

Pie π().Her, youwilbea toenhc yourpevis rogam byipemlntg avrib) is a well-known mathematical constant, which is defined as the ratio of the circumference
to the diameter of a circle and its value is 3.141592653589793.

Another well-known mathematical constant defined in the math module is e. It is called Euler's
number and it is a base of the natural logarithm. Its value is 2.718281828459045.

SAMPLE PROGRAM

The relationship between the sides (a, b) of a right triangle and the hypotenuse (h) is given by
the Pythagorean formula

a2 + b2 = h2

Write a program that reads in the lengths of the two sides of a right triangle and computes the
hypotenuse of the triangle.

Program Code 1
import math library for predefined functions sqrt
print(”Enter sides of the triangle…”)
a=float(input(”\nside a: “))
b=float(input(”\nside b: “))
h = math.sqrt ((a** 2.0)) + (b** 2.0)) function call for sqrt

print(”\n\nhypotenuse of the triangle is “,h)

127 | P a g e
Computer Fundamentals and Programming Using Python

Program Output for both program codes:

Enter sides of the triangle…

side a: 3
side b: 4

hypotenuse of the triangle is 5

Programmer Defined Function

Python allows programmers to create their own functions. This is used to make the program
more organized and structured. These functions are called programmer defined functions.

Functions are declared at the beginning of the program code. Function definition begins with
the header, composed of the word def followed by the function name then with the
arguments(optional) that are within a parentheses. Then there should always be a block with
the code that the function is to execute. Any of the arguments passed to the function can be
used as if they were declared in the block.

Line no.
Syntax Remarks
def function_name (arguments): Statement_1 Statement_2
Function
Statement_3
header
1
… Last_statement Block of codes; consists of executable statemen
2
3
4
5
6

Table 8.2 General format for defining a function

Parameters and arguments

Arguments in Python are passed by reference. Any changes made with the value of the
parameters within the function, the changes reflects back in the calling function.

SAMPLE PROGRAM 1

Write a program that adds two integers and outputs the sum. The program defines a
function with two parameters, performs the addition of two integers and returns the sum.

How it works Program code


Functiondefinition.Declaringthe function addition with
def addition
two parameters
(a, b):

Block of codes of the function addition


print(“value of a is “,a)
print(“value of b is “,b)

Adds the values of a and b sum=a+b


Return the sum to the calling function return (sum)

128 | P a g e
Computer Fundamentals and Programming Using Python

How it works Program code


Statement of the main block
Function call. Calling the addition function with two
answer=addition(5,3)
arguments. 5 will be passed to parameter a and 3 to parame

print(“the result is “, answer)

SAMPLE PROGRAM 2

Write a program that subtracts two integers and outputs the difference. The program defines a
function with two parameters, performs the subtraction of two integers and returns the
difference. It shows four (4) different ways on how to call a function.

How it works Program code


Function definition. Declaring the function def subtraction (a, b):
addition with two parameters
Block of codes of the function
addition Adds the values of a and b diff=a-b
Return the sum to the calling function return (sum)

Statement of the main block


x=5
y=3
Function call. Calling the addition function answer=subtraction(7,2)
with two arguments. 5 will be passed to
parameter a and 3 to parameter b. returned
value is assigned to answer.
Display the value of answer print(“the first result is “,answer)
Another function call with two arguments, 8 print(“the second result is
for parameter a and 5 for b. result (returned “,subtraction(8,5))
value) is displayed
Another function call with two arguments, print(“the third result is
x for parameter a and y for b. result “,subtraction(x,y))
(returned value) is displayed
Another function call with two arguments, answer=4+subtraction(x,y)
x for parameter a and y for b. result
(returned value) is added to 4
print(“the fourth result is “,answer)

SAMPLE PROBLEMS WITH PROGRAM CODES

1. Write a program that will display the square of the integers 1 to

10. #function definition


def compSquare( y ):
#The parameter y will accept the value of x
s = y* y
return (s)

def displaySquare( s ):
#The parameter s will accept the value of square
129 | P a g e
Computer Fundamentals and Programming Using Python

print(s)

for x in range (10):


square=compSquare( x ) #calling the function compSquare with value of x as
argument

displaySquare(square) #calling the function displaySquare with the value of


square as argument

Sample program output

1 4 9 16 25 36 49 64 81 100

2. A liter is 0.264179 gallons. Write a program that will read in the number of liters of gasoline
consumed by the user’s car and the number of miles traveled by the car; and will then
output the number of miles per gallon the car delivered. Define a function to compute
the number of miles per gallon.

def miles_per_gal (lit_gal, miles_trav):


car_del=(lit_gal * 0.264179) / miles_trav
return (car_del)

nlg=float(input(“Enter number of liters of gasoline consumed by the user\’s car :”))


nmt=float(input(“Enter number of miles travelled by the car :”))

nmg=miles_per_gal(nlg,nmt)

print(“number of miles per gallon the car delivered is “,nmg)

Sample program output:

Enter number of liters of gasoline consumed by user’s car:3


Enter number of miles traveled by the car:2
The number of miles per gallon the car delivered is 0.3962685

See if you can do this!

Programming Exercises 22

A quadratic equation is one of the form ax2 + bx + c =0. Write a program to solve such
equations for x using the quadratic formula:
Object 6

Your program will output all real number values that, when substituted for x, will make the left
hand side equal to zero. The input to the program consists of the three coefficients a, b, and c.
130 | P a g e
Computer Fundamentals and Programming Using Python

Program Code

131 | P a g e
Computer Fundamentals and Programming Using Python

Programming Exercises 23

In order to discourage excess consumption, an electric company charges its customers a lower
rate, namely $0.11, for each of the first 250 kilowatt hours, and higher rate of $0.17 for each
additional kilowatt hour. In addition, 10% surtax is added to the final bill. Write a program to
calculate electric bills given the number of kilowatt hours consumed as input. Use two function
declarations: one to compute the amount due without the surtax and one to compute the total
due with surtax.

Program Code

132 | P a g e
Computer Fundamentals and Programming Using Python

Programming Exercises 24

Write a function declaration for a function called grader that takes a numeric score and returns
a letter grade. Grade has one argument of type integer. Use the rule that 90 to 100 is an A, 80
to 89 is a B, 70 to 79 is a C and less than 70 is an F.

Program Code

133 | P a g e
Computer Fundamentals and Programming Using Python

Bibliography

Brian Heinold(2012). A Practical Introduction to Python Programming. Department of Mathematics and


Computer Science, Mount St. Mary’s University

Clement, J. (July 24, 2020). Worldwide digital population as of July 202. Statistica 0 Retrived from
https://www.statista.com/statistics/617136/digital-population-worldwide/

Computer Basics. (2009). Retrieved May 5, 2013, from Computer Basics for Beginners:
http://www.computerbasicsguide.com/basics/types.html

Discovering Computers. (2002). Retrieved May 5, 2013, from Slideshare:


http://www.slideshare.net/ZOulKapunk/chapter-1introductiontocomputers3165

Fabien, G. (1999). Computer's Fundamentals Course. Retrieved May 5, 2013, from http://www.cs.cmu.edu/
~fgandon/lecture/uk1999/computers_types/

GCF LearnFree.org (2020). Internet Basics, Goodwill Community Foundation, Inc. Retrieved from
https://edu.gcfglobal.org/en/internetbasics

Gregory, Lucas (February 18, 2019). Timeline of Revolutions. Industrial of Internet of Things Retrieved
from https://www.industrialiotseries.com/newsroom/timeline-of-revolutions/

Hardware of Personal Computers. (2007). Retrieved May 5, 2013, from Slideshare:


http://www.slideshare.net/ipwk/lesson-2-ppt-v6

IncludeHelp (2020). Computer Number System and its Types. Retrieved from
https://www.includehelp.com/computer-number-systems.aspx

Litemind (2020). What is Mind Mapping? Retrieved from https://litemind.com/what-is-mind-mapping/

Malik, D. (2009). C++ Programming From Problem Analysis to Program Design (4th ed.). Boston, MA, USA:
Course Technology, Cengage Learning.

Rayome, Alison (June 24, 2019). Top 10 Emerging Tehnologies of 2019 Retrieved
from https://www.techrepublic.com/article/top-10-emerging-technologies-of-2019/

Rippe, B. (2009). CSCI 123 Introduction to Programming Concepts in C++. Retrieved March 23, 2012, from
CSCI 123 Introduction to Programming Concepts in C++: http://staffwww.fullcoll.edu/brippe/csci123/

Rivas, Teresa (August 22, 2017). Ranking The Big Four Tech Stocks: Google Is No. 1, Apple Comes In Last.
Barrons Retrieved from https://www.barrons.com/articles/ranking-the-big-four-internet-stocks-google-is- no-
1-apple-comes-in-last-1503412102

Savitch, W. (2011). Problem Solving with C++: The Object of Programming (7th ed.). USA: Addison
Wesley.

Schildt, H. (1992). Turbo C/C++: The Complete Reference (2nd ed.). Osborne, U.S.A.: McGraw-Hill.

TutorialsTeacher (2020). Python Tutorils Retrieved from https://www.tutorialsteacher.com/python/

Williams, Brian K. and Sawyer, Stacey C. (2011). Using Information Technology, A Practical Introduction to
Computers and Communications, 9th Edition, The McGRawHill Companies, Inc., 121 Avenue of the
Americas, New York, NY, 10020

University of Hull (July 28, 2020). The Digital Student Retrieved from
https://libguides.hull.ac.uk/digitalstudent/

134 | P a g e

You might also like