You are on page 1of 2

CMSC 11: Introduction to Computer Science

The process continues until the sequence


is exhausted or a break statement is executed
within the code block.

Handout #3: Iterative Statements


Iterative Statements
- Statements that causes the repeated execution
of a sequence of statements given that the
statement is true. It is often called a looping
statement.
There are two types of loops in Python (unlike in other
programming languages).
1. While loop
- A loop that repeatedly executes a statement as
long as the statement is true.
- A while loop must have an initialization, condition,
and increment/decrement or update statement.
General Format:
while Boolean_expression:
block_of_code

Example 3(using a step):


for count in range(0,10,3):
print(count)
The default step value is 1.
Example 4 (Prints the largest of n numbers):
n = int(input("Input N numbers: "))
ctr = 0
max1 = 0
while ctr < n:
x1 = int(input("Input number: "))
if(x1 > max1):
max1 = x1
ctr = ctr + 1
print("The largest number is", max1)
It can also be for ctr in range(0,n)

Example 1:
count = 0
while count < 10:
print(The count is, count)
count = count + 1

Nested loops
- They are loops within a loop.
Example 5:

2. For loop
- A loop that iterates over items in a sequence
whether a list or a string. It also must have an
initialization, condition, and increment.

for i in range(0,3):
for j in range(0,4):
print(j, end="")

General Format:
for variable in sequence:
block_of_code
A sequence can be defined by a range.
Using the range function:
The range function is used to iterate over
a sequence of numbers.
Example 2:
for i in range(0,10):
print(Counting from:, i)

print()
The end= parameter suppresses new lines. print() is the
same as \n.
Tracing example 5:
i
j

0
0

1
0

2
0

The variable following for is bound to the


first value of the sequence, and the code block is
executed.

CMSC 11 PYTHON HANDOUT #3 | GBCEmalada

Avoid infinite loops


These are common errors. The loop of the
program doesnt stop because the condition is always
true.

continue forces a loop to loop again, skipping the rest of


the body.

while True:
print(Hindi na ako aasa.)

i = 0

Example 8:

while i < 5:
Mixing conditional statements and loops
Conditional statements (if, if-else, nester if-else,
and if-elif-else) can be combined with loops (for or while)
to create a program that can solve a specific problem.

if i == 3:
i = i + 1
continue

Example 6:
print(i)
num = int(input("Enter range: "))
i = i + 1
for i in range(1, num):
if i % 2 == 0:
print(i,"is an even number")
else:
print(i,"is an odd number")

Behavior changing keywords


break exits out of the smallest enclosing loop. It
terminates the loop and transfers execution to the
statement after the loop.
Example 7:
i = 0
while i < 5:
if i == 4:
break
else:
print(i)
i = i + 1

CMSC 11 PYTHON HANDOUT #3 | GBCEmalada

You might also like