Teacher's Guide GR 10
Teacher's Guide GR 10
Teacher's Guide GR 10
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.
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.
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
Python graphics 29
and decision-making
Introduction to Networking 70
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 + " =^.^=");
} }
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:
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:
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;
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.
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;
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.
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.
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.
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:
== Equal
18
You can always combine logical operators to create more complex conditions:
|| or (x == 5 || y < 0)
! not ! (x == 6)
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>
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>
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:
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>
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
Instructions to repeat
Instructions to repeat
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:
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
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
Practice 1 - Solution 39
Solution
If we use the suggested starting point, the solution would be:
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?
42
5
Using colors with turtle
graphics
Colors methods
Colors to discover
methods to discover
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
Fill color
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).
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:
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.
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.
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
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)
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
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
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 *.
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 *.
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
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:
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.
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.
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:
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”!
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:
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
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.
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.
72
Practice 1
For each of the following networks, specify its type: LAN, WLAN, MAN, OR WAN.
A school network
Two students sharing files, one in Africa and the second in Europe
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:
It’s not possible to add more PCs to the network in the future.
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.
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.
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.
• 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:
Resources
Electricity
Keyboards
75
Which of the following networks is LEAST likely to be a WAN?
The Internet
A school network
Ring
Bus
Star
Bus
Star
Ring
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.
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.
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.
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.
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!
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.
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.
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:
void loop() {
// put your main code here, to run repeatedly:
instruction1;
instruction2;
…;
}
Mainly, there are eight commands and instructions that you need to know:
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.
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.
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