0% found this document useful (0 votes)
246 views33 pages

Programming in Python Part II PDF

This document provides information about conditional programming using if-else statements. It explains how to use if-else, if-elif-else, and nested if statements in Python programs. Examples are given to demonstrate how to write programs that check conditions and provide different outputs depending on whether conditions are true or false. The document aims to teach students how to create programs with conditional logic and alternative paths using Python and JavaScript.

Uploaded by

Ryusui Nanami
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
246 views33 pages

Programming in Python Part II PDF

This document provides information about conditional programming using if-else statements. It explains how to use if-else, if-elif-else, and nested if statements in Python programs. Examples are given to demonstrate how to write programs that check conditions and provide different outputs depending on whether conditions are true or false. The document aims to teach students how to create programs with conditional logic and alternative paths using Python and JavaScript.

Uploaded by

Ryusui Nanami
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 33

What I Need to Know

This module covers the knowledge, skills and attitude in understanding conditional
computer programming. This includes (1) the use of the if-else statement in the programs
and (2) creating programs using conditional structure.

Upon completion of this module, the students should be able to:


LO1. Use the if-else statement in the program
LO2. Create alternative options in the program
LO3. Create programs using Nested If Conditional Structure
LO4. Apply Python and JavaScript language respectively on identified problems related
to data processing and automation.
To get the most from this Module, you need to do the following:

1. Begin by reading and understanding the Learning Outcome/s and Performance


Standards. These tell you what you should know and be able to do at the end of
this Module.
3. Do the required Learning Activities. They begin with one or more
Information Sheets (What is It). An Information Sheet contains important notes or
basic information that you need to know. After reading the Information Sheet,
test yourself on how much you learned by answering the Self-check (What I
Learned). Refer to the Answer Key for correction. Do not hesitate to go back to
the Information Sheet when you do not get all test items correctly. This will
ensure your mastery of basic information.
4. Demonstrate what you have learned by doing what the Activity / Operation
/Job Sheet (What’s More & What I Can Do) directs you to do.
5. You must be able to apply what you have learned in another activity or in real
life situation.

1
What is It

USING IF-ELSE STATEMENTS

If-Else Conditional Structure


The if-else conditional structure evaluates a condition and provides statements when the
answer is either true or false.

else
Condition
Statement/s

else
Statement/s

In Python, its syntax is:

if condition: The first half of the syntax is the same as the if statement.
statement/s The else with a colon (:) is added to the next line. The
else: statement/s for the else is placed afterward. Let us modify
statement/s the programs from Lesson 2.

Example 1: PIN
Let us create a program that asks the user to enter his or her PIN. The program displays a
message if the PIN is correct. Else, it displays another message if the PIN is incorrect.

Pseudocode:
1. Assign the PIN to a variable.
2. Display the instruction to the user to enter his or her PIN.
3. Accept the entered PIN.
4. Evaluate if the entered PIN is the same as the stored PIN. Display a message when the
PIN is correct.
5. Display another message when the PIN is incorrect.

2
Flowchart

3
Using If-Elif-Else Statements
If-Elif-Else Conditional Structure
The if-elif-else conditional structure evaluates multiple conditions one at a time. If the
current condition is true, it disregards the remaining conditions. However, if the current condition
is false, it checks the next condition and so on. Given this, it is necessary to arrange our
conditions in logical order. If all conditions are false, the program executes the statements found
in else.

4
In Python, it uses this syntax:

if condition:
statement/s
elif condition:
statement/s
else:
statement/s

The if-elif-else syntax also starts with the if. When adding another condition, we use
elif. The if block has only one (1) else as its last option. However the if block may also
end with an elif.

The colons (:) are always placed next to the conditions and else.

Example 1: Score Remarks

Let us create a program that asks the user to enter his or her score in a 10-point
quiz. The program displays the remarks “Score is out of range.”, “You got a perfect
score”, “You passed the quiz!”, or “Oops. Do better next time.”

In this example, comparison operators are to be used. Arranging our conditions


logically will avoid overlapping conditions.

Pseudocode:

1. Assign the passing score to a variable.


2. Display the instruction to the user to enter his or her score.
3. Accept the entered score and convert it into a float.
4. Evaluate if the entered score is greater than the perfect score.
a. Display “Score is out of range.” if the score is beyond the perfect score.
5. If false, evaluate if the entered score is equal to the perfect score.
a. Display “You got a perfect score!” if the score is equivalent to the perfect
score.
6. If false, evaluate if the entered score is greater than the passing score.
a. Display “You passed the quiz!” if the score passed.
7. Else, display “Oops. Do better next time.”

5
Flowchart

6
Program:
#Score Remark
#Display the remarks “Score is out of range.”, “You got a
perfect score!”,
#“You passed the quiz!”, and “Oops. Do betters next time.”

hps = 10
passingScore = 7.5
score = float(input("Please enter your score: "))
if score > hps:
print("Score is out of range.")
elif score == hps:
print("You got a perfect score!")
elif score >= passingScore:
print("You passed the quiz!")
else:
print("Oops. Do beter next time.")

 The first two (2) line codes have comments, stating the title and description of the
program.
 The next two (2) lines have the variables and their values. The hps variable has
10. This is for the highest possible score of the quiz. The passingScore variable
has 7.5.
 The assignment operator (=) is used. All values are float so they can
accommodate decimal values.
 The next line is for the user input. The score variable gets the value, which is the
score that the user enters. It is converted into a float.
 The succeeding lines are included in the if block. It follows the correct syntax,
where conditions are logically declared as well as the statements are specified.
 The comparison operators are used such as the double equal sign (==).
 Proper indentations are observed throughout the program.

Output:
 This is the output when the entered score is beyond the HPS:
Please enter your score: 12
Score is out of range.

7
 This is the output when the entered score is passing:
Please enter your score: 9
You passed the quiz!

Example 2: Positive, Zero (0), or Negative


Let us create a program that determines if a number is positive, zero(0), or
negative.
In this example, we will use our mathematical knowledge in identifying as to which
group a number is included. There are similarities with the previous example.
Program:

#Positive Zero Negative


#Identify if a number is positive, zero, or negative.

number = int(input(“Please enter a number: “))


if number > 0;
print (“The number”, number, “is a positive number.”)
elif number == 0:
print (“The number is zero.”)
elif number < 0:
print(“The number”, number, “is a negative number.”)

 The first two (2) line codes have comments, stating the title and description of the
program.
 The next line is for the user input. The number variable gets the value, which is
the number that the user enters. It is converted into an integer (int).
 The succeeding lines are included in the if block. The correct syntax and order of
the conditions are followed. The statements for the positive and negative numbers
include the entered number.
 The strings (e.g., “The number” and “is a positive number.”) and the variable
(number) are separated by a comma (,). Spaces are included in the string.

Output:

 This is the output when the entered number is a positive number:


Please enter a number: 18
The number 18 is a positive number.

 This is the output when the entered number is zero (0):


Please enter a number: 0
The number is zero.

8
 This is the output when the entered number is a negative number:
Please enter a number: -1
The number -1 is a negative number.

USING NESTED IF STATEMENTS

Nested If Conditional Structure


The nested if conditional structure is used in creating levels of nesting conditions. An if
block is placed in the statement of a condition. Any number of nesting in the statements is
possible. The nesting depends on the program that is created.

In Python, it uses this syntax:


if condition:
if condition:
statement/s
else:
statement/s
elif condition:
statement/s
else:
statement/s

9
The Indentations are used to show the levels of nesting.

Example 1: Positive, Negative, Odd, Even, or Zero (0)

Let us create a program that determines if a number is zero (0) or any of the
following:
Positive – Odd Negative – Odd
Positive – Even Negative – Even

Pseudocode

1. Display the instruction to the user to enter a number.


2. Accept the entered number and convert it into a float.
3. Compute the remainder.
4. Evaluate if the entered number is equal to zero (0).
a. Display a message.

5. If false, evaluate if the entered number is greater than zero (0).


a. Evaluate if the remainder is not equal to zero (0).
b. Display a message.
c. If false, display another message.

6. If false, evaluate if the entered number is less than zero (0).


a. Evaluate if the remainder is not equal to zero (0).
b. Display a message.
c. If false, display another message.

The entered number is needed throughout the program. It is used to compute the
remainder and all conditions. Placing it ahead the rest makes it reasonable.

The remainder is computed after getting the entered number. The computation of
the remainder is done once, which can be used for all conditions that need it. This makes
our program efficient.

10
Flowchart

11
The flowchart has similar order of steps to the pseudocode. The flowlines coming
from all statements are directed to the flowline toward the end. This signifies that the
program ends.

Program:

#Positive, Negative, Odd, Even, or Zero


#Identify if a number is positive – odd, positive – even,
#negative – odd, negative – even, or zero.

Number = float(input(“Please enter a number: “))


remainder = number % 2
if number == 0:
print(“The number is zero.”)
elif number > 0:
if remainder != 0:
print(“The number”, number, “is positive – odd.”)
else:
print(“The number”, number, “is positive – even.”)
elif number < 0:
if remainder != 0:
print(“The number”, number, “is negative – odd.”)
else:
print(“The number”, number, “is negative – even.”)

 The first three (3) line codes have comments, stating the title and description of
the program.
 The next line is for the user input. The number variable gets the value, which is
the number that the user enters, and it is converted into a float.
 The computation for the remainder is in the next line. The modulo (%) operator is
used. The computed value is assigned to the remainder variable.
 The succeeding lines are included in the if block. Let us notice the proper use of
the syntax and the logical order of the conditions.
 The first level of conditions is for identifying if the number is positive, zero (0), or
negative. The second level of conditions is for identifying if the number is even or
odd.
 The indentations help in organizing the codes.

Output:
 This is the output when the entered number is positive and odd:

12
Please enter a number: 5
The number 5.0 is positive – odd.

 This is the output when the entered number is negative and even:
Please enter a number: -8
The number -8.0 is negative – even.

Example 2: Election
Let us create a program that determines if a user is eligible to vote or not. A person
at the age of 18 or over is eligible to vote. Sophia and Phil are both running for president.

Program:

#Election
#Identify if a user is eligible to vote.
#Allow user to input his or her vote.

name = input (“Please input your name: ”)


age = int(input(“Please enter your age: “))
if age > 18:
print(“You are eligible to vote.”)
vote = input(“Please enter the code of your vote.”
“Sophia[S], Phil[P]: ”)
if vote == “S”:
print(“You voted for Sophia.”
“Thank you.”)
elif vote == “P”:
print(“You voted for Phil.”
“Thank you.”)
else:
print(“You abstained.”)
else:
print(“Sorry. Please come back when you are 18 years old or
over.”)

13
 The first three (3) line codes have comments, stating the title and description of
the program.
 The next lines are for the user to input his or her name and age. The entered
values are assigned to their respective variables. The entered age is converted to
an integer (int).
 The succeeding lines are included in the if block. The first level of conditions is for
the age. The next level of conditions is for casting a vote.

Output
 This is the output when the user is ineligible to vote:
Please input your name: Joy
Please enter your age: 16
Sorry. Please come back when you are 18 years old or over.

 This is the output when the user is eligible to vote and votes for Sophia:
Please input your name: Elsa
Please enter your age: 18
You are eligible to vote.
Please enter the code of your vote. Sophia[S], Phil[P]: S
You voted for Sophia. Thank you.

 This is the output when the user is eligible to vote and votes for Phil:
Please input your name: Nelvin
Please enter your age: 21
You are eligible to vote.
Please enter the code of your vote. Sophia[S], Phil[P]: P
You voted for Phil. Thank you.

 This is the output when the user abstains:


Please input your name: Kyle
Please enter your age: 25
You are eligible to vote.
Please enter the code of your vote. Sophia[S], Phil[P]: None
You abstained. Thank you.

14
TESTING MULTIPLE CONDITIONS
Multiple Conditions
In the previous unit, we are introduced to the logical operators and, or, and not.
These are used to compare operands or conditions.
Operator Description
and True if both conditions are true.
or Tre if at least one of the conditions is true.
not True if condition is false.

The syntax is:

(first condition) logical operator (second condition)

This is placed after if or elif. The parentheses may be omitted. We add another
logical operator when adding another condition.
Example 1: Positive, Negative, Odd, Even, or Zero (0)
We will use the same example from lesson 5. The algorithm is similar, however.
Notice the difference in the conditions.
Let us create a program that determines if a number is zero (0) or any of the
following:
Positive – Odd Negative – Odd
Positive – Even Negative – Even

Pseudocode:
1. Display the instruction to the user to enter a number.
2. Accept the entered number and convert it into a float.
3. Compute the remainder.
4. Evaluate if the entered number is equal to zero (0).
 Display a message.
5. If false, evaluate if the entered number is greater than zero (0) and the remainder
is not equal to zero (0).
 Display a message.
6. If false, evaluate if the entered number is greater than zero (0) and the remainder
is equal to zero (0).
7. If false, evaluate if the entered number is less than zero (0) and the remainder is
not equal to zero (0).
 Display a message.
8. If false, evaluate if the entered number is less than zero (0) and the remainder is
equal to zero (0).
 Display a message.

15
The first three (3) steps are similar to the pseudocode from the example in the
previous lesson. When it comes to evaluating the number, one (1) condition for zero
(0) and the rest of the conditions have two (2) descriptions: if positive or negative,
and odd or even.

(Flowchart-link to be provided)

In the flowchart, there are five (5) decision boxes, one (1) for identifying if the
number is zero (0). The remaining decision boxes are for identifying if the number is
positive or negative, and odd or even.

Program:

#Positive, Negative, Odd, Even, or Zero using Logical


Operators
“““Identify if a number is positive – odd, positive – even,
negative – odd, negative – even, or zero.”””

Number = float(input(“Please enter a number: ”))


Remainder = number % 2
if number == 0:
print(“The number is zero.”)
elif (number > 0) and (remainder != 0):
print(“The number”, number, “is positive – odd.”)
elif (number > 0) and (remainder == 0):
print(“The number”, number, “is positive – even.”)
elif (number < 0) and (remainder !=0):
print(“The number”, number, “is negative – odd.”)
else:
print(“The number”, number, “is negative – even.”)

 The first three line codes are comments. We use the hash (#) character for
single line comments.
 The first line that has the program titles is an example. The next (2) lines
are multiline comments.
We enclose the lines in three (3) double quotation marks or single
quotation marks.

16
 The next lines are included in the if block. The first condition displays if a
number is zero (0).
 The first half of the condition determines if it is positive or negative and the
other half determines if it is odd or even.
 They are connected with the and logical operator, which signifies that both
must be satisfied to proceed to their respective statements.
Output:

This is the output when the number 7 is entered:


Please enter a number: 7
The number 7.0 is positive – odd.

Example 2: Free Mango Pie


A fast-food restaurant is giving out their delicious mango pie based on the
conditions. In this program, we will use string values.

Using and operator


An order of a cheeseburger and juice gets a free mango pie. This means the
customer should order both cheeseburger and juice to get a mango pie.
Program:

#Free Mango Pie using Logical Operators


#Give a customer a mango pie based on the conditions.

print(
‘Menu \n’,
‘‘‘Burger
Cheeseburger [C]
Double cheeseburger [DC] \n’’’,
‘‘‘Drink
Juice [J]
Softdrink [S]’’’)
order1 = input(‘Please enter your burger: ‘)
order2 = input(‘Please enter your drink: ‘)

#Using AND operator


if order1 == ‘C’ and order2 == ‘J’:
print(‘You get a free mango pie. \n’
‘Thank you.’)
else: print(‘Sorry, no free mango pie.’)

17
 After the comments, the menu is displayed using print.
 In the first line, we enclosed the string Menu and \n with a single quote.
This is another option aside from double quotes.
 The \n is used to display the next string Burger… in the next line. There is a
comman to end it.
 The burger and drink menu are enclosed in their own three (3) single quotes.
Let us notice also that \n is added to the line of Double cheeseburger [DC].
Let us also experiment placing everything in three (3) single quotes and see the
output.
 The next lines are for the orders. Orders are placed in different variables.
 The rest of the codes are for the if block. The and operator is used in the
condition.
We may separate the conditions in parentheses: if (order1 == ‘C’) and (order2
== ‘J’)

Output:

Menu
Burger
Cheeseburger [C]
Double cheeseburger [DC]
Drink
Juice [J]
Softdrink [S]
Please enter your burger: C
Please enter your drink: S
Sorry, no free mango pie.

Using OR operator
An order of a cheeseburger or juice gets a free mango pie. This means the
customer gets a mango pie if he or she orders either a cheeseburger or a juice, or both
to get a mango pie.

18
Program:
#Using OR operator
if order1 == ‘C’ and order2 == ‘J’:
print(‘You get a free mango pie. \n’
‘Thank you.’)
else: print(‘Sorry, no free mango pie.’)

The condition is similar to the example program for and operator. We only replaced
the and operator with the or operator.

Output:
Menu
Burger
Cheeseburger [C]
Double cheeseburger [DC]
Drink
Juice [J]
Softdrink [S] Using NOT operator
Please enter your burger: C Only an order of a cheeseburger or a
Please enter your drink: S juice gets a free mango pie.
Sorry, no free mango pie. Program:

print(
‘Menu \n’,
‘‘‘Burger
Cheeseburger [C]
Double cheeseburger [DC]
Mushroom burger [MB] \n’’’,
‘‘‘Drink
Juice [J]
Softdrink [So]
Shake [Sh]’’’)
order1 = input(‘Please enter your burger: ‘)
order2 = input(‘Please enter your drink: ‘)

#Using NOT operator


if (order1 == ‘C’) or (not order2 == ‘J’):
print(‘Sorry, no free mango pie.’)
else: print(‘You get a free mango pie. \n’
‘Thank you.’)

19
The not operator is useful when we want only a few values to be true.
In this example, there are more items in our menu and we only want orders with a
cheeseburger or juice to get a free mango pie.
They are enclosed in parentheses to clearly see the functions of the operators,
although the program will still work even without them.

Output:

Menu
Burger
Cheeseburger [C]
Double cheeseburger [DC]
Mushroom burger [MB]
Drink
Juice [J]
Softdrink [So]
Shake [Sh]
Please enter your burger: C
Please enter your drink: Sh
Sorry, no free mango pie.

What is a Script?

A script is a set of computer instructions or commands that puts together or connects


existing components to accomplish a new related task. Scripts are typically written in
plain text form and are interpreted each time they are invoked.

• Objects - are items that exist in the browser. The browser window, the page itself,
the status bar, and the date and time stored in the browser are all objects.
• Methods are actions to be performed on or by an object. Methods also represent
functions that are designed for a specific purpose like doing math or parsing
strings.
• Properties• are an existing subsection of an object

JavaScript is a powerful scripting language that enables Web developers/designers to


build more functional and interactive websites. Most major Web browsers and those
emerging on the Net support JavaScript.

20
What can JavaScript do?
• JavaScript gives HTML designers an easy-to-learn programming tool.
• JavaScript allows a webmaster to create more appealing Web pages with
relatively simple codes.
• JavaScript makes Web pages more dynamic.
• JavaScript can respond to triggers or react to events.
• JavaScript can read and write HTML elements.

Syntax refers to a set of rules that determines how a specific language (in this case,
JavaScript) will be written (by the programmer/webmaster) and interpreted (by the
browser, in the case of JavaScript).

Introduction to the Basic Syntax

<html>
<head><title>My First JavaScript</title>
<script type="text/javascript">
<!--
document.write("This code outputs this text into the browser");
-->
</script>
</head>
</html>

Output:
This code outputs this text into the browser
Variables are a container that contains a value, which can change as required.

Declaring Variables
Variables are declared with a var statement. It is always good practice to pre-define your
variables using var. If you declare a variable inside a function, it can be accessed
anywhere within the function.

// declaring one variable


var firstname;
// declaring several variables
var firstname, lastname;

21
// declaring one variable and assigning a value
var firstname = “Jocelyn”;
// declaring several variables and assigning a value
var firstname = “Juan”, lastname = “Delacruz”;

<html>
<head><title>My JavaScript Variable</title>
<script style="text/javascript">
var firstname = "John";
</script>
</head>
<body>
<script style="text/javascript">
document.write("Hello there " + firstname)
</script>
</body>
</html>

Output:
Hello there John

MATH/ARITHMETIC OPERATOR

Operator Name Example Result


+ Addition myVariable = 3 + 4 myVariable = 7
- Subtraction myVariable = 15 - 7 myVariable = 8
* Division myVariable = 20 / 4 myVariable = 5
% Modulus myVariable = 24 % 10 myVariable = 4
- Negation myVariable = -10 myVariable = -10
++ Increment
-- Decrement

22
Logical/Boolean Operators
Operator Name Example Result

&& AND (both statements must be True) True && True True
|| OR (one must be True) True || False True
! NOT (Flips truth value) !True False

<script style=”text/javascript”>
var mylogic = 10<=8 || 10>=8
document.write(mylogic);
</script>

Result:
True

If Statement
The If Statement is one of the most popular and most important conditional
constructs in JavaScript and in many other programming languages.
This conditional statement construct evaluates a condition to True or False. It then
runs a specific code depending on the result of this evaluation. Try this example:

<script style="text/javascript">
var myPhone = "Motorola";
if (myPhone == "Motorola")
{
document.write("Hello moto!");
}
</script>

Result:
Hello moto!

23
If Else Statement

The If Else statement is similar to the If statement, except that we are giving an
alternative instruction in case the argument isn’t True. Let’s use the previous example for
this one and change the value of the variable to “Nokia”.

<script style="text/javascript">
var myPhone = "Nokia";
if (myPhone == "Motorola") {
document.write("Hello moto!");
}
else {
document.write("My phone is not a Motorola.");
}
</script>
Result:
My phone is not a Motorola.

If Else If Statement

But in the real world, you don’t always evaluate just one condition. Sometimes, you
would need to evaluate more than one or multiple conditions. This is possible in
JavaScript with the If Else If statement. The name refers to an If statement that depends
on another If statement.

<script style= “text/javascript”>


var myPhone = “Nokia”;
if (myPhone == “Motorola”) {
document.write(“Hello moto!”); }
else if (myPhone == “Nokia”) {
document.write(“It is a really cool phone. “); }
else {
document.write(“I’m using some other phone brand.”);
}
</script>
Result:
It is a really cool phone.

24
Switch Statement

<script style=”text/javascript”>
var mySubject = “Computer”;
switch (mySubject)
{
case “Algebra”:
document.write(“When will it ever end?”);
break
case “Calculus”:
document.write(“Give me a choice!”);
break
case “Computer”:
document.write(“My favorite!”);
break
default:
document.write(“I’m out a here!”);
}
</script>
Result:
My favorite!

While Loop

<script style=”text/javascript”>
var mypromise = 1;
while (mypromise <= 12)
{
document.write(mypromise+”. I will not sleep in algebra class again.<br>”);
mypromise += 1;
}
</script>
Result:
1. I will not sleep in algebra class again.
2. I will not sleep in algebra class again.
3. I will not sleep in algebra class again.
4. I will not sleep in algebra class again.

25
5. I will not sleep in algebra class again.
6. I will not sleep in algebra class again.
7. I will not sleep in algebra class again.
8. I will not sleep in algebra class again.
9. I will not sleep in algebra class again.
10. I will not sleep in algebra class again.
11. I will not sleep in algebra class again.
12. I will not sleep in algebra class again.

Functions and Events


Functions and Events
 Functions
 Predefined functions
 Events

Functions

A function (also known as method) is a self-contained piece of code that performs a


particular "function" when it is called.
Sometimes there will be text inside the parentheses. This is known as an argument. An
argument provides additional information needed by the function to process.

<script style=”text/javascript”>
function wakeUp()
{
alert(“Wake up Johnny, algebra class is over”);
}
</script>

Dialog Boxes
• Alert function “alert( )”– displays an alert box with a message defined by the string
message. We used this predefined function in the previous code to wake up
Johnny after the algebra class.

26
• Confirm function “confirm( )” – asks whether the user would continue or cancel
the action. Here is an example:

<body>
<script type="text/javascript">
if (confirm("Do you really want to wake up Johnny?")) {
document.write("OK, continuing to wake up Johnny!") }
else {
document.write("Aborting \"operation wake up Johnny\"") }
</script>
</body>

Prompt function “prompt( )” – asks for an input from the user and passes it to the
specified function. Here’s an example:

<body>
<script type="text/javascript">
var response = prompt("What is your name?")
if (response != null)
{
document.write("That's great! My friend's name is also "+response+".")
}
</script>
</body>

Sample Code
</head><title>My JavaScript Variable</title>
<script style=”text/javascript”>
function wakeUp() {
alert(“Wake up Johnny, algebra class is over”);
}
</script>
</head>
<body>
<a href=” JavaScript:void(0);” onMouseover=”wakeUp();”>Wake up Johnny when algebra
class is over.</a>
</body>

27
JavaScript Objects

What Is a JavaScript Object?


A JavaScript Object is the coding representation of objects that are used in your
page or in your browser.
Here are some key reasons:

• Increased code reuse – reuse of objects makes your coding work easier.
Especially in large scripts, you can create JavaScript objects that can be reused
across pages.
• Easier maintenance – because you can use objects across pages, you don’t have
to rewrite your objects for every page in your website.
• Increased extensibility – you can increase the functionality of your new codes by
simply taking existing objects and adding or revising a few codes or revising some
scripts.

JavaScript Object Creation and Use

• Objects have properties. Properties are the attributes of your JavaScript object.
Example:
document.bgColor = “red”;

• Objects also have methods. Methods are the things that your object can do.
Example:
document.write(“The method <b>\”write\”</b> writes this text to the page”);

• Event handlers specify when your object is supposed to do something or when


your objects are supposed to apply your preferred attributes.
Example:
<a href=”javascript:void(0); onClick=”document.bgColor = ‘red’;”>change color</a>

Object Creation
Generally, objects may be created using the following syntax:
var someVariable = new Object()

28
When JavaScript sees the New operator, it creates a new generic object. Using this
syntax, you can create objects like Array, Function, Date, Number, Boolean, and String.

JavaScript
Independent Objects

 Array Object
 Data Object
 Math Object
 Number Object
 String Object

Arrays
Arrays are a fundamental part of most programming languages and scripting
languages. They are basically an ordered stack of data with the same data type.
Using arrays, you can store multiple values under a single name.
var myFruit = new Array(3)
myFruit[0] = “mango”
myFruit[1]= “guava”
myFruit[2] = “apple”

var myFruit = new Array(3)


myFruit[0] = “mango”
myFruit[1]= “guava”
myFruit[2] = “apple”

Let’s try some of these methods. First, let’s try the join(delimiter). Write this on your
Notepad:
<script style="text/javascript">
<!--
var myFruit = new Array(“mango”,”guava”,”apple”);
var myString = myFruit.join(“/“);
document.write(myString);
//-->
</script>

29
Result:
mango/guava/apple

Data Object
JavaScript provides you with the ability to access the date and time of your user’s local
computer, which can be pretty cool in some cases. This is possible through the
JavaScript date object.

<script style="text/javascript">
<!--
var currentDate = new Date();
var day = currentDate.getDate();
var month = currentDate.getMonth();
var year = currentDate.getYear();
document.write(day + "/" + month + "/" + year)
//-->
</script>

Sample Codes:
<script style="text/javascript">
<!—
document.write(Math.PI);
//-->
</script>
<script style="text/javascript">
<!—
var myValue = MathPI;
document.write(myValueI);
//-->
</script>

30
Activity 1.1 & 1.2
Create If-Elif-Else Programs
Analyze the problems carefully. Create the programs. Follow the name format and file
location when saving your work.
1. Ages and Stages
Create a program that checks as to which stage an age is. Use the table below.

Age Stage
5-12 years Grade-schooler
13-17 years Teen
18-21 years Young adult

2. LRT-2 Single Journey Fare Matrix


Create a program that displays the fare based on the entered destination. The starting
station is Araneta-Cubao. Use the table below. Use the code destination to shorten the
user’s input.

Destination Fare
Recto (RE) PHP 25
J.Ruiz (JR) PHP 20
Gilmore (Gi) PHP 15

Activity 2.1 & 2.2


Create Nested If Programs
Analyze the problems carefully. Create the programs. Follow the file name format and file
location when saving your work.
1. Concert Ticket
Create a simple concert ticketing system that allows users who are 18 years old and
above to buy tickets. The ticket prices are as follows:
VIP – PHP 4,500
Patron – PHP 3,500
Box regular – PHP 2,500
2. ATM (Automatic Teller Machine)
Create a simple ATM program that allows the user to check his or her balance after
entering his or her PIN. A message is shown when the balance is below PHP 8,000.
Another message is shown when the balance is PHP 8,000 and above.

31
Activity 3
Compute the Shipping Cost
Work with a partner. Analyze the problem carefully. Write the pseudocode and create the
program. Follow the file name format and file location when saving your work.
Create a simple shipping cost program that displays the shipping cost based on the
dimensional (DIM) weight and location. Use the data below.

DIM Weight Greater Manila Area Luzon


Maximum 30 kg Free Free
Minimum 31 kg PHP 115 PHP 305

Activity 4.1, 4.2, 4.3


Create Multiple Conditions Programs
Analyze the problems carefully. Create the programs.
1. Between Two (2) Numbers
 Create a program that identifies if the entered number is between 7 and 18.
 Modify your program. This time the user enters the starting and ending numbers of
the range.
2. Divisible by Two (2) Numbers
Create a program that identifies if the entered number is divisible by 5 and 11 using the
not operator.
3. Job Application
 Create a job application program where the applicant enters his or her age. Only
applicants who are 18-59 years old are eligible to apply.
 Display a message once the applicant is eligible.

Activity 5
Create a Fast-Food Delivery Program
Work with a classmate. Read and analyse the problem carefully. Construct the
algorithm by using a flowchart or a pseudocode and create the program.
Create a program that determines the delivery cost of a fast food based on the total
bill and location. Use the table below.

Total Bill Location Delivery Service


Less than PHP 1,000 Within Metro Manila Additional PHP 50
At least PHP 1,000 Within Metro Manila Free delivery
Less than PHP 1,500 Outside Metro Manila No delivery service
At least PHP 1,500 Outside Metro Manila Additional PHP 80
At least PHP 2,500 Outside Metro Manila Free delivery

32
Let’s Test Ourselves
Determine the Condition
Read each item carefully. Write True if the item is correct, else write False.
____ 1. The nested if structure has an if block placed in its condition.
____ 2. The creation of algorithm is done before using the nested if.
____ 3. A nested if structure has two (2) levels of conditions or more.
____ 4. The program will run properly with no indentions.
____ 5. The first condition always has a nested if as its true value.

References
Computers for Digital Learners; Programming; ICT Tools Today High School
Series; Phoenix Publishing House

https://www.tutorialspoint.com

www.CodeMonkey.com

33

You might also like