5 Loops
5 Loops
Sokratis Sofianopoulos
1
Loops
2
For loop using the range function
• For loops can iterate over a sequence of numbers using the range function (we will see
functions next week)
• The range function can take 1, 2 or three parameters
• One parameter (n): Prints integer numbers from 0 to n-1
for x in range(5):
print(x)
• Two parameters (x, y) : Prints integer numbers from x to y-1
for x in range(4, 9):
print(x)
• Three parameters (x, y, z) : Prints integer numbers from x to y-1 with stride z
for x in range(3, 8, 2):
print(x)
3
Exercise
4
Solution
n = -1
while n not in range(1, 11):
n = int(input("Input a number: "))
for i in range(1,11):
print(f"{n} x {i} = {n*i}")
5
break and continue statements
• break is used to exit a loop (for or while)
• continue is used to skip the current block, and return to the "for" or "while" statement
• Break example:
count = 0
while True:
print(count)
count += 1
if count >= 5:
break
• Continue example:
for x in range(10):
if x % 2 == 0:
continue
print(x)
6
Using the else clause in a loop
7
Else example in a simple while loop
count=0
while(count<5):
print(count)
count +=1
else:
print("count value reached %d" %(count))
8
Else not reached because of break statement
9
Exercise
• Loop through and print out all even numbers from 1 to 200 with
a stride of 3 but
1. You must use a continue statement
2. As you go, count how many even numbers you find
3. After the loop, use an f-string to print a message with the
total number of even numbers that your script found
10
Solution
count=0
for number in range(1, 201, 3):
if number % 2 == 1:
continue
if count == 30:
break
count+=1
print(number)
print(f"Number of even numbers in range {count}")
11
The pass Statement
• for loops cannot be empty, but if you for some reason have a for loop with
no content, put in the pass statement to avoid getting an error:
for x in range(5):
pass
12