0% found this document useful (0 votes)
20 views25 pages

ICT2103 Full Book-Part-1

Uploaded by

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

ICT2103 Full Book-Part-1

Uploaded by

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

Decomposition

Algorithm Abstraction

Pattern
Recognition

Computational
Thinking and Coding
in

Dr. Hamad Odhabi, Ali Farhat, Rajavelu Loganathan,


Dr. Ossama Embarak, Steve Allison, and Dr. Phil Quirck

Computational Thinking
and Coding in Python 1
2
Table of Contents

Preface 4
Study Guide 5
Computational Thinking and Coding 10 Data Analytics in Python 52
Example of an Algorithm 14 Why do I need to learn Data Analytics? 53
An Example of Applying Computational Thinking 16 The process of Data Analytics 54
Programming Language 18 Accessing files in pandas 55
Translating an Algorithm Into Python Code 20
Getting familiar with Azure Notebook 56
The for Loop 22
Examples 23 Example 1: Accessing Excel files 60
Exercises 26 The pandas DataFrame 62
Data Types and Variables 27 Skipping unnecessary rows and columns 63
Exercise on Variables 31 Display data in one or more columns 64
Python Data Types 32 Displaying unique values in a column 65
Arithmetic Operators 35 Describing the data of a column 66
Example 36 Slice data using index 67
User Defined Functions in Python 39 Working with loc in pandas 70
Examples of User Defined Functions 41 Renaming columns 72
Exercises 43 Calculated columns 73
Making Selections: The if Statement 44
Changing the index 74
Comparison Operators in Python 46
Python’s Logical Operators 47 Sorting data 76
Examples of Selections 48 Combining two similar DataFrames 78
Nested if 49 Grouping Data 79
Example of a Nested if 50 Working with missing data 80
Exercises 51 Writing data to an external file 83

Data Visualization Common 84


used charts Examples 86
Enhancing the chart The 87
Pie Chart 90
Case Study 91
Summary of pandas 92
commands 106

3
Preface
Software

You may ask, what programming development environment do I need


to complete the examples and exercises in this book? Of course, you
are free to download and install any development environment that
you prefer. However, we are using a cloud-based interactive
development environment (IDE) that does not require any installation. All
you need is a modern browser. The IDE that we will use is REPL.it.
REPL.it, which will allow you to write the required code, debug and run it.
REPL.it will save the code for you and you will be able to access your
code at any time. Later in the book, when we start looking at Data
Analysis, we will be using Jupyter Notebook. As with REPL.it, we will
use a cloud-based version of Jupyter Notebook through Microsoft
Azure.

4
How can I make the most of this book?

We recommend that you read the book chapters in detail, watch the videos
linked to each chapter, and complete the practical codes and exercises at the
end of each section. Also, you can participate in the discussions on our
dedicated Facebook page.

What I will learn from this book?

This book is intended to develop the reader's knowledge, skills, and


competencies in computational thinking, data analysis, and
visualization. It has been structured into 3 main units:

Unit 1: Fundamentals of Unit 2: Introduction to Data


Programming using Python Analytics.
and turtle. This unit covers the following
• Introduction to topics:
Computational Thinking • Accessing Data
• Program Structure • Cleaning Data
• Computer Algorithms • Searching
• Data Types and Variables • Grouping and Indexing
• Sequence, Iteration, and • Joining Multiple Data
Selection Sets
• Writing Data to Files

Unit 3: Data Visualization


• Line Plots
• Histograms
• Bar Charts
• Scatter Plots
• Box Plots

9
Computational
Thinking and Coding

This section aims to develop your knowledge and skills in


the following areas:

• Explain the process of Computational Thinking


• Identify key components of Computational Thinking
• Apply computational thinking to solve a real life problem
• Understand the structure of algorithm
• Develop algorithms to solve real life problems
• Translate algorithm from human language to computer
programming language (Python)

10
Computational Thinking and Coding
Computational thinking is the thought and processes involved in
formulating a problem and expressing its solution(s) in such a way
that a computer — human or machine — can effectively carry out
that solution. In other words, it is the ability to formulate a solution
that can be understood by humans and executed by computers.

There are four core components of computational thinking:

Decomposition

Algorithm Abstraction

Pattern
Recognition

Decomposition: The process of breaking down a


complex problem or system into smaller and more
manageable parts. This could not be achieved without a
proper and thorough understanding of the problem that
needs to be solved. For example, calculate the area for
the shape in figure 1. Looking at the shape at first, one
might think it is hard to solve the problem, but if we
break the problem into smaller tasks, then the solution Figure 1
becomes easy.
Looking at the shape closely, we notice that it is composed of a triangle on top
and a rectangle/square on the bottom part. Thus, the original problem can be
broken into calculating the areas of a triangle and a rectangle, then adding
them together. The problem is decomposed into three smaller problems which
make the original problem more manageable and easier to solve. Note that
the equations to calculate the area of a triangle and a rectangle are already
known and thus the problem becomes trivial to solve.
11
Abstraction: When you are dealing with a complex problem, there
is the possibility that many components or data will have no
relation to the problem you are trying to solve. Identifying and
eliminating these components is an important task. In abstraction,
you focus on the important information only, ignoring irrelevant
details. A key to this process is to look for the information or facts
that are necessary to solve the problem. For example, consider
the problem that was presented in Decomposition. Find the area
of the following shape with the facts provided:

b =5
a =5

width = 6

Color = blue height =5

Figure 2

Not all the given information is important. For example, the


height and width are needed to calculate the area of the
bottom rectangle. On the other hand, the color does not play
any role in calculating the area and so we can ignore it.
Learning to disregard irrelevant data is a special skill that is
developed over time and requires a good understanding of the
solution you’re trying to achieve.

A company calculates its employees’ yearly bonuses based on their


number of years working at the company and their current salary.
Information is kept about each employee. Write down the sort of
information that might be collected on each employee and decide
which items are needed to calculate the bonus and which not.

12
Pattern Recognition: The process of looking for and finding
similarities. Patterns may exist within the same problem or in
different problems. Pattern recognition is important to get a
deeper understanding of the problem and begin formulating a
possible solution.

For example, find the sum of the following numbers:

One way to solve this is to keep a running total in your head and while
adding numbers in sequence. That method does work, but it will take a
long time and the possibility of making a mistake is great. But if you
look closely, you will notice a pattern in these numbers: there are five
2’s, four 10’s, and three 5’s. Solving it now becomes much easier:

This is a simple example of pattern recognition but the concept is a


powerful one and will be used throughout this course.

If you look around, you will find many patterns in daily life, including
the daily routine of going to sleep and waking up next morning.

Think of some of the patterns that you see around you and write
them down in simple steps.

13
Algorithm: A procedure for solving a given problem. It is made up of
a set of rules and steps needed to solve a problem. It is concise and
unambiguous, with clear start and end points. The algorithm can be
expressed in plain spoken language and/or a series of calculations, or
graphically in flow charts.

Example of an Algorithm

How to make a cup of black tea

1. Get an empty teacup


2. Determine the type of tea desired
3. Put the selected tea bag in the cup
4. Determine if sugar is needed
5. Add the desired amount of sugar
6. Add water to the kettle
7. Turn on the heat under the kettle
8. Bring the water to a boil
9. Pour the boiling water from the kettle to the cup
10. Stir the cup with the tea bag and optional sugar
11. Remove tea bag after one minute
12. Serve the tea
13. Done

Sometimes there are different solutions or algorithms to solve the


same problems. Some algorithms are faster and more efficient than
others. Algorithm design and evaluation is a very big area for
research and development. Study the algorithm above and see if you
can improve or change it to achieve the same result. You will find at
least a few other ways to make it solve the problem. Discuss it within
the class and determine which one is the best. Good luck with it! J

14
More Examples
Find all even numbers in a list
1,3,5,6,2,8,9,10,11,2,4

For every number in the list


divide the number by 2
get the remainder of the
division if the remainder = 0
the number is even and print it
else
the number is odd and do nothing
Next number

Find the maximum number in a list


1,3,5,6,2,8,9,10,11,2,4

maxNumber = 0
For every number in the list
if the number is greater than maxNumber
assign maxNumber to the new number found
Next number

# When the list is finished


Print maxNumber

List all even numbers from 0 to 1000


2,4,6,8,10,12....998,1000
For number x = 0 to 1000
x=x+2
print x
Next number

Study the algorithms above and see if you can improve or change them to
achieve the same result.

• Design an algorithm that lists all odd numbers between 50 and 500
• Design an algorithm that adds all numbers between 1 and 100
• Design an algorithm that finds the sum of all even numbers between 100
and 500

15
An Example of Applying Computational Thinking
Assume that you are required to develop an
algorithm to draw the shape on the right. How
can you apply computational thinking to this
problem, develop the solution/algorithm, and
later use a computer language called Python to
draw this shape?

If you divide the shape into four parts, examining


each part carefully, you will notice that the shape
is made up of squares. Each square is rotated
slightly by a small angle. This process of discovery
is called decomposition.
If you draw one square, then change the angle
slightly, draw the next square, and repeat this
multiple times, you will get the shape. Seeing
the shape is pattern recognition.
There are other lines in this shape that are created by having many
squares drawn at different angles. If you spend too much time at this
stage trying to understand how they have been created, you might
get confused. Focusing on the big picture and finding the most
important part of the problem is called abstraction.

The next step is writing the solution step-by-step using simple


language. This is called algorithm.

16
What Does “Algorithm” Mean in Computer Terms?
An algorithm is a step-by-step process for producing a solution to
a problem which can be translated into computer code. There are
four main components of an algorithm: data acquisition,
sequence, selection, and iteration. Writing an algorithm to solve a
simple problem may not require all these components. An
algorithm is usually written in plain human language, and then
translated to a high-level programming language such as Python,
Java, C, etc.

Let us develop an algorithm for our Example


1.1. As we noted, this shape is made up of
squares. After we draw one square, we change
the angle slightly and then draw the next
square, and so on.
How to draw a square:

This should be simple. The instruction for drawing a square can be


written as follows:

Move pen forward by 100 points


Change the angle to the right by 90 degrees
Move pen forward by 100 points
Change the angle to the right by 90 degrees
Move pen forward by 100 points
Change the angle to the right by 90 degrees
Move pen forward by 100 points

The above algorithm describes how to


draw a square. The next step is to convert
it to a computer code.

17
Programming Language
Computer language, also referred to as programming language, is a
formal language used to communicate commands to a machine,
typically a computer. It is used to create a program to implement a
specific algorithm.

There are many computer languages available today and their use
depends on what technology the finished program will run on. In
addition, each programming language has unique capabilities and a
set of functions that play a role in choosing which one to implement
a particular algorithm.

Here are some examples of programming languages and their typical


uses:

• Java: Used to create programs for mobile phones, web sites, personal
computers, and many other platforms.
• C#, Visual Basic: Used to create programs that run on Microsoft products.
• Swift: Used to create programs that run on Apple products.
• JavaScript: Used to write games and other programs that run on web browsers.
• Python: One of the latest computer languages that has unique capabilities and
can run on many devices.

In this course we will be using Python. We will use a website called https://
repl.it to implement algorithms.

18
Why Python Programming Language?
Python is one of the most popular programming languages. In
recent years, it has gained more popularity due to its readable
code, powerful libraries, wide range of applications, and growing
and active community. According to an IEEE survey, Python is the
fourth most popular language, and the most popular introductory
programming language in US universities. The ability to connect to
a wide range of data sources, integrate with many applications
including machine learning, artificial intelligence, and motion
graphics, has made it one of the main choices to develop
applications that work on all platforms and computer devices.

One of the reasons for Python’s popularity is the availability of a


powerful, ready to use and efficient library of codes.
Here are the most widely used Python libraries:

NumPy is the fundamental package for scientific


computing in Python.
SciPy (pronounced “Sigh Pie”) is a Python-based
ecosystem of open-source software for
mathematics, science, and engineering.
Pandas is an open source library providing high-
performance, easy-to-use data structures and data
analysis tools for the Python programming language.

matplotlib is a Python 2D plotting library which


produces publication quality figures in a variety of
hardcopy formats and interactive environments
across platforms.

19
Translating an Algorithm Into Python Code
In this book, we are using Python as our high-level programming
language. We are also using a specific graphical library that will
help us draw various shapes and objects. This library is called
“turtle.” In programming, the library refers to a code that is
already written and can be used to develop another code. The
turtle library has built-in commands that make it easy to draw an
object. For example, if you want to draw a line with a length of
100 points, you can simply use the command forward(100). To
access another library in Python, you need to use the keyword
import.

For example, to connect turtle to our code, we need the following


line:
import turtle as t

The above line connects our code/program to the turtle library and
creates an object with the name t. Now we can make it perform
some actions. For example, we can instruct it to move forward by
100 points.
t.forward(100)

The result will be a line that is 100 points


long.
t.left(90)

The head of the arrow will change to the left by


90 degrees.
Adding another t.forward(100) will draw a
vertical line starting from the end point.

20
Drawing a Square in Python - turtle
You are now ready to complete the square. You need to simply
write the same instructions two more times. What you have
done so far is translated the algorithm for drawing a square
from a human language into a high-level computer language.
We used Python and one of its libraries called turtle.

Here is the full code to draw a square:

Code Explained

● Line 1: This line imports turtle and creates an object with the
name t.
● Line 3: Asks the object t to move forward by 100 points (or
pixels).
● Line 4: Changes to the left by 90 degrees.
● Lines 5 to 9: Repeats the same processes of lines 3 and 4.
At this point the square is complete.
● Line 10: Changes the angle by 5 degrees to the left.

21
The for Loop
The for loop repeats a block of code for a number of times. In
this example, we will repeat drawing the square 20 times.

Ends
The structure of the for loop when
i =19
starts with the keyword for in
lower case. A variable shouldbe
used as a counter. In this case for i in range(1,20):
we use i as a counter, but you
can use any name for the
variable. The keyword in range This isthe This loop
counter startswith
is required. i =1

The range of values must be added between brackets and


separated by a comma. Each for loop line must end in a colon.
The following lines that belong to the for loop must be indented to
start under the letter r in the word for.
Here is the full code to draw a square:

Code Explained

● Line 3: This line starts at the same level as line 1. The for loop
is using i as a counter and starts from 1 and runs to 19. Please
note that it stops before 20 is reached.
● Lines 4 to 11: These lines are indented to the right. They all
start at the same level as the letter r of the for loop. This
means they all belong to the for loop and will be repeated.

22
Examples

Using Python and turtle draw the following


image:

23
Examples

Using Python and turtle draw the following image. Use


penup and pendown. Also, you need to change the color
using function color.

24
Examples

Using Python and turtle draw the following image.

25
Exercises
Now it is time to demonstrate the creativity and competency
that you have developed so far. Please try all these exercises
and submit your code through repl.it

Exercise 1: Draw the following shapes:

Exercise 2: Draw a house or a car. You are free to decide the size
of the house and the model of the car. Try to show off your best
creativity and skills.
Exercise 3: Use the for loop to produce your best art.
Exercise 4: The table below provides additional turtle commands.
Use them to enhance your code for exercises 1, 2, and 3.

Methodor Required Description


Command Parameters

forward amount Moves the turtle forward by the specifiedamount

backward amount Moves the turtle backward by thespecified


amount

right angle Turns the turtle clockwise

left angle Turns the turtle counter clockwise

penup none Picks up the turtle’s pen

pendown none Puts down the turtle’s pen to startdrawing

color color name Changes the color of the turtle’spen

fillcolor color name Changes the color the turtle will use to fill a
polygon

position none Returns the current position

goto x,y Moves the turtle to positionx,y

shape shape name Should be ‘arrow’, ‘classic’, ‘turtle’, or ‘circle’


26
Data Types and Variables
This section aims to develop your knowledge and skills in
the following areas:

• Explain the need for data types using real life scenarios.
• Classify different data types which can be used to
maintain program data.
• Apply the rules for variable names.
• Use arithmetic operators to perform calculation in
Python.
• Apply the Precedence Rules of arithmetic operators.

27
Data Types and Variables
In our daily life we use numbers and text to communicate and
perform certain processes. Numbers and text are called data types.
In Python and most programming languages, text is referred to as a
string. There are different types of numbers. For example, suppose
we want to know how many students are sitting in a classroom. Of
course we will not have 15.5 students, so we will use a whole
number, or integer. An integer is represented in Python as int. But if
we are dealing with prices of items where we need to use fractions,
then we will use float.

Python is very flexible with data types. You can easily change data
types.

Variables:

Technical Definition of a Variable: A variable is a memory


location where a programmer can store a value.

Variables are used to store data. For example, a variable such as


price will have different values based on the product. Another
example is id. Your id is different from other students. We
represent variables by using letters or words.
Variable is the name given to the physical location of RAM (Main
memory). These variables can be used to hold values that are like
numbers, text, Boolean values and other types. The values of the
variable can change.
Variable in general are of two types:

• Local Variable
• Global Variable

28
Local variables are the variables that are only referenced inside
the function in which it is declared. It is not accessible outside the
function.
Global variables are explicitly declared as global and can be used
in the entire program. These variables can be referenced from
any part of the program.
It is important to declare the variable by giving a valid name to it
before using it. While declaring a variable the type of variable
based on the values that are going to be stored on it should be
mentioned.
In python, it is not necessary to mention the type of the variable
while declaring the variable. The variable will take up the type of
the value that is assigned to it.
If a variable is assigned a number without decimal then the
variable is integer variable, and if we reassign a decimal value the
variable will become a float variable.

Python variables are created when they are first assigned with a
value. It is always important that the variable must be assigned
before being referred in the code.
Rules for Naming Variables:

● Must begin with a letter (a - z, A - B) or underscore (_)


● Other characters can be letters, numbers or _
● Case Sensitive. Upper case is different from lower case
● Can be any (reasonable) length
● There are some reserved words which you cannot use as a variable
name because Python uses them for other things

29

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy