IGS1131
Software Programming (Python)
Loop
For
A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).
This is less like the for keyword in other programming languages and works more like an iterator method as
found in other object-orientated programming languages.
With the for loop, we can execute a set of statements, once for each item in a list, tuple, set etc.
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
The for loop does not require an indexing variable to set beforehand.
Looping Through a String
Even strings are iterable objects, they contain a sequence of characters:
Loop through the letters in the word "banana":
for x in "banana":
print(x)
names = ["Geralt", "Aragorn", "Legolas"]
print("---------------")
for x in names:
print(x)
print("---------------")
for x in names[0]:
print(x)
print("---------------")
The break Statement
With the break statement we can stop the loop before it has looped through all
the items:
Exit the loop when x is "banana":
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break
Exit the loop when x is "banana", but this time the break comes before the print:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
break
print(x)
number = 0
for number in range(10):
if number == 5:
break # break here
The variable number is initialized at 0 in this small program.
Then a for statement constructs the loop if the variable
print('Number is ' + str(number))
number is less than 10.
print('Out of loop')
Within the for loop, an if statement presents the condition
that if the variable number is equivalent to the integer 5,
then the loop will break.
Within the loop is also a print() statement that will execute
with each iteration of the for loop until the loop breaks, since
it is after the break statement.
Let’s place a final print() statement outside of the for loop to
know when you are out of the loop.
The continue Statement
With the continue statement we can stop the current iteration of the loop, and
continue with the next:
Do not print banana:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)
number = 0
for number in range(10):
if number == 5:
continue # continue here
print('Number is ' + str(number)) Here, Number is 5 never occurs in the output, but the loop
continues after that point to print lines for the numbers 6–10
print('Out of loop') before leaving the loop.
You can use the continue statement to avoid deeply nested
conditional code or optimize a loop by eliminating frequently
occurring cases you would like to reject.
The continue statement causes a program to skip certain
factors that come up within a loop but then continue
through the rest of the loop.
The range() Function
To loop through a set of code a specified number of times, we can use the range() function,
The range() function returns a sequence of numbers, starting from 0 by default, and
increments by 1 (by default), and ends at a specified number.
Using the range() function
for x in range(6):
print(x)
Note that range(6) is not the values of 0 to 6, but
the values 0 to 5.
The range() function defaults to 0 as a starting value, however it is possible
to specify the starting value by adding a parameter: range(2, 6), which
means values from 2 to 6 (but not including 6):
Using the start parameter
for x in range(2, 6):
print(x)
The range() function defaults to increment the sequence by 1, however it is possible to
specify the increment value by adding a third parameter: range(2, 30, 3):
Increment the sequence with 3 (default is 1)
for x in range(2, 30, 3):
print(x)
Else in For Loop
The else keyword in a for loop specifies a block of code to be executed when the loop is
finished:
Print all numbers from 0 to 5, and print a message when the loop has ended:
for x in range(6):
print(x)
else:
print("Finally finished!")
The else block will NOT be executed if the loop is stopped by a break statement.
Break the loop when x is 3, and see what happens with the
else block:
for x in range(6):
if x == 3: break
print(x)
else:
print("Finally finished!")
for num in [1, 2, 3]:
if num == 4:
break
else:
print("Loop completed without breaking")
Nested Loops
A nested loop is a loop inside a loop.
The "inner loop" will be executed one time for each iteration of the "outer loop":
Print each adjective for every fruit:
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for x in adj:
for y in fruits:
print(x, y)
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 [0, 1, 2]:
pass
After the if conditional statement, the pass statement tells
number = 0 the program to continue running the loop and ignore that the
variable number evaluates as equivalent to 5 during one of
for number in range(10): its iterations.
if number == 5:
pass # pass here
print('Number is ' + str(number))
print('Out of loop')
Using zip() to iterate over multiple sequences
zip() can combine two (or more) sequences and iterate over them together.
names = ["Alice", "Bob", "Charlie"]
scores = [85, 92, 78]
for name, score in zip(names, scores):
print(f"{name} scored {score}")
Looping through a dictionary
student = {"name": "John", "age": 20, "grade": "A"}
for key, value in student.items():
print(key, ":", value)
Multiplication table
number = 5
for i in range(1, 11):
print(f"{number} x {i} = {number * i}")
Sum of numbers in a list
numbers = [1, 2, 3, 4, 5]
total = 0
for num in numbers:
total += num
print("Sum:", total)
Finding even numbers in a range
for i in range(10):
if i % 2 == 0:
print(i, "is even")
Reversing a list
fruits = ["apple", "banana", "cherry"]
for i in range(len(fruits) - 1, -1, -1):
print(fruits[i])
Backward
Range-1
stop