CMSC 11 Handout 3
CMSC 11 Handout 3
Handout No. 3
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
Example 2:
N = int(input(How many numbers will you enter?:))
i = 0
while i < N:
num = int(input(Enter a number: ))
print(Youve entered, num)
i = i + 1
RBAguila
Handout No. 3
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.
Syntax:
for variable in sequence:
block_of_code
RBAguila
Handout No. 3
Example 5:
#this loop only stops when youve entered five zeroes
num_of_zeroes = 0
loop_num = 1
while num_of_zeroes < 5:
print(This is loop number:, loop_num)
num = int(input(Enter an integer: ))
if num == 0:
num_of_zeroes = num_of_zeroes + 1
loop_num = loop_num + 1
Nested Loops
same as \n.
Infinite Loops
RBAguila
Handout No. 3
Example 8:
while True:
num = int(input(Enter a positive number:))
if num <= 0:
print(Youve entered a non-positive number.)
break
continue forces a loop again, skipping the rest of the body. Once a continue is
encountered, we stop the current iteration and move to the next one.
Example 9:
for i in range(0,10)
if i % 2 == 0
print(We found an even number.)
continue
print(i)
References:
1. Laboratory Guide (JMBawagan)
2. CMSC 11 Lab Session 2 Handout (GBCEmalada)
RBAguila