Module-4-INTEGRATIVE PROGRAMMING 2
Module-4-INTEGRATIVE PROGRAMMING 2
Tuguegarao City
Course Code :
Course Title : INTEGRATIVE PROGRAMMING 2
MODULE No. 04
TITLE: CONDITIONAL AND LOOPS 1
INTRODUCTION
LEARNING 1.
OUTCOMES
LEARNING 1.
OBJECTIVES
if BOOLEAN EXPRESSION:
STATEMENTS
Here is an example:
food = 'spam'
if food == 'spam':
print('Ummmm, my favorite!')
print('I feel like saying it 100 times...')
print(100 * (food + '! '))
The Boolean expression after the if statement is called the condition. If it is true, then all the indented statements get
executed. What happens if the condition is false, and food is not equal to 'spam'? In a simple if statement like this,
nothing happens, and the program continues on to the next statement.
Run this example code and see what happens. Then change the value of food to something other than 'spam' and run it
again, confirming that you don’t get any output.
Flowchart of an if statement
Page 1
UNIVERSITY OF CAGAYAN VALLEY
Tuguegarao City
the if statement is a compound statement. Compound statements consist of a header line and a body. The header line
of the if statement begins with the keyword if followed by a boolean expression and ends with a colon (:).
The indented statements that follow are called a block. The first unindented statement marks the end of the block. Each
statement inside the block must have the same indentation.
4.1.2. The if else statement
It is frequently the case that you want one thing to happen when a condition it true, and something else to happen when
it is false. For that we have the if else statement.
if food == 'spam':
print('Ummmm, my favorite!')
else:
print("No, I won't have it. I want spam!")
Here, the first print statement will execute if food is equal to 'spam', and the print statement indented under
the else clause will get executed when it is not.
Flowchart of a if else statement
Page 2
UNIVERSITY OF CAGAYAN VALLEY
Tuguegarao City
if BOOLEAN EXPRESSION:
STATEMENTS_1 # executed if condition evaluates to True
else:
STATEMENTS_2 # executed if condition evaluates to False
Each statement inside the if block of an if else statement is executed in order if the boolean expression evaluates
to True. The entire block of statements is skipped if the boolean expression evaluates to False, and instead all the
statements under the else clause are executed.
There is no limit on the number of statements that can appear under the two clauses of an if else statement, but there has
to be at least one statement in each block. Occasionally, it is useful to have a section with no statements (usually as a
place keeper, or scaffolding, for code you haven’t written yet). In that case, you can use the pass statement, which does
nothing except act as a placeholder.
if x < y:
STATEMENTS_A
elif x > y:
STATEMENTS_B
else:
STATEMENTS_C
Page 3
UNIVERSITY OF CAGAYAN VALLEY
Tuguegarao City
elif is an abbreviation of else if. Again, exactly one branch will be executed. There is no limit of the number
of elif statements but only a single (and optional) final else statement is allowed and it must be the last branch in the
statement:
if choice == 'a':
print("You chose 'a'.")
elif choice == 'b':
print("You chose 'b'.")
elif choice == 'c':
print("You chose 'c'.")
else:
print("Invalid choice.")
Each condition is checked in order. If the first is false, the next is checked, and so on. If one of them is true, the
corresponding branch executes, and the statement ends. Even if more than one condition is true, only the first true
branch executes.
4.3. Nested conditionals
One conditional can also be nested within another. (It is the same theme of composibility, again!) We could have
written the previous example as follows:
Flowchart of this nested conditional
Page 4
UNIVERSITY OF CAGAYAN VALLEY
Tuguegarao City
if x < y:
STATEMENTS_A
else:
if x > y:
STATEMENTS_B
else:
STATEMENTS_C
The outer conditional contains two branches. The second branch contains another if statement, which has two branches
of its own. Those two branches could contain conditional statements as well.
Although the indentation of the statements makes the structure apparent, nested conditionals very quickly become
difficult to read. In general, it is a good idea to avoid them when you can.
Logical operators often provide a way to simplify nested conditional statements. For example, we can rewrite the
following code using a single conditional:
The print function is called only if we make it past both the conditionals, so we can use the and operator:
4.4. Iteration
Computers are often used to automate repetitive tasks. Repeating identical or similar tasks without making errors is
something that computers do well and people do poorly.
Page 5
UNIVERSITY OF CAGAYAN VALLEY
Tuguegarao City
Repeated execution of a set of statements is called iteration. Python has two statements for iteration – the for statement,
and the while statement.
4.4.1. Reassignmnent
it is legal to make more than one assignment to the same variable. A new assignment makes an existing variable refer to
a new value (and stop referring to the old value).
bruce = 5
print(bruce)
bruce = 7
print(bruce)
5
7
because the first time bruce is printed, its value is 5, and the second time, its value is 7.
With reassignment it is especially important to distinguish between an assignment statement and a boolean expression
that tests for equality. Because Python uses the equal token ( =) for assignment, it is tempting to interpret a statement
like a = b as a boolean test. Unlike mathematics, it is not! Remember that the Python token for the equality operator
is ==.
Note too that an equality test is symmetric, but assignment is not. For example, if a == 7 then 7 == a. But in Python, the
statement a = 7 is legal and 7 = a is not.
Furthermore, in mathematics, a statement of equality is always true. If a == b now, then a will always equal b. In
Python, an assignment statement can make two variables equal, but because of the possibility of reassignment, they
don’t have to stay that way:
a=5
b=a # after executing this line, a and b are now equal
a=3 # after executing this line, a and b are no longer equal
The third line changes the value of a but does not change the value of b, so they are no longer equal.
Note
In some programming languages, a different symbol is used for assignment, such as <- or :=, to avoid confusion. Python chose
to use the tokens = for assignment, and == for equality. This is a common choice, also found in languages like C, C++, Java,
JavaScript, and PHP, though it does make things a bit confusing for new programmers.
4.4.2. Updating variables
(increment (adding 1 to the value of our variable) and decrement (deducting 1 from the value
of our variable))
When an assignment statement is executed, the right-hand-side expression (i.e. the expression that comes after the
assignment token) is evaluated first. Then the result of that evaluation is written into the variable on the left hand side,
thereby changing it.
One of the most common forms of reassignment is an update, where the new value of the variable depends on its old
value.
Page 6
UNIVERSITY OF CAGAYAN VALLEY
Tuguegarao City
n=5
n=3*n+1
The second line means “get the current value of n, multiply it by three and add one, and put the answer back into n as its
new value”. So after executing the two lines above, n will have the value 16.
If you try to get the value of a variable that doesn’t exist yet, you’ll get an error:
>>> w = x + 1
Traceback (most recent call last):
File "<interactive input>", line 1, in
NameError: name 'x' is not defined
Before you can update a variable, you have to initialize it, usually with a simple assignment:
>>> x = 0
>>> x = x + 1
This second statement — updating a variable by adding 1 to it — is very common. It is called an increment of the
variable; subtracting 1 is called a decrement.
Page 7