Download as pdf or txt
Download as pdf or txt
You are on page 1of 98

Edited by: Mr.

Adnan Jabado
Programming part by: Mr. Ibrahim Fattal

COMPU-TECH
AND
ROBOTICS

Level 10
Introduction
Introduction
We live in an ever-advancing era. The pace at which technological development is
progressing demands a more immense understanding of how computers think and an
easier approach to practically operate and communicate with the devices around us.

The introduction and development of computer-oriented skills are becoming a requirement


for both children and adults. This series of books helps close the gap between the complex
concepts of the digital world and the human mind in a way that enhances our daily
interaction with digital systems as a whole.

Highly effective methods have been used in this series to put the students in direct contact
with advanced programming and robotics concepts using very friendly approaches and
ensuring that the students gain a set of benefits.

The benefits of learning about computers and robotics range from personal ones to
career-impacting ones, like improved critical thinking, a stronger independent work ethic,
a greater sense of empowerment, better career options, an open perspective towards
programming, high problem-solving skills, a practice for curiosity and creativity, and future-
proof knowledge.

This book will further enhance the students’ skills in spreadsheet and content editing
programs like Excel, Word, and PowerPoint. It will also introduce them to website building
and programming robotics, familiarizing them with basic HTML tags and using variables
in an Arduino system.

The students’ early exposure to computers in healthy ways will build up to a more efficient
time with digital machines later on as they grow up. This book aims to strengthen this
vision.

DAR EL CHIMAL PRINTING - PUBLISHING -


INTERNATIONAL Co. DISTRIBUTING

Tripoli, Lebanon - P.O.Box 57 - Tel.: (06) 411311, 411611 - Fax: 9616410263


E-mail: info@darelchimal.net - Website: www.darelchimal.net
All rights reserved - Edited and Revised Edition 2022

All rights reserved. No part of this publication may be reproduced or utilized in any form or by
any means, electronic or mechanical, including photocopying, recording or by any information
storage and retrieval system, without prior permission in writing from the publisher.
Table of Contents

HTML and JavaScript 5

Chapter 1 - Introduction to JavaScript 6

Chapter 2 - JavaScript and HTML 15

Python graphics 29

Chapter 3 - Reviewing turtle graphics basics 30

Chapter 4 - More turtle navigation 35

Chapter 5 - Using colors with turtle graphics 43

Chapter 6 - Optimizing your code – Using functions 48

Chapter 7 - Advanced topics in turtle graphics: Interaction 56

and decision-making

Introduction to Networking 70

Chapter 8 - Networks basics 71

Chapter 9 - Network hardware and cabling 78

Robotics with Gravity Intermediate Kit for Arduino 84

Chapter 10 - The Arduino microcontroller 85

Chapter 11 - First Code with Arduino 88


PREFACE
Comparing learning 25 years ago and now, a real revolution has happened since the
introduction of the Internet, smartphones, tablet devices, and different powerful
desktops / laptops. In the past, research was done using tons of books and references,
which required a lot of reading and, of course, a lot or writing and laying out the final
paper document by hand. Nowadays, we can access information within seconds using
the Internet from almost anywhere, even smartphones.
Teaching is taking a new perspective; classrooms are turning into big interactive
audiovisual rooms, using smart boards, tablets, and laptops.The development of Virtual
Reality environments (VR) is making it possible for students from anywhere in the
world to visit Egypt’s Pyramids, for example, without moving from their classroom.
Skills are instantly assessed and lesson content is becoming interactive with the help
of these technologies.
Cars are becoming more autonomous, houses are becoming smarter, and robots are
becoming more intelligent using Artificial Intelligence and Machine Learning technics.
Even if technology is apparently taking over teaching (online educational websites, free
or paid pdf books and documents, instructional videos,YouTube…) and other aspects
of our lives, books are still the best way to learn any skill in a very structured way.
In this context, this series of computer books will guide you in every step of your
computer-learning journey, from general office applications like Microsoft Word, Excel,
and PowerPoint, passing by programming environments like Scratch and Python, and
finishing with ICT general knowledge and robotics.
By completing all levels, you should achieve a solid base in each topic, and then it will
be up to you to practice and reach far beyond the contents of these books.
This series of computer books can be used by anyone, not only by school students.
Furthermore, we shall continuously evolve the content in order to meet your
expectations, as students or young adults.
“TELL ME AND I FORGET.
TEACH ME AND I REMEMBER.
INVOLVE ME AND I LEARN.”
(BENJAMIN FRANKLIN)
Webpages Authoring with

HTML and
JavaScript
1
Introduction to JavaScript
Introduction
As you already know, a computer program or software is a series of instructions that
can be understood and followed by a computer.
Introduction
The JavaScript programming language is used to write programs that runs in web
As you already know, a computer or software program is a series of instructions that can be understood
pages. JavaScript can control how a web page looks or make the page respond when a
and followed by a computer.
viewer clicks a button or moves the mouse (make a page interactive).
The JavaScript programming language is used to write programs that run on web pages. JavaScript can
control how a web page looks or make the page respond when a viewer clicks a button or moves the mouse
(It Your first
makes the pageJavaScript
interactive). code
There are many JavaScript editors on the market (free or paid). We are going to use
thefirst
Your Google Chrome
JavaScript codebrowser as an editor. Google Chrome have a built-in JavaScript
console.
There In order
are many to access
JavaScript editorsit,onopen a new(free
the market pageorinpaid).
yourWe
browser and
are going to type about:blank
use the Google Chrome
browser
in theasaddress
an editor.bar.
Google Chrome
A blank has
page a built
will in JavaScript
be displayed console.
in your In orderPress
browser. to access
the it,
keyopen a new
page in your browser
combination <ctrl>and+type about:blank
<shift> in the
+ j and you address
will bar. JavaScript
see your A blank page will beappear:
console displayed in your
browser. Press the key combination <ctrl> + <shift> + j and you will see your JavaScript console appear:

This
This console,
console, as will
as you you see,
will is
see, is excellent
excellent for testing
for testing all the
all the short short programs
programs that you willthat you willThe
be writing.
blinking cursor
writing. The(|)blinking
next to acursor
right-angle bracket
(|) next to a(>), is called prompt.
right-angle bracket (>), is called prompt.
When
When youyou enter
enter codecode
at theatprompt
the prompt
(cursor)(cursor)
and pressand press
enter, enter, JavaScript
JavaScript should
should execute your code and
display the result
execute, your(ifcode
any) and
on the next line.
display theType the(if
result following
any) oninto
thethe console:
next line. Type the following
5 *into
2; the console:
5 * 2;
Now press enter key on your keyboard. JavaScript should output the answer (10) to this simple calculation
Now press enter key on your keyboard. JavaScript should output the answer (10) to
on the following line:
this simple calculation on the following line:

7
Simple, isn’t it? Let’s try another example. Type in the following code:
Simple, isn’t it? Let’s try another example. Type in the following code(If you want to go to the next line
withoutSimple,
executing theit?
isn’t code, usetry
Let’s Shift + Enter):
another example. Type in the following code:
var repeatNumber = 5;
var repeatNumber = 5;
for (var i = 0; i < repeatNumber; i++) {
for (var i = 0; i < repeatNumber; i++) { console.log(i + “ =^.^=”);
console.log(i + " =^.^=");
} }

After pressing the enterthe


After pressing key,enter
you should have should
key, you the following
have output:
the following output:

As youAs noticed, the program


you noticed, theincludes
program lotsincludes
of symbols, including
lots parentheses
of symbols, (), semicolons
including ;, curly
parentheses (),brackets
{ }, plus signs +, and;,some
semicolons curlywords like var,
brackets for and
{ }, plus console.log.
signs All these
+, and some wordssymbols and for
like var, words
andare part of
JavaScript’s syntax to create working programs.
console.log. All these symbols and words are part of JavaScript’s syntax to create
When you’re
workinglearning a new programming language, one of the trickiest parts is getting used to the rules
programs.
for how to write different kinds of instructions to the computer. When you’re first starting out, it’s easy to
When you’re learning a new programming language, one of the trickiest parts is
forget when to include parentheses, or to mix up the order in which you need to include certain values. But
getting
don’t worry, used
as you to the you’ll
practice, rules start
for how
to gettoused
write different kinds of instructions to the
to it.
computer. When you’re first starting out, it’s easy to forget when to include
parentheses, or to mix up the order in which you need to include certain values. But
Data Types and Variables
don’t worry, as you practice, you’ll start to get used to it.
Data is information that we store in our computer programs. For example, a user name is data, and so is a
password. Even the color of a car, its horsepower, brand, etc., is data.
Data Types and Variables
In JavaScript, there are three basic types of data: numbers, strings (text), and Booleans.
Data is information that we store in our computer programs. For example, a user
Numbers are used for representing numbers of course! For example, your age can be represented as a
name is data, and so is a password. The color of a car, its horsepower, brand etc. All
number, and so can your height. Numbers in JavaScript look like this:
this information is data.
5; 6.75; 1.75;
In JavaScript, there are three basic types of data: numbers, strings (text), and
StringsBooleans.
(text) are used to represent text. Your name, password, address, email, etc., can be represented as a
string in JavaScript. Strings are written in JavaScript between double quotes:
Numbers are used for representing numbers of course! For example, your age can be
“Hi, this is a string”; as a number, and so can your height. Numbers in JavaScript look like this:
represented
“Welcome to JavaScript programming”;
5; 6.75; 1.75;
Booleans are values that can be either true or false. For example a Boolean value about whether a door is
locked or not. Another could be whether a person knows programming or not. Example: true; false;

8
You may have noticed that all of the JavaScript commands that we used,
end with a semicolon (;). Semicolons mark the end of a particular
JavaScript command or instruction / statement). Without it you will
have a syntax error!
You may have noticed that all of the JavaScript commands that we used end with
a semicolon (;). Semicolons mark the end of a particular JavaScript command or
instruction / statement). Without it you will have a syntax error!
Numbers and Operators
Data is information that we store in our computer programs. For example, a user
JavaScript
Numbers lets you perform basic mathematical operations like addition, subtraction,
and Operators
Data multiplication, andwe
is information that division.
store in The symbols programs.
our computer used for these calculations
For example, are lets
JavaScript +, -, you
*, and /,
perform
basic which are called
mathematical operators.
operations like addition, subtraction, multiplication, and division. The symbols used for
these The
calculations are +,
JavaScript -, *, andcan
console /, which are called
be used operators. i.e. you type in the expression you
as a calculator
The JavaScript console can
want to calculate be used the
followed as aenter
calculator.
key onForyour
instance, you typeif in
keyboard; the expression
there is no erroryou
in want
your to
calculate followed
syntax, by the enter
the console willkey
giveonyou
yourthe
keyboard;
answerifon there
theisline
no error in youryour
following syntax, the console will
expression.
give you the answer on the line following your expression. Example:
Example:

When writing more complex calculations (including multiple operators), the


answer will depend on the order that JavaScript does each operation. In math as
well as in JavaScript, the rule is that multiplication and division always take place
before addition and subtraction. In the event that parentheses are used in your
calculations, Javascript will evaluate what’s inside before applying the above rule.

Example 1:
(2 + 3) + 5 * 10;
55
Example 2:
The result of the following calculations will be different:
12 / 2 + 4; and 12 / (2 + 4);
The first expression will give as result 10 and the second one will give 2 as result.

9
In the following table, you can find a summary of the main numbers’ operators used
in JavaScript:
In the following table, you can find a summary of the main numbers’ operators used in JavaScript:

Operator Description Example


+ Addition 5+6
- Subtraction 12.5 – 8.25
/ Division 9/3
* Multiplication 3*6
% Modulus (division remainder) 8%3
** Exponentiation 2 ** 3

Variables
As you already Variables
know, variables are locations (think of named boxes) in the computer memory to store
data. To createAs
a new
youvariable,
alreadyyou mustvariables
know, use the keyword var, followed
are locations ofthe
(thinkby nameboxes)
named of the variable. For
in the computer
example, to create a newto
memory variable
store called
data. studentAge,
To create awe
newshould write: you must use the keyword var,
variable,
var studentAge;
followed by the name of the variable. For example, to create a new variable called
studentAge, we should write:
When the console writes back following an instruction “undefined” in response,
var studentAge;
this isn’t an error! That’s just what JavaScript does whenever a command doesn’t
return a value (no calculation or explicit output).
In the code above, When we’vethe
created
console a writes
new variable calledan
back following studentAge. In order to give
instruction “undefined” in or
In theto change
code above,its value,
we’ve we use
created the
a new
response, equal
thisvariable sign,
error!followed
isn’t ancalled That’s justbywhat
studentAge. Inthe wanted
order to givevalue:
JavaScript or to whenever
does change its value,
we use the studentAge
var equal sign, followed16;by the wanted
=a command doesn’tvalue:
return a value (no calculation or explicit output).
var studentAge = 16;
This operation is called assignment i.e. we are assigning the value 16 to the variable
This operation
studentAge. As assignment
is called a result of i.e.
thisweoperation,
are assigning
thetheJavaScript
value 16 tointerpreter
the variable studentAge. As a result
has knowledge of
of thisthis
operation,
variable which value is currently 16. To verify this assumption, type studentAge;To
the JavaScript interpreter has knowledge of this variable whose value is currently 16.
verify this, type studentAge; in the interpreter followed by enter. You should have as response the value 16:
in the interpreter followed by enter. You should have as response the value 16:

If we If weto
need need to aupdate
update variableavalue,
variable value,
we use we use
the equal (=)the
signequal (=)the
without varwithout
sign keyword:the var
keyword:
studentAge = 20;
studentAge = 20;
20
20
When you change a variable value, the previous value is forgotten, and you won’t
be able to access it again.
when you change a variable value, the previous value is forgotten, and
10 you won’t be able to access it again.
Let’s try a slightly more complex example. Type in the console the following code followed by enter:
var carSpeed = 85; // speed in Km/h
var travelTime = 2.3; // time in hours
var distTravel = carSpeed * travelTime;
distTravel;

You should have as result the following number:


195.49999999999997

The first two created variables were directly assigned with a value using the following syntax:
var varName = value.

The third variable (distTravel) was assigned by using a formula (carSpeed * travelTime) involving a
calculation with the two previous variables.

The variable name at the last line will display in the console the current variable value and gives us 195.499.

Variable Name Rules


There are some rules to be followed in variable naming:
• Variable names are case sensitive: for example, userAge is not the same as UserAge; JavaScript will
give you an error. Of course, misspelling the variable will also give you an error.
• You cannot use spaces in a variable name; for example, the name “user Age” is not acceptable and
will cause an error.
• A variable name must begin with a letter, an underscore (_) or a dollar sign ($). • A variable name can
only contain letters, numbers, underscores, or dollar signs.

One easy way (and most common to all programmers) to name a variable is to have it start with a lowercase
letter, and then capitalize each of the following words in the name. Example:
var carSpeed = 0;
var userAge = 16;
var numberOfClients = 100;
var number2 = 6;

All of the above names are valid as variable names.

Through this book, we will use this naming convention for the variables.

11
Through this book, we will use this naming convention for the variables.

Practice
Practice11
Using the JavaScript console, calculate the distance in meters having the following
Using the JavaScript console, calculate the distance in meters having the following variable declared:
variable declared:
var distKm
var distKm= =5.75;
5.75;
Useaavariable
Use variable to
tostore
storethethe
answer in meters.
answer in meters.

Solution
Solution

Practice 2
Practice 2
Calculate the hypotenuse of a rectangle triangle knowing the two other sides A and B:
Calculate the hypotenuse of a rectangle triangle knowing the 2 other side A and B:
var sideA
var sideA= 7.5;
= 7.5;
var sideB
var sideB= 6;
= 6;
Use
Useaa variable
variable totostore,
store, then
then display
display the wanted
the wanted result. result.

Solution
Solution

TheThe “undefined”
“undefined” response
response from
from thethe consoleisisnot
console notan
anerror
error message;
message; you can notice
youthat
canit’s displayed
notice that it’sonly after entering
displayed a line
only after of instructions
entering a line of without any explicit
output request.
instructions Onany
without the other hand,
explicit yourequest.
output can notice Onthat
theno “undefined”
other message was
hand, you
canprinted
noticeafter
that the “hypo” line, message
no “undefined” which ledwasto display
printedthe value
after theof the variable.
“hypo”
line, which led to display the value of the variable.
Special Operators: ++ and --
Special
Increasing Operators:
and decreasing ++values
variables and -- used in programming, especially when we need to add
is often
or subtract 1 from
Increasing anda variable value.variables
decreasing This operation is called
values incrementing
is often or decrementingespecially
used in programming, in programming.
This is done using the “++” operator for increasing a variable by 1, and using “--” for decreasing a variable
when we need to add or subtract 1 from a variable value. This operation is called
by 1. These operators are used in front or after a variable name; the operation outcome (incrementing or
incrementing
decrementing or decrementing
a variable) in the
is the same, but programming. This is done using the “++” operator
output won’t be!
for increasing a variable by 1, and using “--" for decreasing a variable by 1. These
12
operators are used in front or after a variable name; the operation outcome
operators are used in front or after a variable name; the operation outcome
(incrementing or decrementing a variable) is the same, but the output won’t be!
Let’s looktake
Let’s at anan
example in order
example to better
in order understandthe
to highlight thedifference.
difference. Using the JavaScript console on your
Google
UsingChrome browser, enter
the JavaScript the following
console on yourcode, line Chrome
Google by line, and see the changing
browser, values
enter the of the variable:
following
code, line by line, and see the changing values of the variable:

As we expect, each time we use the “++” operator, the value of the variable will
increase by 1, and as a result of the operation, we’ll have 1 printed as a result of the
As we expect, each time we use the “++” operator, the value of the variable will increase by 1, and as a
second
result of theinstruction, andhave
operation, we’ll so on. Whenasthe
1 printed “--" isofused,
a result the variable
the second value
instruction, andwill beWhen the “--”
so on.
is used, the variable
decreased by 1,value will relevant
and the be decreased by 1,
value and
will bethe relevant value
displayed, andwill be displayed, and so on…!
so on…!
TryTry
thethe
nextnext
example and type
example andit type
instruction by instruction
it instruction to see the results:
by instruction to see the results:

You may
You havehave
may noticed the following:
noticed the following:
• The final
• The value of the
final variable
value is the
of the same inisthe
variable the2 same
examples before
in the incrementing
2 examples of the variable value.
before
• When thedecrementing theafter
“++” operator isofused value.name, the current value of the variable is printed, then
the variable
variable
the incrementation
• When theis“++”performed!
operator is used after the variable name, the current value of
the variable is printed, then the incrementation is performed!
Don’t forget, the “++countCars;” instruction is the same as:
countCars
Don’t = countCars
forget, the + 1; instruction is the same as:
“++countCars;”
countCars = countCars + 1;

If you need to increment / decrement more than 1, you can use the “+=” or “-=”
operators: 13
If you need to increment / decrement more than 1, you can use the “+=” or “-=”
If you need to increment / decrement more than 1, you can use the “+=” or “-=” operators:
operators:

What
What wewe applied
applied forfor
thethe
“+”“=”
andand
“+”“-“ (incrementing/…)
operators are /also possible with the
(incrementing
“x” and “/” operators.
decrementing) is also possible with “+” and “/” operators!

14
2
JavaScript and HTML
So far, you learned the following:
• Defining variables in JavaScript.
• Writing operations in JavaScript.
Let’s combine what you learned about HTML tags with JavaScript, and build advanced webpages.

From now on, you will be implementing all exercises and practices using the Notepad++ editor.

Integrating JavaScript with HTML


Let’s start with a small HTML / JavaScript code to demonstrate this integration. Open your Notepad++
application and enter the following HTML code:
<html>
<head>
<title>HTML + JavaScript Page</title>
</head>
<body>
<h1>Hello everyone!</h1>
<p>Page with JavaScript</p>
<script>
var msgDisplay = “Pleased to finally use JavaScript with HTML.”;
document.write(msgDisplay);
</script>
</body>
</html>

You should have as output:

Hello everyone!
Page with JavaScript
Pleased to finally use JavaScript with HTML.
Note the use of the <script> </script> tags:
<script>
var msgDisplay = “Pleased to finally use JavaScript with HTML.”;
document.write(msgDisplay);
</script>

Everything between the tags is treated as JavaScript and run by the JavaScript interpreter. Note the
document.write(msgDisplay) instruction; It will let you “write” on the webpage. As it is in the HTML code
after the paragraph tags, the sentence will be displayed by the end of the page.

Congratulations, your first “hybrid” webpage.


16
Alerts and Prompts (Input)
JavaScript provides different built-in functions to display popup messages for different purposes or display
a popup to take a user’s input value.

The alert()
This function is to display a popup message to the user. This popup will have an OK button to close the
popup.
Example:
Alert(“Welcome to the website”)
In the following paragraphs, we shall extend this function to the confirm box, which will make it possible
to introduce 2 buttons: OK and Cancel.

The prompt()
This JavaScript instruction simulates a user input using the console; as result, a pop-up window appears in
your browser window with a text field to enter the wanted value.
The Prompt function takes two string parameters. First parameter is the message to be displayed and
second parameter (which is optional) is the default value which will be in input text when the message is
displayed.
Example of use: var age = prompt(“Please enter your age in years”, “15”);

In this example, the variable age will store the value returned by the user, which is 15 by default.

var tenure = prompt(“Please enter preferred tenure in years”, “15”);


if (tenure != null) {
alert(“You have entered ” + tenure + “ years” );
}

Conditional if … else
There are two forms of conditional statements in JavaScript: if statements and if...else statements. An if
statement is used to execute a group of instructions if a condition is evaluated to true. An if...else statement
executes a group of instructions if a condition is true and another piece of code if not.
Example:
var number = 16;
if (number >= 0) {
console.log(«The number you entered is positive!»);
}

Of course, this code will display the message “The number you entered is positive!”, because variable
“number” has 16 as value; Change the code and assign -8 to the variable “number”, and run again the code;
You will only get “undefined” as output, in fact nothing is displayed.

17
If we rewrite the code and add an else statement, and run it with a negative value, the solution would be
excellent: a classification for numbers as positive or negative.
var number = -9;
if (number >= 0) {
console.log(“The number you entered is positive!”);
} else {
console.log(“The number you entered is negative!”);
}

Note the use of { } to group all conditions related to the if or else statement.

Else - if statement
The else if statement is used to check a sequence of conditions and execute instructions related to each
condition.
Example:
var number = -9;
if (number > 0) {
console.log(“The number you entered is positive!”);
} else if (number==0){
console.log(“You entered Zero!”);
} else {
console.log(“The number you entered is negative!”);
}

In the following, you can find a table summarizing all comparison operators that you can use as a condition
in the if – else if statements:

Operator Symbol Meaning

== Equal

< Less than

> Greater than

>= Greater than or equal

<= Less than or equal

!= Not equal (different)

18
You can always combine logical operators to create more complex conditions:

Operator Meaning Example

&& and (x < 5 && y > 10)

|| or (x == 5 || y < 0)

! not ! (x == 6)

The confirm() function


This function is very useful when you need the user’s confirmation to proceed. For example, you want to
take user’s confirmation before saving or deleting data. The confirm() function displays a popup message
to the user with two buttons, OK and Cancel. You can check which button the user has clicked and proceed
accordingly.
The following example demonstrates how to display a confirm box and then checks which button the user
has clicked.
Example: Confirm Box
var userPreference;
if (confirm(“Do you want to save changes?”) == true) {
userPreference = “Data saved successfully!”;
} else {
userPreference = “Save Cancelled!”;
}

Practice 1
Write a small JavaScript code which takes as input a temperature in Fahrenheit and converts it to Celsius.
Integrate your JavaScript code within a HTML document.

Solution
<html>
<head>
<title>Temp Converter</title>
</head>
<body>
<h1>Welcome to the temperature converter</h1>

19
<body>
<h1>Welcome to the temperature converter</h1>
<script>
<script>var tempF = prompt("Please enter the Fahrenheit temp", "0");
var tempF
var= prompt(“Please
tempC = (tempF enter-the32)*5/9
Fahrenheit temp”, “0”);
alert("The Celsius temp is: "+tempC)
var tempC = (tempF - 32)*5/9
</script>
alert(“The Celsius temp is: “+tempC)
</body>
</script>
</html>

</body>
</html>

Screenshots from the solution:


Screenshots from the solution:

Practice 2
Practice 2
In this example, you will try to write the answer on the web page: write a small JavaScript code which takes
as input your age in years and displays it on the website in months.

Solution
<html>
<head>

20
<title>Age Converter</title>
</head> In this example, you will try to write the answer on the web page: write a small
JavaScript code which takes as input your age in years and display it on the website in
<body> months.
<h1><font color=darkgreen>Welcome to the Age converter</font></h1>
Practice 2 - Solution
<script>
var ageYears = prompt(“Please
<html> enter your age in years”, “0”);
<head>
var ageMonths = <title>Age
ageYears * Converter</title>
12;
document.write(“<h2><font
</head>
color=red>”);
<body>
document.write(“Your age “+ageYears);
<h1><font color=darkgreen>Welcome to the Age converter</font></h1>
<script>
document.write(“var
in months is: =“+prompt("Please
ageYears ageMonths); enter your age in years", "0");
var ageMonths = ageYears * 12;
document.write(“</font></h2>”);
document.write("<h2><font color=red>");
</script> document.write("Your age "+ageYears);
document.write(" in months is: "+ ageMonths);
</body> document.write("</font></h2>");
</script>
</html>
</body>
</html>

Screenshots from the solution:


Screenshots from the solution:

21
Solution discussion
In order to integrate HTML commands into JavaScript and make the language execute
Solution discussion
In order to integrate HTML commands into JavaScript and make the language execute them, use the
document.write(…) instruction. The advantage is that you will have a non-static HTML, you can
control the contents during the page loading.
Remember, if you need to start a new line, the HTML tag is <br />.

Practice 3 – If - else
Write a JavaScript code which lets you ask for 2 numbers, and then display their average. Layout out your
page in HTML, as well as the answer. Be careful not to do a calculation if no numbers are entered.

Practice 3 – Solution
<html>
<head>
<title>Average Calc</title>
</head>
<body>
<h1><font color=darkgreen>Average of 2 Numbers</font></h1>
<script>
var num1 = prompt(“Please enter the 1st number”, “0”);
var num2 = prompt(“Please enter the 2nd number», “0”);
var avg = (num1+num2)/2;
document.write(“<h2><font color=blue>”);
document.write(“The average of “+num1);
document.write(“ and “+ num2+” is “,avg);
document.write(“</font></h2>”);
</script>
</body>
</html>

Let’s suppose that we enter 16 for the 1st number and 13 for the second number. We will get the
following webpage as answer:

22
Let’s suppose that we enter 16 for the 1 number and 13 for the 2 number, you will
get the following webpage as answer:

What happened?
What happened?
The JavaScript
Theprompt()
JavaScript function always
prompt() deliversalways
function a string.delivers
If nothing is entered,
a string. and the is
If nothing user still clicks
entered, and
OK, an empty string is simply returned. However, if a person refuses to respond and clicks CANCEL, the
the user still clicks OK, an empty string is simply returned. However, if a person
prompt JavaScript function will return null.
refuses to respond and clicks CANCEL, the prompt JavaScript function will return null.
So, you need
So,to you
be careful
need whento bemanipulating
careful when variables storing the
manipulating result of astoring
variables prompt.the result of a prompt.
When working
When withworking
strings, string1 + string2string1
with strings, will result in concatenating
+ string2 will resultthein2 concatenating
values, so if string1=”Hello”
the 2 values,
and string2=”andBye” the answer would be a string containing “HelloandBye”.
so if string1=”Hello” and string2=”andBye” the answer would be a string containing
The answer“HelloandBye”.
to this problem is to change the type of the string value sent by the prompt() instruction into a
number: thisThe
operation
answer is to thiscasting
called problem the to
entry from text
change the(string)
type oftothe
a number; and thissent
string value is done by using
by the
the parseFloat() or parseInt()
prompt() methods
instruction to cast
into a string to
a number: a decimal
this or anisinteger
operation callednumber.
casting the entry from
And the newtextsolution
(string)will
tobe by addingand
a number; a parseFloat()
this is done function
by usingto the
theprompt() call: or parseInt()
parseFloat()
methods to cast a string to a decimal or an integer number.
var num1 = parseFloat(prompt(“Please enter the 1st number”, “0”));
var num2 =And the new solution of
parseFloat(prompt(“Please thethe
enter practice will “0”));
2nd number”, be by adding a parseFloat() function
to the prompt() call:
var num1 = parseFloat(prompt("Please enter the 1st number", "0"));
var num2 = parseFloat(prompt("Please enter the 2nd number", "0"));

Practice 4 – If 4 – If
Practice
Write a JavaScript code which calculates a car speed based on a known distance
Write a JavaScript code which calculates a car’s speed based on a known distance covered between 2 towns.
The distancecovered
(in kms)between 2 towns.
and the time The distance
(in minutes) should be (in kms)toand
prompt the when
the user time the
(in page
minutes) should be
is loaded.
prompt to the user when the page is loaded.
If the calculated car speed is greater than 100 km/h, a warning in red should be prompted to the webpage.
If the calculated car speed is greater than 100 km/h, a warning in red should be added
Handle minutes and distance as integers. The answer as float.
to the webpage. Handle minutes and distance as integers. The answer as float.
Use HTML to layout your solution.
Use HTML to layout your solution.

23
Practice 4 - Solution
Practice 4 - Solution
<html>
<head>
<title>Speed</title>
</head>
<body bgcolor=azure>
<h1><font>Travel time calculation</font></h1>
<script>
var dist = parseInt(prompt(“Please enter the distance (km)”, “0”));
var travelTime = parseInt(prompt(“Please enter the travel time (min)”, “0”));
var speed = (dist*60)/travelTime;
document.write(“<h2><font color=blue>”);
document.write(“The distance is “+dist+” km<br />”);
document.write(“The time travel is “+travelTime+” minutes<br />”);
document.write(“The car speed is: “+speed+” km/h”);
document.write(“</font></h2>”);
if (speed > 100) {
document.write(“<h2 align=center><font color=red>”);
document.write(“Speed more than 100 - Danger”);
document.write(“</font></h2>”);
}
</script>
</body>
</html> </body>
</html>

ScreenshotsScreenshots
from the solution:
from the solution:

24 The switch Statement


The switch statement is built around the following important points:
The switch Statement
The switch statement is built around the following important points:
• The condition part.
• The case statements.
• The break statements.
• The default statement.
Example:
Switch (age)
{
case 15:
// code
break;

case 16:
// code
break;

case 17:
// code
break;
default:
// default statement code
break;
}
In the above example:
• age represents the variable being checked.
• Each case statement represents a possible value, if a match is found, then the execution starts till the
following break statement. This statement tells JavaScript to stop executing at this point and exit the
switch statement.
• case 16: is similar to the expression if (age == 16).
• The default statement is only executed when none of the case statements match.

Practice 5
Write a JavaScript code which will rate and display a student grade, as following:
• Grade 18 up to 20: Excellent
• Grade 16 up to 18 (not reaching 18): Very Good
• Grade 14 up to 16 (not reaching 16): Good
• Grade 12 up to 14 (not reaching 14): Acceptable
• Otherwise: Failed
You need to ask for the student name and grade when the webpage is loaded. Use the appropriate HTML
layout for the display.

25
Practice 5 – Solution
<html>
<head>
<title>Grading System</title>
</head>
<body bgcolor=lemonchiffon>
<h1><font>Student Grade</font></h1>
<script>
var stdName = prompt(“Please enter the student name”, “-”);
var stdGrade = parseFloat(prompt(“Please enter the student grade”, “0”));
document.write(“<h2><font color=blue>Hello student “+stdName+”</font></h2>”);
document.write(“For the grade “+stdGrade+”/20<br />”);
var val = “”;
if (stdGrade>= 18 && stdGrade<=20){
val=“Ecellent”;
} else if (stdGrade>= 16 && stdGrade<18){
val=“Very Good”;
} else if (stdGrade>= 16 && stdGrade<18){
} else if (stdGrade>= 14 && stdGrade<16){
val="Very Good";
val=“Good”;
} else if (stdGrade>= 14 && stdGrade<16){
} else if (stdGrade>= 12 && stdGrade<14){
val="Good";
val=“Acceptable”;
} else if (stdGrade>= 12 && stdGrade<14){
} else { val="Acceptable";
val=“Failed”;
} else {
} val="Failed";
document.write(“<font
} color=red>You got a: “+val+”</font>”);
</script>document.write("<font color=red>You got a: "+val+"</font>");
</body></script>
</html></body>
</html>

Screenshot of the webpage:


Screenshot of the webpage:

Practice 6 – switch case


26
Write a JavaScript code which will displays the number of days in a given month; for
Practice 6 – switch case
Write a JavaScript code will display the number of days in a given month; for example, if you enter October,
it should display 31.
In case of February, you should ask for the year and calculate if it is a leap year or not in order to display
the exact number of days.

Practice 6 – Solution
<html>
<head>
<title>Number of Days</title>
</head>
<body>
<h1><font>Days Calculation</font></h1>
<script>
var year = parseInt(prompt(“Please enter the year” “0”));
var monthName = prompt(“Please enter the month name”, “-”);
var leapYear = false;
var days = 0;
if ((year % 4 == 0 && year % 100 != 0) || year % 400==0) {
leapYear= true;
}
document.write(“<h2><font color=blue>Regarding the month: <b>”+monthName);
document.write(“</b>, year: <u>”+year+”</u>;</font></h2>”);
switch (monthName) {
case “January”:
case “March”:
case “May”:
case “July”:
case “August”:
case “October”:
case “December”:
days = 31;
break;
case “April”:
case “June”:
case “September”:
case “November”:
days = 30;
break;
case “February”:
if (leapYear == true) {

27
days = 29;
} else {
days = 28;
}
break;
default:
days=0;
break;
}
document.write(“<font size=+1 color=red>The number of days are: <b><u>”+days+”</u></b></
font>”);
</script>
</body>
</html>
Screenshot from the application:
Screenshot from the application:

28
3
Reviewing turtle graphics
basics
Quick review of basic commands
Quick review of basic commands
Quick review of basic commands
forward( ) Quickleft(
review
) of basic commands
penup( )
forward( ) left( ) penup(
backward( )
Quick review
forward( )
right( )
of basicleft(
commands
)
pendown( ) penup( )
backward( ) right( ) pendow
forward(
backward()) left(
right()) penup( ) )
pendown(
Using
Using the the methods
methods above,above,
write write
the
backward( the)appropriate
appropriate Python codePython
in ordercode in order
to )draw to draw
the following the
shapes.
Using the methodsright(
above, write the appropriate pendown( ) in o
Python code
following shapes.
followingabove,
Using the methods shapes.
write the appropriate Python code in order to dra
Shape 11
Shape
following shapes.
Using the methods above, write the appropriate Python code in order to dra
Shape 1
following shapes.
Shape 1
Shape 1

Shape 2
Shape 2
Shape 2 Shape 2
Shape 2

Shape 3
Shape 3
Shape 3
Shape 3 Shape 3

31
Quick review of the “for” loop
Quick review of the “for” loop
Quick review of the “for” loop
Variable to keep track of the current
Variable to keep track of the current
number of repetitions
number of repetitions

Overall number of repetitions; in


Overall number of repetitions; in
our case three times
our case three times

Instructions to repeat
Instructions to repeat

Note the indentation used. If not present, Python will


Note the indentation used. Ifgive
not apresent, PythonItwill
syntax error. represents all instructions
give a syntax error. It represents all instructions
included in the “for” loop.
included in the “for” loop.

Practice 1 Practice 1
Practice 1
Draw the following shape by using the “for” loop.
Draw the following Draw
shape by
theusing the “for”
following loop.by using the “for” loop.
shape

Practice 1 – Solution
Practice 1 Practice 1 – Solution

Solution
from turtle import *
# square sides 20
for i in range(4):
forward (20)
left (90)

# square sides 30
for i in range(4):
forward (30)
left (90)

32
# square sides 40
for i in range(4):
forward (40)
left (90)

Warning:
You probably noticed the following 3 lines in the code:
Remark:
# square sides 20
# square sides
You30probably noticed the following 3 lines in the code:
# square sides 40
# square sides 20
When working# square
with anysides 30
programming language, you include comments in the code to notate
# square
your work. This detailssides 40
what certain parts of the code are for, and lets other developers – you
included – know what you were up to when you wrote the code. This is a necessary practice,
and good developers make heavy
When working withuse
anyofprogramming
the comment system.
language, you include comments in the c
Comments in Python
notate startwork.
your with the hash
This character,
details what#,certain
and extend to of
parts thethe
endcode
of theare
physical
for, and lets oth
line. developers – you included – know what you were up to when you wrote the cod
Comments are not interpreted by the programming language.
is a necessary practice, and good developers make heavy use of the comment s
Comments in Python start with the hash character, #, and extend to the end of
physical line.
Comments are not interpreted by the programming language.
Practice 2
Draw the following shape 2 “for” loop.
by using the
Practice
Draw the following shape by using the “for” loop.

Practice 2 – Solution

33
Practice 2

Solution
from turtle import *
for i in range(3):
forward (20)
left (90)
forward (20)
penup ()
backward (20)
right (90)
forward (20)
pendown ()

Remember: There is never only 1 solution for a problem, especially in drawing figures.

34
4
More turtle navigation
More
Morenavigation
More methods
navigation
navigation
More to discover to
navigation
methods
methods methods
todiscover
discover
to discover

Moves
Movesthe theturtle
turtleMoves
totothe
thehome
the
home
turtle
position
position
to the
(0,
(0,
home
0),
0),facing
facing
position
totothe
the
(0, 0), facing to th
home()
home() home() right
rightofofthe
thescreen
screen
right of the screen

Moves
Movesthe
theturtle
turtleMoves
totothe
theposition
the
position
turtle
x,x,
to
yyrelative
the
relative
position
totothe
the
x,center
ycenter
relative to the cente
goto(x,y)
goto(x,y) //
goto(x,y)
setpos(x,y)
setpos(x,y)
/ setpos(x,y)
ofofthe
thegraphical
graphicalwindow,
of
window,
the graphical
which
whichisis
window,
(0,0)
(0,0) which is (0,0)

Sets
Setsthe
theheading
headingSets
(direction)
(direction)
the heading
ofofthe
the(direction)
turtle
turtletotoan
an
ofangle
angle
the turtle
inin to an angle in
setheading(degrees)
setheading(degrees)
setheading(degrees)
degrees.
degrees.Relative
Relativetotoyour
yourscreen,
degrees. screen,00to
Relative isisyour
always
alwaystotothe
screen, 0right,
the is
right,
always to the right,
90
90isisalways
alwaysup,
up,180
90
180istotothe
theleft
alwaysleftofof180
up, the
thescreen.
toscreen.
the left of the screen.

Clears
Clearsthe
thescreen
screen
Clears
leaving
leaving
the
the
the
screen
turtle
turtle
leaving
atatits
itscurrent
current
the turtle
position
position
at its current position
clear()
clear() clear()
and
anddirection
direction and direction
Clears
Clearsthe
thescreen
screen
Clears
and
andreset
reset
the screen
the
theturtle
turtle
andtoto
reset
the
theorigin
the
origin
turtle
(0,0),
(0,0),
to the origin (0,0),
reset()
reset() reset()
facing
facingtotothe
theright
right
facing to the right

showturtle()/hideturtle()
showturtle()/hideturtle()
showturtle()/hideturtle()
Sets
Setsthe
thestate
statetotoshow
Sets
showthe
/ /hide
hide
state
the
the
toturtle
show
turtle / hide the turtle
Resize
Resizethe
thecurrent
current
Resize
drawing
drawing
the canvas,
current
canvas,with
drawing
withoptionally
optionally
canvas,setting
setting
with optionally settin
the
thebackground
backgroundcolour
the
colour
background
ofofthe
thecanvas.
canvas.
colour
Do
Doofnot
not
thealter
alter
canvas.
the
theDo not alter the
drawing
drawingwindow.
window. To
Toobserve
drawing
observe hidden
window. Toparts
hidden partsofofthe
observe thecanvas,
hidden
canvas,
parts of the canvas
screensize(w,h,[bgcolor])
screensize(w,h,[bgcolor])
screensize(w,h,[bgcolor])
use
usethe
thescrollbars.
scrollbars.With
use thethis
With thismethod,
scrollbars.
method, one
Withone can
this
can make
makevisible
method, visible
one can make visib
those
thoseparts
partsofofaadrawing
those
drawing which
parts of awere
which wereoutside
drawing
outside the
whichthecanvas
were
canvas
outside the canvas
before.
before. before.
Set
Setthe
thesize
sizeofofthe
the
Set
main
main
the window.
size
window.
of the
Parameters
Parameters
main window. : : Parameters :
width
width––ififan width
aninteger,
integer, aasize
–size
if an
ininpixels,
integer,
pixels,ififaaasize
float,
float,
inapixels,
apercentage
percentage
if a float, a percenta
ofofthe
thesize
sizeofofthe
theof
screen;
screen;
the size default
default
of theisis
screen;
50%
50%ofofdefault
screen
screenis (0.5)
(0.5)
50% of screen (0.5)
setup(width,height)
setup(width,height)
setup(width,height)
height
height––ififan height –the
aninteger,
integer, the
if anheight
height
integer,
ininpixels,
pixels,
the height
ififaafloat,
float,
in pixels,
aa if a float
percentage
percentageofofthe the
percentage
size
sizeofofthe the
of screen;
the
screen;
sizedefault
of
default
the is screen;
is75%
75%of default
of is 75%
screen
screen(0.75)
(0.75) screen (0.75)

Set
Setthetheturtle’s
turtle’sspeed
speed
Set thetotoan
turtle’s
aninteger
integer
speed
value
value
to from
an
from
integer
00toto10.
value
10. from 0 to 10.
IfIfxxisisaanumber
numbergreater
Ifgreater
x is a than
number
than10 10or
greater
orsmaller
smaller
than
than
than
100.5,
or
0.5,smaller
speed
speed than 0.5, spe
isisset
settoto0.0.The
Thespeed
speed
is setvalues
to
values
0. The
represent
represent
speed values
the
thefollowing:
following:
represent the following:
• • “fastest”:
“fastest”:00 • “fastest”: 0
speed(x)
speed(x) speed(x) • • “fast”:
“fast”:10
10 • “fast”: 10
• • “normal”:
“normal”:66 • “normal”: 6
• • “slow”:
“slow”:33 • “slow”: 3
• • “slowest”:
“slowest”:11 • “slowest”: 1

Discovering
DiscoveringDiscovering
your
yourdrawing
drawing
your
Canvas
Canvas
drawing Canvas
As
Asyou
youalready
already
As
noticed,
noticed,
you already
all
allyour
your
noticed,
drawings
drawings
all your
are
areinside
drawings
insideyour
your
are
turtle
turtle
inside
graphics
graphics
your turtle
window,
window,
graphics window,
which
whichisis400
400pixels
pixels
whichwidth
width
is 400and
and
pixels
300
300width
pixels
pixels
and
height.
height.
300 The
pixels
Theturtle
turtle
height.
always
always
Thestarts
turtle
startsat
always
atthe
themiddle
middle
starts at the midd
of
ofthe
thegraphics
graphics
ofwindow,
window,
the graphics
facing
facing
window,
the
theright
right
facing
side
sideof
the
ofyour
your
rightscreen.
screen.
side of your screen.
Let’s
Let’sconsider
considerLet’s
the
thefollowing
following
consider code:
the
code:
following code:

36
Discovering your drawing Canvas
As you already noticed, all your drawings are inside your turtle graphics window, which is 400 pixels width
and 300 pixels height. The turtle always starts at the middle of the graphics window, facing the right side
of your screen.
Let’s consider the following code:

from turtle import *


for i in range(7):
forward (50)
left (90)
forward (50)
right (90)

Once you save and run the code above, you should get the following graphic as result:
Once you save and run the code above, you should get the following graphic as

Of course, in order to view your full graphic, you need either to maximize your t
Of course, in order to view your full
graphics graphic,oryou
window, need either
change your to maximize
code your turtle
and draw smallergraphics
steps.window, or
change your code and draw smaller
Another waysteps.
could be the use of the screensize() method, which will make
Another way could be possible
the use ofthe
theview
screensize() method,
of missing parts which
of your will make
drawing by possible the view
adding scroll of to the
bars
missing parts of your drawing by adding scroll bars to the graphics window.
graphics window.
Change your code as follow,
Changecompile
youritcode
and run
as it:
follow, compile it and run it:
from turtle import *
screensize (1000,600)
for i in range(7):
forward (50)
left (90)
You will notice that your turtle graphics window now shows scrollbars, to let you
forward (50)
right (90)and view invisible parts of your drawing.

Scrollbars
37
You will notice that your turtle graphics window now shows scrollbars, to let you scroll and view invisible
You
partswill
of notice that your turtle graphics window now shows scrollbars, to let you scroll
your drawing.
and view invisible parts of your drawing.

Scrollbars

By scrolling to the limits of the drawing


By scrolling to the limits of the drawing, you will see the wholewhole
drawingdrawing and
and you will missyou will miss nothi
nothing!
This is not the only way to solve the problem :). Another method you could use is the setup() method.
This
This method, as described in the table above, lets you change the is notofthe
dimension onlygraphics
the turtle way towindow,
solve the pr
instead of just adding scroll bars. method you could use is the setup()
By the changing the code to the following: This method as described in the table
By scr
from turtle import * change the dimension of the turtle gra
whole
setup (1000,750)
instead of just adding scroll bars.
for i in range(7):
forward (50)By the changing the code to the following: This is
left (90)
metho
forward (50)
right (90) This m
chang
instead of just adding scroll bars
By the changing the code to the f
Save and run your code. You should get the following display:
Save and run your code. You should get the following displayed:

Save and run your code. You sho

38 Using coordinates to navigate


Using coordinates
Using to navigate
coordinates to navigate
As you used forward / backward / left / right methods to navigate and make your
As you used forward / backward / left / right methods to navigate and make your drawings, let’s get into
drawings,
graphics let’s
window get into graphics
coordinates system. window coordinates system.

As it is illustrated in the figure above, the Python turtle uses a coordinates system very
similar to the mathematical coordinates system, where the turtle always stars in the
center of it with (0,0) as x and y coordinates.
S instead of using forward(distance) to move, you can do so by specifying the
As it is illustrated in the figure
coordinates of above, the you
the point Python
wantturtle usestoa with
to get coordinates system very similar
the setpos(x,y) to the
or goto(x,y)
mathematical coordinates
methods.system, there the turtle always starts in the center of it with (0,0) as x and y
coordinates.
Instead of using forward (distance) to move, you can do so by specifying the coordinates of the point you
Practice 1
want to get to with the setpos(x,y) or goto(x,y) methods.
Draw the following shape using setpos( ) / goto( ) methods (if needed, use
penup( ) / pendown( ) methods). Each square in the grid is 10  10 pixels.

Practice 1
Draw the following shape using Optional Starting
setpos() / goto() methods (if point

needed, use penup( ) / pendown()


methods). Each square in the grid is 10
x 10 pixels.

Practice 1 - Solution 39

If we use the suggested starting point, the solution would be:


Practice 1

Solution
If we use the suggested starting point, the solution would be:

from turtle import *


setpos (0,40)
setpos (40,40)
setpos (40,-40)
setpos (-40,-40)
setpos (-40,20)

Remember:

1. You need to calculate the coordinates of the key points of the drawing.

2. When moving from one point to another, you leave a trace (the turtle is in pendown() status).
So remember to use penup() / pendown() if needed.

3. You can start from any point you want as long as you pay attention to your turtle position.
Practice 2
Draw the following shape using setpos() / got
is 10  10 pixels.

Practice 2
Draw the following shape using setpos() / goto()
methods. Each square in the grid is 10 x 10 pixels.

Practice 3
Draw the following shape using a “for” loop in o
40
square in the grid is 10  10 pixels.
Draw the following shape using a “for” loop in or
square in the grid is 10  10 pixels.

Practice 3
Draw the following shape using a “for” loop in order
to complete your drawing. Each square in the grid is
10 x 10 pixels.

Practice 3 – Solution
Practice 3
One solution to this problem is to start at the cen
50 pixels then move backward for 100 pixels then
Solution
One solution to this problem is to start at the center of the screen, move forward for 50 pixels then move
backward for 100 pixels then return to the point where the turtle started. These commands draw a horizontal
line. It will be easy to complete the drawing by repeating it 6 times i.e. using a “for” loop. Remember to turn
left or right 30o each time you complete a loop.

41
Practice 4
Draw the following shape. Each square in the gr

Practice 4
Draw the following shape. Each square in the grid is
10 x 10 pixels.

Practice 5
Practice 5
What does the following code do?
What does the following code do?

from turtle import *


for i in range(4):
for j in range (4):
forward (60)
left (90)
left (90)

42
5
Using colors with turtle
graphics
Colors methods
Colors to discover
methods to discover

Colors methods to discover


This command should be used before drawing the shape you
begin_fill()
want to fill .
This
This command
command should
should be
be used
used after drawing the shape you
end_fill()
begin_fill() before drawing the shape you
want to fill
want to fill .
pensize(integer) Set the
This pen sizeshould
command to the be
given number
used .
after drawing the shape you
end_fill()
want to fill
pencolor(color) Set the pen color to the given color .
pensize(integer) Set the pen size to the given number
fillcolor(color) Set the fill color to the given color .
pencolor(color) Set the pen color to the given color
color(color) Set both the fill and pen colors to given color .
fillcolor(color) Set the fill color to the given color
Set the pen and fill color at the same time. Color1 should be
color(color1,
color(color) color2) Set
the both
namethe fill and
of the penpen colors
color, and to the fill color .
giveniscolor
color2

Set the pen and fill color at the same time. Color1 should be
color(color1, color2)
the name of the pen color, and color2 is the fill color
Colors in your drawing Canvas
Colors in your drawing Canvas
Colors as extremely easy to use when drawing with the turtle. There are 2 methods
Colors infor
categories your drawing
controlling Canvas
colors: pen colors and fill colors.
Colors are extremely easy to use when drawing with the turtle. There are 2 attributes for controlling colors:
penColors as extremely
colors and fill colors. easy to use when drawing with the turtle. PenThere
color are 2 methods

categories for controlling colors: pen colors and fill colors.


Pen color

Fill color

Fill color

To resume quickly the use of these methods.


To choose pen color:
To choose pen color:
1. Start by setting
To resume the penthe
quickly color
useyou
ofwant
theseto methods.
use. Type pencolor (color).
2. Draw 1.your
Start by setting
shape(s). Each the
timepen
you color
want toyou
usewant to use
a different pentocolor,
drawusewith
the the
pencolor (color) method.
To choose pen color:
pencolor(color) method.
1.
2. Start
Drawby setting
your the pen
shape(s). Eachcolor
timeyouyouwant
wanttotouse
usetoadraw withpen
different the color, use the
To fill shapes:
pencolor(color) method.
1. Start2.by Draw
settingyour
the fill color. Type
shape(s). fillcolor(color);
Each time you want to use a different pen color, use the
2. Type begin_fill();
pencolor(color) method.
3. Draw
To filla shape
shapes:
– The shape should be closed (All the sides are touching).
4. After1.finishing your
Start by shape,the
setting typefillend_fill();
color with the fillcolor(color) method.
To fill shapes:
2. Insert the begin_fill() method.
1.
3. Start
Drawby setting
your the fill
shape(s) – ofcolor witha the
course fillcolor(color)
closed line shapes. method.
2. Insert the begin_fill() method.
44
3. Draw your shape(s) – of course a closed line shapes.
4. Finish with the end_fill() method to apply the fill color.

Warning:
You can set both pen and fill colors at the same time. In order to achieve this
You
task, you cancanuse
set the
bothcolor()
pen and fill method.
colors at the
Twosame time.toInuse
ways order to achieve
this method: this task, you can use
color(color)the orcolor() method. Two ways toIn
color(color1,color2). usethe
thisfirst
method:
use of the method, the color
color(color)
argument represents both pen or color(color1,color2).
and fill color. In the second In thecolor1
use, first use of the method,
represent the the color
argument
pen color and color2 therepresents
fill color.both pen and fill color. In the second use, color1 represent the pen color
and color2 the fill color.
Quick colors reference
When using colors, you can either use the color name like “red”, “green”, “blue”,
Quick
“yellow” andcolors
so on, reference
or use a percentage of the RGB color system to “make” your color.
For example, the red color in the RGB system is (1, 0, 0) where the first number
When using colors, you can either use the color name like “red”, “green”, “blue”, “yellow” and so on, or
represents the red component
use a percentage in your
of the RGB color color,
system the second
to “make” number
your color. For represents
example, thethered color in the RGB
green component, and the third number is the blue component. All the three
system is (1, 0, 0) where the first number represents the red component in your color, the second number
represents
numbers should green
the be component,
between and1.the
0 and Tothird
usenumber blue component.
is thecolor
the yellow using the RGB
All thesystem,
three numbers should
be between
we would write0(1, To use the yellow color using the RGB system, we would write (1, 1, 0).
and1,1.0).

Let us put all these methods into practice.


Let us put all these methods in practice.

PracticePractice
1 1
DrawDraw
the following shapes
the following shapesusing
usingturtle Pythoncommands.
turtle Python commands. Set Set the color
the pen pen color to “blue”
to “blue” and the fill color to
and the fill color to “lightgreen”. Each triangle side is 60, and the gap between the
“lightgreen”. Each triangle side is 60, and the gap between the first triangle and the secondfirst
one is 10.
triangle and the second one is 10.

Gap: 10 pixels

Practice 1 - Solution
Practice 1

Solution

45
Note: you can control the pen width (the line thickness) by using the pensize(num) method, passing to the
method a positive number as the pen thickness.
The previous example would become, if we change the pen size for each figure, as following:
from turtle import * Note that you can control the pen width (the
color («blue», «lightgreen») method, passing to the method a positive num
pensize Note
(3) that you can control the pen width (the line thickness) by using the pensize(num)
The previous example would become if we cha
begin_fill()
method, passing to the method a positivefollowing:
number as the pen thickness.
for i inTherange (3):
previous example would become if we change the pen size for each figure as
forward (60)
following:
left (120)
penup ()
forward (70)
pendown ()
left (60)
pensize (2)
pencolor (»red»)
for i in range (3):
forward (6)
left (120)
end_fill()
The result of executing the code will be:
The result of executing the code will be:
The result of executing the code will be:

Note the change of the pen thickness and colo


and pencolor() methods.
Note the change of the
Note pen
the thickness
change of and
the color for each figure
pen thickness andusing
colorthe each figureand
forpensize() using the pensize()
pencolor()
methods. and pencolor() methods.
Practice 2
Using the “for” loop, draw the following shape
Practice 2
Using the “for” loop, draw the following shape: • E
Practice 2 • T
• Each square in the grid is 20 × 20 pixels.
• P
Using the “for” loop, draw the following shape: • The gap between shapes is 20 pixels. and pi
• Each square in the grid is 20 × 20 pixels. • Pen and fill colors are: red, green, blue
• The gap between shapes is 20 pixels. and pink.
• Pen and fill colors are: red, green, blue and pink.

46
Practice 2

Solution
Remember, there is no exclusive solution for a given problem!
from turtle import *
# pencolor (”red”)
# fillcolor (”green”)
for k in range (5):
color (”red”, “green”)
pensize (3)
begin_fill()
for i in range (3):
forward (40)
left (120)
forward (40)
end_fill()
right (90)
color (“blue“, “pink“)
begin_fill()
for j in range (4):
forward (40)
right (90)
end_fill()

penup ()
left (90)
forward (20)
pendown ()

Warning:
1- As you noticed in the second and third lines of the solution, 2 methods were marked as
comments. You can always use these methods instead of the color() method to set your
pen and fill colors.
2- Pay attention to the indents after each “for” loop. You can control the start and end of
each loop with the indents. If any indentation was wrong, the code will display unwanted
shapes.

47
6
Optimizing your code –
Using functions
What is a function in Python?

In Python, a function is a group of related statements that perform a specific task. Functions help break our
What is a function in Python?
program into smaller and modular pieces. As our program grows larger and larger, functions make it more
organized andInmanageable.
Python, a function is a group
Furthermore, of related
it avoids statements
repetition thatcode
and makes perform a specific task.
reusable.
Functions help break our program into smaller and modular pieces. As our program
Syntax of Function
grows larger and larger, functions make it more organized and manageable.
def function_name(parameters):
Furthermore, it avoids repetition and makes code reusable.
statement(s)

Syntax of
A function definition Function
consists of the following components:
def function_name(parameters):
1. The def keyword,statement(s)
which marks the start of a function.
2. A function name, which uniquely identifies it.
A function definition consists of the following components:
3. Parameters (arguments)
1. The defthrough which
keyword, we marks
which pass values to a function.
the start They are optional.
of a function.
4. A colon (:) to 2. A function
mark name,
the end of which uniquely
the function header. identify it.
3. Parameters (arguments) through which we pass values to a function. They are
5. One or more valid python statements that make up the function body. Statements must have same
optional.
indentation level.
4. A colon (:) to mark the end of the function header.
5. One or more valid python statements that make up the function body.
6. An optional return statement to return a value from the function.
Statements must have same indentation level.
6. An optional return statement to return a value from the function.
First example of a function
First example of a function
Create a newCreate
Pythonafile, and insert the following code.
new Python file, and insert the following code.
from turtle import *
def draw_square ():
for i in range (4):
forward (50)
left (90)
draw_square()
Once you runOnce
it, you will
you runget
it,ayou
square
will of
get50
a pixels
squaresides.
of 50So whatsides.
pixels happened?
So what happened? Function name:
“draw_square”
Function body: all instructions
to be executed when the
function is called.

Function call. Don’t


forget the “()” or you will
have an error!

Once the function is defined, you can use it as much as you like by simply “calling” it. A “function call” is
when you write its name as an instruction, so the Python executes the instructions within its body.
You can call the function (in our example, drawing a square) whenever you need to draw a 50 pixels sides
square.

49
You can call the function (in our example drawing a square) whenever yo
draw a 50 pixels sides square.
Practice 1
Practice 1
Your turn now. Change the previous code in order to draw the following figure (each grid square is
Your turn now.
10 × 10 pixels) using the draw_square() Change the previous code in order to draw the following
function.
grid square is 10 × 10 pixels) using the draw_square() function.

Practice 1 - Solution
Practice 1 Using the draw_square() function, the solution could be as following:

Solution
Using the draw_square() function, the solution could be as following:
from turtle import *
def draw_square ():
for i in range (4):
forward (50)
left (90)
pensize (2)
fillcolor («pink»)
begin_fill()
for i in range (4):
draw_square()
left (90)
Of course, if you are still wondering about the advantage of using functio
end_fill ()
solution without the use of functions.

50
Of course, if you are still wondering about the advantage of using functions, check the solution without the
use of functions.

from turtle import *


pensize (2)
fillcolor («pink»)
begin_fill()
for i in range (4):
for j in range (4):
forward(50)
Instead of using complex nested loops, the solution is simpler when breaking your
left (90)
code to small, easy parts.
left (90)
end_fill ()
Now let’s take functions to another level.
Instead of using complex nested loops, the solution is simpler when breaking your code to small, easy parts.

Now let’s take functions


What iftoI need
another
tolevel.
draw a bigger square? Or smaller one! It’s not a good programming
What if I need topolicy
draw ato
bigger square?
change theOr smaller
code one!
of the It’s not aeach
function good time.
programming policy to change the
code of the function each time. or arguments of a function are the solution.
Parameters
Parameters or arguments of a function are the solution.
Create a new file, type, save and run the following code:
Create a new file, type, save and run the following code:
from turtle import *
def draw_square (side):
for i in range (4):
forward (side)
left (90)

draw_square(60)
draw_square(80)
draw_square(100)
draw_square(120)
You will
You will get 4 squares get 4 squares
of different sizes in of different
1 simple size in 1 simple function.
function.
Argument(s) of
the function

Call of the function, each time


with a different size!

51
Practice 2
Practice 2
Using functions, write a Python code to draw the following
Using functions, write a shape. Thetosmaller
Python code draw theequilateral triangle
following shape. has 60
The smaller

pixels side, the next one 80 pixels, then100, 120 and finally 140.
equilateral triangle has 60 pixels side, the next one 80 pixels, then100, 120 and finally
140.

The function:
As you already know, you can use the following Python code:
For j in range(nb_sides):
Practice 2 - Solution
forward(distance)
left(360/nb_sides)
Practice 2
Where:
Solution nb_sides is the number of the shape’s sides you want to draw.
distance is the length of each side.
Using the draw_square() function, thecorrespond
And 360/nb_sides solution could
to thebe as following:
external angle (turn angle)

from turtle import *


Based on all the above, our function will be written as following:
def draw_tri (side):
for i in range (3):
def polygon(sides, length):
Practice 3
forwardfor(side)
j in range(sides):
Define a function, which draws a regular
left (120) forward(length) polygon. You need to use a “for” loop in order to
left(360/sides)
achieve the function. The function need to take 2
draw_tri(80) arguments: the 1st one should be the number of
Of course, you can use assides,
variables’
the 2ndname whatever you want (with respect to
draw_tri(100) one the side length.
variables naming). Once the function defined, draw the following
draw_tri(120)
Set your (0,0) origin on the drawing
shapes and
using thestart drawing
defined your shapes. Remember to set
function.
draw_tri(140)
your fill colors before starting theunit
The grid shape,
is 20and don’t forget to start with begin_fill()
pixels.
and end your shape (or shapes with the same fill color) with end_fill().

Practice 3 – Solution
Practice 3 The solution should contain 2 main steps: the function definition, and then drawing
Practice 4
the colored shapes.
Using the polygon function
Using the from thefunction
polygon previous practice,
from draw the
the previous following
practice, figures.
draw the Pickfigures.
following dimensions at your
convenience. Pick dimensions at your convenience.
Shape 1: triangle based Shape 2: Pentagon based
Angle between shapes: 45 o
Angle between shapes: Guess it on your own
to be calculation

52
Practice 4

Challenge Practice 5 - Challenge


Using the polygon function that you already defined, draw the following figure. Note
Using the polygon function that you already defined, draw the following figure. Note that each shape is
that each shape is bigger than the previous one by 10%, for a total of 11 shapes,
bigger than the previous one by 10%, for a total
including ofone.
the first 11 shapes, including
The shape the first one. The shape is a hexagon.
is a hexagon.

Practice 5 - Solution

Practice 4

Solution
Using the draw_square() function, the solution could be as following:
from turtle import *
Remarks:
def polygon (side, length):
As you noticed in the solution, the variable “i" is used to increment the polygon size
for j in range (sides):
each time the loop is repeated. In fact, each time Python runs the “for” loop, the value
forward (length)
of the variable “i” changes. Since “range” value is 11, the first value of i is 0. In the
left (360/sides)
second loop, it becomes 1, then 2, 3, 4, and so on till it reaches 10, which makes 11
for i in range (11):
loops as total. This change of value at each repetition is called variable increment,
which can be used in several situations in programming.
polygon (6,50+50*i/10)
left (36)

Warning:
As you noticed in the solution, the variable “i» is used to increment the polygon size each
time the loop is repeated. In fact, each time Python runs the “for” loop, the value of the
variable “i” changes. Since “range” value is 11, the first value of i is 0. In the second loop,
it becomes 1, then 2, 3, 4, and so on till it reaches 10, which makes 11 loops in total. This
change of value at each repetition is called variable increment, which can be used in several
situations in programming.

53
Practice 5

Challenge
Practice 6 - Challenge
Using a “for” loop, draw athe
Using following
“for” shape starting
loop, draw with theshape
the following first side length equal
starting 40. first side length equal 4
with the

Starting point of the turtle

Practice 6 - Solution
Practice 5Be creative with your solution :)

Solution
Be creative with your solution :)
from turtle import *
for i in range (20):
forward(40+10*i)
left (90)

54
7
Advanced topics in turtle
graphics:
Interaction and decision-
making
User interaction

User interaction is very important in programming applications. Without interaction, your application would
be extremely restricted in its functionalities. For example, when accessing your email, by providing a user
name and password. Or even in your Windows application, when you change your desktop wallpaper. It’s
done by letting the application interact with the user!

Text/number input

There are 2 graphical methods that we can use to display a pop up dialog window and ask the user for input:

textinput(title, prompt)

Pop up a dialog window for input of a string (text). Parameter title is the title of the dialog window, prompt
is a text mostly describing what information to input. Return the string input. If the dialog is canceled,
return None *.

numinput (title, prompt, default=None, minval=None, maxval=None)

Pop up a dialog window for input of a number. Parameter title is the title of the dialog window, prompt
is a text mostly describing what numerical information to input. Default (optional): default value, minval
(optional): minimum value for input, maxval (optional): maximum value for input.

The number input must be between minval and maxval if these are given. If not, a hint is issued and the
dialog remains open for correction. Return the number input. If the dialog is canceled, return None *.

* Definitions provided by Python.org

Application 1
Create a new Python file and type the following code:

56
Save and run it.Save
You shouldrunhave on your displayhave
a pop upyour
window askingafor the number of sides, as result
Save and
and run it.it. You
You should
should have onon your display
display a pop
pop upup window
window asking
asking for
for the
the
of the Python instruction:
number
number of of sides,
sides, as
as result
result of
of the
the Python
Python instruction:
instruction:
num_sides=numinput("Drawing","Enter
num_sides=numinput("Drawing","Enter sides") sides")

Input
Input
Area
Area

You surely noticed


You that the execution of the program will stop the
until you enter will
a value followed by enter ona value
You surely
surely noticed
noticed that
that the
the execution
execution of of the program
program will stopstop until
until you
you enter
enter a value
the keyboard (or click on the OK button).
followed
followed by by enter
enter on
on the
the keyboard
keyboard (or(or click
click on
on the
the OK
OK button).
button).
The second pop up window will be displayed as result of the Python instruction:
The
The second
second poppop up
up window
window will
will be
be displayed
displayed as as result
result of
of the
the Python
Python instruction:
instruction:
length=numinput("Drawing","Enter
length=numinput("Drawing","Enter length of a side") length of a side")

Once
Once you validate
Once you
your validate
second
you entry,your
validate YOUsecond
your second entry,
WILL GET AN
entry, YOU WILL
WILL:)GET
ERROR
YOU GET AN
AN ERROR
ERROR :)
:)
TypeError:
TypeError: 'float' object cannot be interpreted
interpreted asas an
an integer
TypeError: ‘float‘ object 'float'
cannot be object cannot
interpreted beinteger
as an integer
The simplest way to explain what happened is that you need to set the type of the entered value: it should
The
Theorsimplest
simplest way
way to to explain what happened is that you
you need to set the type
type of
of the
be either a number text (string in explain
Python). what
If it’s ahappened
number, theistype
thatshouldneed
be onetoofset
thethe
following: the
entered
entered value:
value: itit should
should be either a number or text (string in Python). If it’s a
• integer value represented in Python as intbe either a number or text (string in Python). If it’s a
• decimal valuenumber,
represented
number, thein type
the Python
type should be
be one
as float
should one of of the
the following:
following:
integer
So, in order to have•• the value
“polygon”
integer value represented
function in
in Python
calculating
represented right, weas
Python int
asshould
int tell it that we are working with
integers (in our example). To do value
•• decimal
decimal so, yourepresented
value need to changein
represented inthe code toas
Python
Python asthe following:
float
float
So,
So, in
in order
order to
to have
have the
num_sides=int(numinput(“Drawing“,“Enterthe “polygon”
“polygon” function calculating
calculating right,
sides“))
function right, we
we should
should tell
tell itit that
that we
we
are
are working
working with
with integers
length=int(numinput(“Drawing“,“Enter integers (in
(in our
our example).
length To
example). To do
of a so,
do you
you need
side“))
so, need to
to change
change the
the code
code to
to
the
the following:
following:
The int() instructions will tell Python to parse the value you entered by keyboard to an integer number,
num_sides=int(numinput("Drawing","Enter
num_sides=int(numinput("Drawing","Enter sides")) sides"))
in order to passlength=int(numinput("Drawing","Enter
the numbers to the “polygon” function a give the correct answer. of a side"))
length
length=int(numinput("Drawing","Enter length of a side"))
Try running the above example with different values each time.
57
Try running the above example with different values each time.

Practice 1
Practice 1
Using the “polygon” function defined in application 1, write an application that will ask for the polygon
Using the “polygon” function defined in application 1, write an application that will ask
type to use (number of sides), each side length, and the number of repetitions. The whole process should be
for the polygon type to use (number of sides), each side length, and the number of
automated i.e. calculated by your code.
repetitions.
Examples The figures
of possible wholeresulting
processfrom
should
yourbe automated i.e. calculated by your code.
code:
Examples of possible figures resulting from your code:

Entry set: Entry set:


Number of sides: 7 Number of sides: 10
Length of sides: 60 Length of sides: 35
Number of repetitions: 9 Number of repetitions: 12

Practice 1 - Solution
Practice 1

Solution

58
Using the “random” library Using the “random” library
Random
Random numbers can be very useful, especially in games programming, addingnumbers can be
the unexpected very
work useful, esp
using
an application. unexpected work using an application.
First, we have to import the random mod
First, we have to import the random module with the command import random using the import instruction:
the import instruction:
from random import * from random import *
The random module has a few different f
The random module has a few different functions for generating a random number. We’ll use
We’ll use randint(a,b), short for rando
randint(a,b), short for random integer. The randint()function expects us to give it two arguments
us to give it two arguments (two values),
(two values), the lowest and highest numbers we want to choose randomly between. Python will respond
choose randomly between. Python will re
with a random number between a and b, inclusive (which means the random number can include a and b).
and b, inclusive (which means the random

Application 2 Application 2
Let’s put this function into practice. Create a new Python file and type in the
Let’s putfollowing code. Save
this function and run Create
in practice.
it. code. Save and run it.

You probably will have something similar

You probably will have something similar to the following figure:

59
In fact, each time you will run it, you will have a different outcome: the mag
In fact, each time you will runrandint() function.
it, you will have a different outcome: the magic of the randint() function.
The solution code explained:
The solution code explained:
Impor
“random
order
“randint(

Defin
The “for” loop, in fu
order to repeat
instructions Generat
side
Generate a random betwee
side length between p
40 and 60 pixels Genera
coordin
a start p
penup() / pendown() shap
in order to move to
Move to the n
the new drawing
drawing posit
position without
drawing a line Dr
po

Practice 2 Practice 2
Using
Using the randint() function, thearandint()
write function,
Python application whichwrite a Python
will draw application
150 squares which
of random will draw
sizes
(between 10 and 35) in random
of positions.
random Apply a random fill
sizes (between 10color
andto35)
eachin square.
random Remember youApply
positions. can use
a random
the RGB representation of colors
eachwith each color
square. value between
Remember you can0 and
use1. the RGB representation of colors with
value between 0 and 1.

Practice 2
Practice 2 - Solution
Solution

60
Remember when executing your solution, you can speed up your turtle by setting its speed.

To set the fill color for each square, the following code was used:
fillcolor(randint(0,255)/255,randint(0,255)/255,randint(0,255)/255)

Each randint(0,255) will produce a random number between 0 and 255 (like the regular representation
of colors in RGB system). Dividing it by 255 will ensure that the final value will between 0 and 1 as a
decimal value for the color.

Warning:
Instead of using the randint(0,255)function, it is possible to use the random()
function. It returns a random float number between 0 and 1. So the fill color instruction will
be written as follows:
fillcolor(random(),random(),random())
We shall see more use of random function in the upcoming chapters.

61
Making decisions

Suppose that we need to draw a shape filled with one of 2 colors available. The statement that makes all this
possible is the “if” statement. Based on an answer, it decides whether to perform a set of actions or skip
over them. For example, if the temperature in a building is fine, the heating and cooling system doesn’t run,
but if it’s too hot or too cold, the system turns on. If it’s raining outside, you bring an umbrella; otherwise,
you don’t. In the following, you’ll learn in Python how to program the computer to make decisions based
on whether a condition is true or false.

The syntax of the “if” statement looks like this:

if condition:
indented statement(s)

The condition we’re testing in an “if” statement is usually a Boolean expression, or a true/false test. A
Boolean expression evaluates to either True or False. When you use a Boolean expression with an “if”
statement, you specify an action or set of actions that you want performed if the expression is true. If the
expression is true, the program will run the indented statement(s), but if it’s false, the program will skip
them and continue with the rest of the program at the next un-indented line.

Application 3
Create a new file in Python and type in the following code.

Once you run it, a pop up dialog asks you to type the letter ‘r’ in case you want to use the red color. Two
cases can result from your answer:
• You type the ‘r’ letter.
• You don’t type the ‘r’ letter.

In the first case, if you type the ‘r’ letter, a red triangle will be draw. If you type anything else, nothing will
happen.
62
What happened is Python has executed all indented instruction when you typed “r”. This is the result of
evaluating the condition resp==”r” to True, and therefore executing the instructions linked to the if –
true part.

Indented
instructions

Indented
instructions

When you type anything else, Python will skip all indented instructions, and nothing
will happen because we reached the end of the instructions.
When you type anything else, Python will skip all indented instructions, and nothing
When you type anything else, Python will skip all indented instructions, and nothing will happen because
will happen
To build because weofreached the end of the instructions.
we reached thethe
endcondition part
of the instructions. the “if” statement, we used comparison operators. It let
you test two values to see how they compare to each other. Is one of the values
To build the
bigger condition
To or
build thepart
smaller of the
the“if”
condition
than partstatement,
other? of Are westatement,
the they
“if” used comparison
equal? operators.
wecomparison
Each used It you
lets you
comparison testusing
two values
operators.
make aIt let
to see how they
you compare
test
comparison to each
two values
operator aother.
is to seeIshow
one of
condition the compare
they
that values
will bigger
to or
evaluate tosmaller
each than
other.
True Isthe
one
or False.other? Arevalues
of the they equal?
Each comparison you
bigger or make using
smaller thanathe
comparison operator
other? Are theyisequal?
a condition
Eachthat will evaluate
comparison to True
you False.a
makeorusing
comparison operator is a Python
condition
arethat will evaluate True or False.symbols):
tomathematical
The The comparison
comparison operators
operators in Pythoninare (compared (compared
to to the
the mathematical symbols):

Thesymbol
Math comparison operators
Python operatorin Python are (compared toExample
Meaning the mathematical
Resultsymbols):
< < Less than 5<6 True
Math
> symbol Python
> operator Meaning
Greater than 5 > 6Example FalseResult
≤ < <= < LessLess
thanthan
or equal 5 <= 56 < 6 TrueTrue
≥ > >= > Greater
Greater thanthan
or equal 5 >= 56 > 6 FalseFalse
= ≤ == <= Less than or equal
Equal 5 == 56 <= 6 FalseTrue
≠ ≥ != >= Greater than or equal5 != 65 >= 6
Not equal TrueFalse
= == Equal 5 == 6 False
As we have≠seen in the application
!= Not nothing
above, equal happens when5 != another
6 Truethan
letter
As we have seen in the application above, nothing happens when another letter than ‘r’ is selected. Let’s
‘r’ is selected. Let’s expand the use of the “if” statement with the “else” statement.
expand the use of the “if” statement with the “else” statement.
As we have seen in the application above, nothing happens when another letter than
In our, case, we need
‘r’ iscase,
In our, wetoneed
selected. draw aexpand
Let’sto triangle without
draw athe useaof
triangle color
theif“if”
without another letter
astatement
color than
with“r”
if another is typed.
the “else”
letter Instatement.
than fact,
“r” iswe need
to execute
typed.other instructions
In fact, we need when the condition
to execute otheris evaluated to false.
instructions when the condition is evaluated
In our, case, we need to draw a triangle without a color if another letter than “r” is
to false.
The “else” statement can only be used after an “if” statement, not by itself, so we sometimes refer to the
The typed.
“else” In fact, we need
statement to execute
can only be usedother
after instructions when the
an “if” statement, not condition is we
by itself, so evaluated
two together as an if-else instruction. The syntax looks like this:
to false.refer to the two together as an if-else instruction. The syntax looks like
sometimes
if condition:
this:The “else” statement can only be used after an “if” statement, not by itself, so we
indented statement(s)
sometimes refer to the two together as an if-else instruction. The syntax looks like
if condition:
else:
other indented
indentedstatement(s)
this: statement(s)
else:if condition:
other indented
indented statement(s)
statement(s)
else:
63
other indented statement(s)
If the condition in the “if” statement is true, the indented statements under the “if” are executed, and the
else and all its statements are skipped. If the condition in the “if” statement is false, the program skips
directly to the else’s other indented statements and runs those.

Application 4
What was required in application 3 is to draw a red triangle if we type the “r” letter. Let’s extend it and draw
a blue square if anything else than “r” is typed.
Look at the changes in the code, using the if-else statements:

As you noticed, the use of the if-else statement is extremely easy. You will get it by practicing.

Practice 3
Write in Python an application that draws a yellow, or green or orange random sided shape (3 to 8), based
on the response to a question at the beginning.

64
Practice 3
Solution
Using the “if” instruction, the solution would be as follow:

Extending the “if-else” use

The problem with the above solution is if the user types letters other than “y”, “g” or “o”, the application
won’t draw anything. If we use the “if-elif-else” instructions, where “elif” is the instruction in Python for
“else if”. The syntax looks like this:
if condition:
indented statement(s)
elif condition:
indented statement(s)
elif condition:
indented statement(s)
.
.
.
else:
other indented statement(s)

65
If we use the “if-elif-else” combination, the new code will be:

Note the use of the print() instruction. This function will allow you to output to the screen – in our case
the Python IDLE shell – the message between the double-quotes. In case you don’t type one the available
letters, the application will print on-screen the message “No choice made”!

Writing complex conditions with and / or / not

There are times when a single conditional statement isn’t enough. In practice 3, if a user enters “Y” instead
of “y”, the program checks to see if the answer is “y”. Of course, in this case, it won’t give the correct
answer. So we need a compound if statement in order to avoid this kind of problem.
Compound if statements are like compound sentences: “I’m going to the store, and I’m going to buy some
groceries.” Compound if statements are useful when we want to do a bit more than just test whether one
condition is true. We might want to test if a condition and another condition are both true (or both are false,
and so on).

66
The syntax is:

Logical Usage Result


operator
True only if both condition1 and
and If (condition1 and condition2):
condition2 are True
True if either of condition1 or
or If (condition1 or condition2):
condition2 are True
not If not(condition): True only if the condition is False

Practice 4
Practice
Write 4
a Python application with the following specifications:
• Pick a random number between 50 and 90.
Write a Python application with the following specifications:
• Print the number on the Python shell window.
• Pick a• random
If the number
number between 50 and50
is between 90.and 60, you will draw a pentagon with the

• Print the “number”


number on as the side
Pythonlength.
shell window.
• If the number is between 61 and 70, you will draw a square with the “number”
• If the number is between 50 and 60, you will draw a pentagon with the “number” as side length.
as side length.
• If the•number
If theisnumber
between is61between
and 70, you
71will
anddraw
80, ayou
square
willwith
draw thea“number”
hexagonaswith
sidethe
length.
“number”
as side
• If the number length.71 and 80, you will draw a hexagon with the “number” as side length.
is between
• If the number is between 81 and 90, you will draw a triangle with the “number”
• If the number is between 81 and 90, you will draw a triangle with the “number” as side length.
as side length.
• The location
• Theof the figures
location should
of the be random
figures between
should x = ±200
be random and y = ±250
between x = ±200 and y = ±250

Practice 4 - Solution
Practice 4

Solution

67
68
Introduction to
Networking
8
Networks basics

70
Introduction
What happens when you type in the address bar of your browser: “http://www.google.com”?

Your computer will try to communicate with another computer probably thousands of kilometers away
from you. To be able to establish this communication, the 2 computers must be connected. We say that the
2 computers are networked. There are a lot of networks, some networks are connected to other networks
which are themselves connected to other networks, which forms “networks of networks of networks”. This
multiple assembly of networks is called the Internet.

The idea of connecting computer networks to other computer networks dates back to the early 1970s with
the ARPAnet project which is, considered the ancestor of the Internet.

In order to identify themselves on a network, every computer has an address: its IP address. An IP address
is of the form “74.125.133.94” for example (this IP address corresponds to the google server “google.fr”).
IP addresses are of the form “a.b.c.d”, with a, b, c and d between 0 and 255.Everything will be explained
later on.

Computer Network Types


Generally, we distinguish networks on their geographical span. It ranges from small networks, as small as
the distance between a mobile phone and its Bluetooth headphone, to the largest network on earth which is
the internet itself.

Personal Area Network (PAN)


Personal Area Network (PAN) is the smallest network. Generally, it includes Bluetooth enabled devices or
infra-red enabled devices (obsolete technology). PAN has a connectivity range of a few meters (not more
than10).

Examples of devices including PAN:


• Wireless printers
• Bluetooth headphones / headsets
• Wireless keyboards and mice
• Portable Bluetooth or wireless speakers

Local Area Network (LAN)


A Local Area Network is a network restricted to a small area like an office, building or university campus.

Connecting devices in LANs is done


using cables in general or low-power radio
(wireless). In this case, we call it WLAN.
There is no limitation on the number of
connected devices to a LAN, but at least
there must be 2.

71
You can share different resources between all the users of a LAN: printers, scanners, file
servers, and of course internet.

RJ45 cables are usually used for connecting the devices to the switch.

A WLAN is in scope when a LAN is constructed


using a wireless device (Router/Access Point). You
will find at its center a wireless switch or router
called access point used for sending and receiving
data to the computers or any connected device to this
network. Always remember that WLANS are more
difficult to make secure since other people can also
try to connect to the wireless network. So, it is very
important to have a good, hard-to-guess password
for the WLAN access point.

The typical range of a wireless connection is about


50m.Two of the factors that impact the range the most are the number of walls/obstacles around the access
point and the wireless technology used.

Metropolitan Area Network (MAN)


The Metropolitan Area Network (MAN) generally
interconnects users with computer resources in a geographic
area or a region larger than that covered by even a large
local area network (LAN) but smaller than the area covered
by a wide area network (WAN) as we will see. It typically
expands throughout a city. For example, a MAN can help
an organization connect all of its offices in a city. It also
provides uplink for LANs to WANs or internet.

Wide Area Network (WAN)


A Wide Area Network is a network that extends over a
large area. A WAN is often created by joining several
LANs together, such as when a business that has offices in
different countries links the office LANs together. Because
WANs are often geographically spread over large areas
and links between computers are over long distances,
they often use optical fiber cables, satellite radio, and
microwave radio to achieve links.
The Internet is an example of a global WAN, and it is the
world’s largest WAN.

72
Practice 1
For each of the following networks, specify its type: LAN, WLAN, MAN, OR WAN.

Network Description Type


The internet

A school network

A network between two banks in the same city.

Upload a photo from your Smartphone to your desktop computer

Two students sharing files, one in Africa and the second in Europe

Playing games in a gaming lounge

You are using a wireless printer connected to your laptop

Watching a movie from an online streaming service to your PC

Practice 2
An establishment using 15 PCs is considering networking them together and adding a file server shared
by all users. Choose all statements that you agree with:

All users will be able to share a single printer.

The network type can be WLAN.

It’s not possible to add more PCs to the network in the future.

Videoconferences would be possible.

Users can easily share files.

Without the network, each computer should have a connected printer in


order to print out a document.

Computer can have internet access.

The network type can ONLY be LAN.

73
Things to remember about Networks

• Networks make sharing devices, such as printers, possible, which saves money.
• Files can easily be shared between users.
• Networks let us use emails.
• Networks might be expensive to implement.
• Managing a large network is complicated.
• Viruses can spread easily throughout networks.
• Computers connected to the same network prone to catch viruses from each other.

Network Topologies

A Network Topology is the arrangement with which computer systems or network devices are connected to
each other. There are three common network topologies: bus, ring and star topologies.

Bus Topology
In this type of network, a long, central cable, called
‘bus’ is used to connect all of the devices together,
computers, printers, servers... Each computer has a
short cable linking it to the ‘bus’. At each end of the
cable a terminator is fitted to stop signals reflecting
back down the bus i.e. it removes the signal from the
line.

It is extremely cheap to install, but it is very slow since


all devices share the same cable to send and receive data. If the central cable breaks, the whole network
will stop working.

Ring Topology
In this type of network, each computer is connected to a loop
of cable, the ‘ring’. If you take a bus network and connect the
ends of the bus cable together, you would have a ring network.
In this topology, each machine connects to exactly two other
machines, creating a circular network structure. When one
host tries to communicate or send a message to a host which
is not adjacent to it, the data travels through all intermediate
hosts. To connect one more host in the existing structure, the
administrator may need only one more extra cable.

If one cable breaks, the network should continue to work since


we would be left with a bus-like network.

74
Star Topology
Almost all LANs use this type of network where every computer is
connected to a central device, a hub or a switch: a hub is cheap but
slower, a switch is more expensive but for sure faster. The hub or
switch connects the devices using a point-to-point connection.

Another thing to remember about the difference between hubs and


switches is that a hub sends every packet of data to every device,
whereas a switch only sends a packet of data to the destination
device. This induces less traffic in the network. Many advantages
can be outlined using the star topology:

• Very reliable
• High performing networks regarding data
• Easy to install.

But remember that if the hub or switch fails, the network will stop.

P.S.
You may read about hybrid networks topology which is simply a network that combines two or more of
the above basic topologies. For example, a star network and a bus network which are connected in the same
LAN are considered, together, a Hybrid network.

Practice 3
Choose the best answer for each of the following questions:

What does a network allow computers to share?

Resources

Electricity

Keyboards

What does a network allow computers to share?

Files cannot be shared between users

Viruses can spread to other computers throughout a computer network

Resources such as printers can be shared

75
Which of the following networks is LEAST likely to be a WAN?

Same Bank ATM machines network

The Internet

A school network

Which type of network needs a terminator to be functional?

Ring

Bus

Star

In which topology we use a switch?

Bus

Star

Ring

Which is the smallest range network?

LAN

PAN

WLAN

76
9
Network hardware and cabling
Introduction
In order to function correctly, network components should be chosen carefully, depending on the network
final use and size. In the following, we will present and discuss the main hardware used in most common
networks: cables, network cards, hubs, switches, routers, proxy servers, bridges, and firewalls.

Network Interface Card (NIC)


Also known as a network card, NIC is a must for any computer or device to connect
to a network. Some network cards can allow wired connections by plugging in a
network cable, while others can let you use a wireless connection like almost all
modern laptops, tablets and Smartphones (even printers). These network cards are
generally built-in the device. In case of a wireless network card, you can notice an
antenna emerging out of the rear side of the computer.

Most modern motherboards come with a built-in network adapter. In case the user
wishes to install an additional network card, there are a lot
of external cards available nowadays in the market. They
are connected to the computer via USB.

Network Transfer Speed


First, let’s get the numbers clear. There is standard 100 Mbps (100 Mega bit per second) Ethernet, which
is what most people have at home. That is translated into 12.5 megabytes per second (MBps or MB/s).
This means that if you don’t have a gigabit router or switch and gigabit network card on your computer or
device, the maximum speed you’ll be able to transfer a file across your home network is 12.5 MBps, using,
of course, a wired network. 1 Gbps network cards are extremely common in new computers and laptops, so
the basic speed of an acceptable network is achieved with this network card speed. Note that even if your
computer has a gigabit Ethernet card, you won’t get those higher transfer speeds unless all the devices that
the data is being transmitted through support gigabit.

Of course, if you have a gigabit ethernet card on your computer, your router or switch is gigabit and the
receiving device also has a gigabit ethernet card, your max transfer speed jumps to a much better 1000
Mbps or 125 MBps (125 megabytes per second). Remember, you won’t get that theoretical speed in real life
network, but you should be getting anywhere from 70 to 115 MBps depending on the type of files you are
transferring and your network setup, that is around 80% to 90% of the theoretical speed of your network.

The latest the latest devices are upgradeable with 10GBe network cards. You’ll, of course, need a switch
that can also handle 10GBe. The transfer speed is 10 times faster than what most people use right now.

If you’re working with a ton of video files that need to be transferred over the network, upgrading your
hardware will greatly improve your workflow.

78
Network Cables
In order to connect together different devices that make up a network, you need cables. Cables are still
used in most networks, rather than using only wireless, because they can carry
much more data per second so we have a faster network that’s less prone to
security breaches.
Many types of cables exist, each can achieve a given transmission speed.

Twisted Pairs cables


The ethernet compatible cable with an RJ-45 connection is the most common type of network cable in use
today. This type of cables – twisted pair cable – is made of two
insulated copper wires twisted together to make a cable. In fact,
the whole cable is made of 4 twisted pairs of wires, for a total of 8
wires. The aim of the twist between wires is to reduce noise (low
signal distortion).

You can find two types of twisted pair cables:


STP (Shielded Twisted Pair) cables and UTP (Unshielded Twisted Pair) cables. The STP cables come with
an extra metal foil surrounding the cables. This makes it more “noise resistant”.

Common cables categories are:


• Cat-5 (data transmission up to 100 Mbps)
• Cat-5e (data transmission up to 1 Gbps)
• Cat-6 (up to 10 Gbps for small distances) RJ 45 connector
• Cat-6e (up to 10 Gbps with a higher bandwidth – around 500 MHz)
• Cat 7 (up to 10 Gbps with a higher bandwidth – around 600 MHz)

Coaxial cables
Coaxial cable has two wires of copper. The core wire lies in the center and it is made of solid
conductor. The core is enclosed in an insulating covering. The second
wire is wrapped around over the covering and that too in turn covered
by an insulating layer. All these layers are covered by plastic
final cover.
Because of its structure, the coax cable is capable of carrying
higher frequency signals than those of twisted pair
cable. It has a good shield against noise. Coaxial cables
provide high bandwidth rates and transmission up to
450 Mbps.

79
To be compatible with this kind of cabling, network cards must have a BNC connector. Cables are connected
using BNC connector and BNC-T. BNC terminator is used to terminate the wire at the far ends (review the
bus topology).

Fiber Optics

Fiber Optic cables use light signals to transmit data. The core of a fiber optic
cable is made of high-quality glass or plastic. From the transmitting side, light is
emitted. It travels through the cable and at the other end, a light detector detects
light stream and converts it to electric data, thus bits

Fiber Optic provides the highest speed among cables. Considering that the data
in a Fiber Optic cable travels a little slower than the speed of light (31% slower), it produces blazing-fast
delivery times.

The fiber optic cable comes in two modes: single mode fiber and multimode
fiber. The single mode fiber can carry a single ray of light whereas multimode is
capable of carrying multiple beams of light. The first one is used in long-distance
telecommunications networks for its higher bandwidth capacity, and the latter is used
in LAN and WAN due its lower cost.

In order to connect and access fiber optics, a special type of connectors is used. They can be Subscriber
Channel (SC), Straight Tip (ST), MT-RJ, FC…
Comparing to the average internet download speed, the fiber optic comes first:

• Fiber optics: Up to 10 Gbps (a data transfer rate up to 10 billion bits per second)
• Cable connections: 25 – 300 Mbps (a data transfer rate up to 300 million bits per second).
• Digital Subscriber Lines (DSL): 0.5 – 75 Mbps.
• Satellite: 5 – 25 Mbps.

For high-performance fiber optic cables, a signal repeater should be placed at each ~ 80 – 100 km in order
to regenerate the original signal.

Hub and Switches


A hub is a device that connects a number of computers together to make a LAN. The typical use of a hub
is at the center of a star network topology. The hub has cables plugged into it from each computer or device.
Nowadays, hubs are pretty much obsolete, having been outdated by cheap switches. A hub is a ‘dumb’
device: if it receives a message, it sends it to every computer connected to the network. This means:

80
• Hub-based networks are not very secure, because you can easily “listen” to all data travelling on the
network.
• Hubs can generate more traffic than other devices!

A switch, like a hub, is a device that connects a number of computers


together to make a LAN. It is also typically used at the center of a star
network topology. The switch has cables plugged into it from each
computer or device.

When the switch receives a message, it checks who it is addressed to,


and only sends it to that specific computer. Because of this: D-Link switch
• Networks that use switches are more secure than those that use hubs
• It generates less traffic on the network.
• But networks using switches tend to be a little more expensive than networks with hubs (A switch
is more expensive than a hub – but with more interesting features).

Routers
A router is a network device that connects together two or more networks. A common use of a router is to
join a home or business network (LAN) to the Internet (WAN).
The router will typically have the Internet cable plugged into it, as well as a cable, or cables to computers
on the LAN.
Alternatively, the LAN connection might be wireless (Wi-Fi), making the device a wireless router. A
wireless router is actually a router and wireless switch combined.
Current routers combine a DSL modem (which retrieves the internet analog signal from the telephone line
and translates it into digital signal), a switch and a router:

In this case, as the above figure shows, one end will connect to your ISP (phone socket) and the rest of the
ports will act as regular switch ports (combo modem/router device). This kind of devices is also ready to
provide WLAN connections.

Proxy Server
A proxy server is a computer set up to share a resource, usually an Internet connection. When accessing the
Internet, a computer can request a web page via the proxy server. The proxy server will get the page using
its own Internet connection, and pass it back to the computer that asked for it. The role of proxy servers

81
is far more than fetching a web page, they are often used
to manage internet access, web contents filtering, block or
control incoming traffic (like hackers trying to gain access to
the network) etc.

Bridges
A bridge is a network device that typically links together two different parts of a LAN.
Whereas a router is usually used to link a LAN to a WAN (such as the Internet), a bridge links independent
parts of a LAN so that they act as a single LAN.

Firewalls
A firewall can be either a physical device, or a software. It is placed between your computer and the rest of
the network in order to protect from security attacks. In personal computers, we can find firewall software
built in, directly integrated in the operating system like in Windows, Linux or even Mac OS.
If you wish to protect a whole LAN from unauthorized access, you should place your firewall device
between the LAN and the Internet connection. Through firewalls, normal data (like e-mails or web pages)
is allowed, but all other data is blocked.

82
Robotics Made Easy
with Gravity Intermediate Kit for
Arduino

By Ibrahim FATTAL
10
The Arduino
microcontroller
The Arduino Controller
Arduino is an open-source electronics platform based on easy-to-use
hardware and software. Arduino boards are able to read inputs like light
on a sensor, a finger on a button, or a Twitter message - and turn it
into an output, for example, activating a motor, turning on an LED,
publishing something online. You can tell your board what to do by
sending a set of instructions to the microcontroller on the board.
The Arduino model we use in all activities is DFRduino UNO from DF
Robot, which is a clone of the Arduino UNO.

How does a device think?


Any device that includes a microcontroller can be considered a simple automatic control device. There are
three essential constituent parts for a simple automatic control device:
• An input unit for collecting signals
• An output unit for sending out signals
• A control unit for processing the signals received (such as a
microcontroller).
Let’s draw an analogy between an automatic control device and
a person. In a person, signals are sensed through sight, hearing,
taste, touch and smell, and then processed by the brain, which
then outputs responses to each. In this case, the output signal
would be the actions of that person.
A microcontroller can output responses as well. Output responses
include sound, light and movement (DC Motors, LEDs, servos etc.)
Here is another way to explain it: imagine someone says “hello” to you, and you immediately reply with
“hello” in return. In this case, your ear is the input unit; your brain is the control unit and your mouth is the
output unit.
The same example in robotics would be as follows:
In addition to a microcontroller, we simply need an acoustic sensor and a buzzer. The acoustic sensor
“hears” a sound; the microcontroller receives a signal and then outputs a signal to the buzzer for it to buzz.
In this case, the acoustic sensor is the input unit; the microcontroller is the control unit and the buzzer is
the output unit.

Input Units - Sensors


A sensor (also known as a transducer) is a physical unit whose purpose is to sense or detect the characteristics
of its environment such as light, temperature or moisture levels and then transmit this data to another device.

85
Sensor Pins
The three categories of sensor pins are as follows:
• Digital Pin
• Analog Pin
• Protocol Pin (Digital)
A protocol pin is also a kind of digital pin. I2C, Serial and SPI are frequently used digital pins.

Control Unit – DFRduino Uno


The microcontroller is the control unit. Think of it as the brain of your device.

Output Units – Actuators


There are many different types of actuators. An actuator is a type of device that is responsible for moving
or controlling a system or mechanism or controlling an environment. It may convert electrical energy into
motion, sound or light. A buzzer or speaker are actuators that output sound.

The Relationship between Software and Hardware


The input unit, control unit and output unit mentioned above are all hardware. In the context of analogy
with a human body, hardware is the body, including arms and legs, of our device. However, the brain is
much more important as it produces ideas and controls actions that our body takes. Consider here the code
(software) as the mind of a person. Both body and mind are essential to a person.

86
11
First Code with Arduino
The Arduino IDE
It is time now to start using the open-source Arduino Software (IDE – Integrated Development Environment),
which will let you write complex code and upload it to the Arduino board. This software can be used with
almost all Arduino board and modules. It is an open source and can be downloaded for free from Arduino.
cc website.
Once Arduino IDE is installed, the interface is very easy to use:

Connect your Arduino to the computer USB port and


check
from the
Tools
menu that you have the right board selected (Arduino/
Genuino Uno) and that Windows is also detecting it
(in our example COM5). If the COM port number is
different, don’t worry, it may differ from one computer to another.
Sometimes, your computer may not detect directly the Arduino board, especially if it’s an Arduino clone
board (not manufactured by Arduino). In that case, unplug your board, and plug it again, it should be
detected…!

Your first Arduino Sketch


Once the circuit has been created on the breadboard, you’ll need to upload the program (known as a sketch)
to the Arduino. The sketch is a set of instructions that tells the board what functions it needs to perform.
Remember, an Arduino board can only hold and perform one sketch at a time, and in each sketch, it will
execute the commands serially.
88
Every Arduino sketch (program) has two main parts:
void setup()
Your Arduino always starts by executing all instructions written inside this part when it is powered ON. All
initial settings and variables initialization have to be done in this part. (The concept is very similar to the
<head></head> tag in HTML). It is executed once every time the board is powered ON.
void loop()
Contains the instructions that get repeated over and over until the board is turned OFF.
void setup() {
// put your setup code here, to run once:
instruction1;
instruction2;
…;
}

void loop() {
// put your main code here, to run repeatedly:
instruction1;
instruction2;
…;
}

Mainly, there are eight commands and instructions that you need to know:

Instructions Description / Use


digitalRead( ) Read a digital value (0 or 1) from an Arduino pin (for example if a
button is pushed or not)
digitalWrite( ) Write 0 or 1 (5V) on an Arduino pin (turn ON or OFF a LED).

analogWrite( ) Write 0 to 255 value on an Arduino pin. An example of this instruction


is when we need to control a LED brightness.

analogRead( ) Read an analog value from an Arduino pin, typically from a sensor.
Return values are between 0 and 1023.

if( ) statements It allows you to make something happen or not, depending on whe-
ther a given condition is true or not.
Serial communication Start a serial monitor.

pinMode( ) Set an Arduino pin as INPUT (for sensors) or OUTPUT (LEDs, motors etc.).
delay( ) Pause the program for the amount of time (in milliseconds).

89
Remember:
• The Arduino C language is case sensitive. So, each time you code, you need to make
sure that you are writing the instruction as it is defined.
• The setup() part of the code is run once, on Arduino startup; the loop() part will be
repeated infinitely as long as the Arduino is powered on.

Let’s start by controlling a LED.


Parts needed for this practice:

DFRduino UNO I/O Expansion Shield

Digital Push Button Digital LED - Red

90
Practice 1

To start this practice, place the IO expansion shield on your DFRduino UNO, and then connect the digital
red LED module to digital pin 8 as shown in the following layout:

Be sure that your power (VCC), ground (GND) and signal connections are correct or you
risk damaging your components.

91
Once you have connected the components and checked your connections, connect the microcontroller to
your PC with the USB cable so you can upload the following Arduino sketch:
void setup() {
// put your setup code here, to run once:
pinMode(8, OUTPUT);
}

void loop() {
// put your main code here, to run repeatedly:
digitalWrite(8, HIGH);
delay(1000);
digitalWrite(8, LOW);
delay(1000);
}
Verify your code then upload it to the DFRuino. You will see your red LED blink ON / OFF each 1 second.

Hardware Analysis
In this practice, the LED is used as a digital output. Remember, when working with digital, you only use 2
values: LOW and HIGH. The LOW value could be associated to 0V, and the HIGH value to 5V.
Software Analysis
The “set digital pin … to LOW” instruction will turn the LED off. The “set digital pin … to HIGH”
instruction will turn the LED on. A wait time of 1 second separates the on and off sequence.
Remember that your code will keep running as long as your controller is powered.

Code review
pinMode(8, OUTPUT);
This command is used for setting the connected pin on the DFRduino to either OUTPUT (receiving signal)
or INPUT (reading a signal from a sensor as we will see later on). As we need to send a signal to the LED
connected, it must be set to OUTPUT.
digitalWrite(8, HIGH);
This command will send the signal HIGH (1) to the pin 8; the LED will turn ON.
delay(1000);
The code execution will stop for 1 second (1000 milli-seconds).
digitalWrite(8, LOW);
This command will send the signal LOW (0) to the pin 8; the LED will turn OFF.

Change your code in order to make the LED blink faster. You will need to set the delay to a smaller value,
for example 250 (0.25s).

92
Practice 2

In the previous practices, we used a LED as output; now, we shall combine it with an input device – a push
button - in order to control the state of the LED. Of course, we will still be working with digital signals.
In order to setup the practice, connect your LED on pin 13, and your push button on pin 7 as following:

Hardware Analysis
As mentioned previously, the LED is an output device and we are adding an input device (sensor) to our
circuit: the digital push button. The signal that we will get from the button will be either a 0 or 1 because
we are dealing with a digital sensor.
Software Analysis
Step 1 – Testing the sensor with the Serial monitor
It is a good practice to start by testing your sensor(s) with the serial monitor; it can display, in real-time, any
value your send from the DFRduino.

Create a new sketch in your Arduino software, and enter the following code:
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(7, INPUT);
}

93
void loop() {
// put your main code here, to run repeatedly:
int button = digitalRead(7);
Serial.println(button);
delay(100);
}

The serial monitor is an on-screen display for any information that we send from the microcontroller. We
can display information from input devices or sensors connected to the it using the Serial.println()
instruction.
In order to initiate the communication between the microcontroller and the computer, we need to use the
“Serial.begin(9600)” instruction in the setup block.
The Serial.println(button) instruction will print on the serial monitor whatever is between the parenthesis,
in our case the value of the variable i.e. the button action.
Click on the Serial monitor icon in order to open the serial display and observe the results:
As long as you don’t push the button, zero is displayed each 100 ms; If you push the button, you will see
the value 1 displayed; So, the push button has two states:

0 – not pushed
1 – pushed
Which are the values for any digital input device.
As the digitalRead() and the Serial.println() are in the void loop(), the information
collected by the sensor will be continuously sent to the Serial monitor with a delay of 100 ms.
Now it is time to turn ON the LED for 2 seconds whenever the button is pushed;
94
Using the same circuit, modify your code as follows:
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(7, INPUT);
pinMode(13, OUTPUT);
}

void loop() {
// put your main code here, to run repeatedly:
int button = digitalRead(7);
Serial.println(button);
if (button == 1) {
digitalWrite(13,HIGH);
delay(2000);
digitalWrite(13,LOW);
delay(2000);
}
delay(100);
}

Remember:
As in any programming language, use a variable to store the button state value!
Verify the code, and upload it; test it by pushing the button, you can see your LED ON for 2
seconds, then OFF. That’s the impact of the IF instruction.
Remember when you work with digital:
• HIGH puts electricity (+5V) on the selected pin.
• LOW cuts the electricity (0V) on the selected pin.

The IF Statement
The if statement is usually used with a comparison operator, such as == (equal to), != (not equal to), <
(less than), > (greater than), <= (smaller than or equal), or >= (greater than or equal). Using one of these
comparison operators allows the program to evaluate an expression, and then make a logical decision.
Usually we use it to test if a particular condition is met. In the code above, let’s examine the use of the if
statement:
if (button == 1) {
instruction 1;
95
instruction 2;
...
}
The code will react and execute the instructions within the if braces only if the button is pushed. If not,
nothing will happen.

Let’s extend our code by adding


The if() then block which checks its Boolean (True or False) condition: if the condition is true, the blocks
held inside it will run, and then the script inserted after it will continue. If the condition is false, the code
inside the block will be ignored and the script will move on. The condition is only checked once; if the
condition turns to false while the script inside the block is running, it will keep running until it has finished.

Practice 3

Change the code you wrote in practice 2 in order to turn the LED ON as long as you keep pushing the
button.

Solution
A first approach is to change the loop() section to the following:
void setup() {
// put your setup code here, to run once:
pinMode(7, INPUT);
pinMode(13, OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
int button = digitalRead(7);
if (button == 1) {
digitalWrite(13,HIGH);
}
delay(100);
}

96
Of course, you will find this solution incomplete since the LED will stay ON once the button is pushed; for
that reason, the full if instruction is very useful with its else part:
if (condition) {
instruction 1;
instruction 2;
...
} else {
instruction 12;
instruction 13;
...
}

The else part will be executed only if the condition is false. Let’s update our code and extend the if block;
the new void loop() code will be:
void loop() {
// put your main code here, to run repeatedly:
int button = digitalRead(7);
Serial.println(button);
if (button == 1) {
digitalWrite(13,HIGH);
} else {
digitalWrite(13,LOW);
}
delay(100);
}

And your LED should stay ON as long as you are pushing it.

Practice 4

Change the code you wrote in practice 3 in order to turn the LED ON when the button is pushed, and OFF
when the button is pushed again.

Solution
A possible solution for the problem is:
bool pushed = false;
void setup() {
// put your setup code here, to run once:
pinMode(7, INPUT);
97
pinMode(13, OUTPUT);
digitalWrite(13,LOW);
}
void loop() {
// put your main code here, to run repeatedly:
int button = digitalRead(7);
if (button == 1) {
if (pushed == false) {
digitalWrite(13,HIGH);
pushed = true;
} else {
digitalWrite(13,LOW);
pushed = false;
}
}
delay(250);
}

Remember:
It’s not the only solution! In our case, we used a variable of type “bool” (which can
take true or false values) in order to save the button and LED states. Notice that it was
declared at the beginning of the code in order to use it anywhere in the current Arduino
sketch.
We can now write the full syntax of the if instruction:
if (condition) {
// set A of instructions;
} else if {
// set B of instructions;
} else if {
...
} else {
// set N of instructions;
}

98

You might also like