Lecture 6
Lecture 6
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.
The for loop does not require an indexing variable to set beforehand.
Looping Through a String
for x in "banana":
print(x)
With the break statement we can stop the loop before it has looped through all
the items:
With the continue statement we can stop the current iteration of the loop, and
continue with the next:
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.
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.
for x in range(6):
print(x)
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
The "inner loop" will be executed one time for each iteration of the "outer loop":
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.
print('Out of loop')
Using zip() to iterate over multiple sequences
zip() can combine two (or more) sequences and iterate over them together.
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)
for i in range(10):
if i % 2 == 0:
print(i, "is even")
Reversing a list
Backward
Range-1
stop