0% found this document useful (0 votes)
94 views

Module-4-INTEGRATIVE PROGRAMMING 2

This document discusses conditional statements and loops in Python. It covers if, if/else, and chained conditional if/elif/else statements. It also covers nested conditional statements and logical operators that can simplify conditionals. The document then discusses iteration with for and while loops in Python. It provides examples of using conditional statements and reassignment of variables in Python code.

Uploaded by

Randy Tabaog
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
94 views

Module-4-INTEGRATIVE PROGRAMMING 2

This document discusses conditional statements and loops in Python. It covers if, if/else, and chained conditional if/elif/else statements. It also covers nested conditional statements and logical operators that can simplify conditionals. The document then discusses iteration with for and while loops in Python. It provides examples of using conditional statements and reassignment of variables in Python code.

Uploaded by

Randy Tabaog
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

UNIVERSITY OF CAGAYAN VALLEY

Tuguegarao City

College of Information Technology


First Semester, S.Y. 2020-2021

Course Code :
Course Title : INTEGRATIVE PROGRAMMING 2

PRELIM PERIODIC COVERAGE

MODULE No. 04
TITLE: CONDITIONAL AND LOOPS 1
INTRODUCTION
LEARNING 1.
OUTCOMES
LEARNING 1.
OBJECTIVES

Discussion/Situational analysis/Content Etc.:


4. Conditionals and loops
4.1. Conditional execution
4.1.1. The if statement
In order to write useful programs, we almost always need the ability to check conditions and change the behavior of the
program accordingly. Conditional statements give us this ability. The simplest form is the if statement, which has the
general form:

if BOOLEAN EXPRESSION:
STATEMENTS

A few important things to note about if statements:


1. The colon (:) is significant and required. It separates the header of the compound statement from the body.
2. The line after the colon must be indented. It is standard in Python to use four spaces for indenting.
3. All lines indented the same amount after the colon will be executed whenever the BOOLEAN_EXPRESSION
is true.

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

College of Information Technology


First Semester, S.Y. 2020-2021

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

College of Information Technology


First Semester, S.Y. 2020-2021

The syntax for an if else statement looks like this:

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 True: # This is always true


pass # so this is always executed, but it does nothing
else:
pass
Python terminology
Python documentation sometimes uses the term suite of statements to mean what we have called a block here. They mean the
same thing, and since most other languages and computer scientists use the word block, we’ll stick with that.
Notice too that else is not a statement. The if statement has two clauses, one of which is the (optional) else clause. The Python
documentation calls both forms, together with the next form we are about to meet, the if statement.

4.2. Chained conditionals (if-elif-else statement)


Sometimes there are more than two possibilities and we need more than two branches. One way to express a
computation like that is a chained conditional:

if x < y:
STATEMENTS_A
elif x > y:
STATEMENTS_B
else:
STATEMENTS_C

Page 3
UNIVERSITY OF CAGAYAN VALLEY
Tuguegarao City

College of Information Technology


First Semester, S.Y. 2020-2021

Flowchart of this chained conditional

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

College of Information Technology


First Semester, S.Y. 2020-2021

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:

if 0 < x: # assume x is an int here


if x < 10:
print("x is a positive single digit.")

The print function is called only if we make it past both the conditionals, so we can use the and operator:

if 0 < x and x < 10:


print("x is a positive single digit.")
Note
Python actually allows a short hand form for this, so the following will also work:

if 0 < x < 10:


print("x is a positive single digit.")

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

College of Information Technology


First Semester, S.Y. 2020-2021

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)

The output of this program is

5
7

because the first time bruce is printed, its value is 5, and the second time, its value is 7.

Here is what reassignment looks like in a state snapshot:

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

College of Information Technology


First Semester, S.Y. 2020-2021

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

You might also like