Loops
Loops
LOOPS
Summer 2025
REVIEW: if, if-else, if-elif-else,
nested if
if: for exceptional
Types of Loops:
for
while
1. while Loop:
while (Boolean expression):
statements
(1). Test the Boolean expression.
(2). If True:
then execute statements in
loop body, then go back to step 1).
# print(count)
count = 0
while (count < 9):
print ('The count is:', count, “Hello Python”)
count += 1
count = 0
while True:
if count > 10:
break
count += 1
print("Hello Python")
Stop loop by user’s input
# another example: for play game
while True:
play_again = input(" do you want to play again, y for yes and n for no>>")
print("bye")
2. for Loop: through a sequence
(1). Test the sequence if it is the end of it
(2). If False:
then execute statements in loop body,
then go to step (2).
#--------------------------------------------------
# (1) count is initialized as 0,
# the first element of sequence of 0, 1, 2, …, 9
# (2) then check if count < = 9 or not
# (3) if yes, print out
Range
range(start,stop,step)
• start: integer ( starting 0 by default)
• stop: integer (exclusive) i.e., end at stop – 1.
• step: integer (increment) 1 is default value
# inner loop
for j in range(4): # 0, 1, 2, 3
print(" inner ", j)
print("\n")
Example: 9x9 table
# example (9x9 table)
# outer loop
for i in range(1,10):
# inner loop
for j in range(1, 10):
print(i*j, end =" ")
print()
Break/Continue: loop interruption
for loop and while loop
Break:
◦ using if condition:
◦ True, then break the loop
Continue:
◦ Also using if condition:
◦ True, then skip the rest of loop
◦ Next round
Example 1: break
# your are given integer 1-100, print the first 5 even numbers
if count >= 5:
break
Example 2: continue
# example for continue: print number 1-10 but not 5
print('Out of loop')
Pass: do not change the loop even if the
condition is true
# Using pass, the program runs exactly, as it would if there were no
conditional statement in the program.
# The pass statement tells the program to disregard that condition and
continue to run the program as usual.
print('Out of loop')
Comparison: while loop and for loop
A for loop:
◦will “do” something to everything
A while loop:
◦ will “do” something until a condition is
met.
Exchangeable
Practice: Fizz-buzz
Run a loop to check a number between 1-20
◦ if a number is divisible by 3 print Fizz,
◦ by 5, print Buzz,
◦ If both divisible, print Fizz Buzz,
◦ any other number, print the number itself
Divisible by 3: num%3 == 0
HW 1
H1.A Letter Grades
H1.B May Calendar
END