Programming in Python Part II PDF
Programming in Python Part II PDF
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.
1
What is It
else
Condition
Statement/s
else
Statement/s
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.
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.”
Pseudocode:
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!
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:
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.
9
The Indentations are used to show the levels of nesting.
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
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:
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.
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.
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.
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:
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:
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: ‘)
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: ‘)
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?
• 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
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).
<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.
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
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.
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
<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
• 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.
• 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”);
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”
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
Destination Fare
Recto (RE) PHP 25
J.Ruiz (JR) PHP 20
Gilmore (Gi) PHP 15
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.
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.
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