Python For Loops

For loop is an iterator in Python. It is used to iterate over iterable objects like strings, lists, tuples.

# Iterating through a string
val = "123456789"
total = 0
for x in val:
    total += int(x)
print(total)

# 45
# Iterating through a list
colors = ["Red", "Blue", "Yellow", "Green"]
for color in colors:
    print(color)

# Red
# Blue
# Yellow
# Green

Range() Function

The range() function is used to generate a sequence of numbers. When range() function is used with one parameter, it returns numbers from zero up to the number given in the parameter.

for number in range(5):
    print(number)

# This program will print numbers from 0 to 5
# Stop number is exclusive in range() function
# 0, 1, 2, 3, 4 will be printed in the output

range() function can have 3 parameters in the following format.

 range([start], stop [, step])

Start parameter indicates the starting number of the sequence. This parameter is optional. If not specified starting number is 0.

Stop parameter indicates the stopping number of the sequence. Generated sequence of numbers will not include the stop number.

Step parameter indicates the increment between numbers in the sequence. This parameter is also optional, if not specified step is 1.

Nested For Loop

Python allows nested for loops. Inner for loop will be iterated for each iteration of outer for loop.

mathClass = ["John", "Charlie", "Lindsay", "Kylie"]
chemistryClass = ["Leonardo", "Kylie", "Nancy", "Charlie"]

for mathStudent in mathClass:
    for chemistryStudent in chemistryClass:
        if mathStudent == chemistryStudent:
            print(mathStudent + " is in both classes.")

# Charlie is in both classes.
# Kylie is in both classes.

Break, Continue, Pass Statements

break, continue, pass statements are used in (For/While) loops in Python. break statement is used to exit the loop, continue statement is used to skip the current iteration, pass statement is used when you don’t want to execute a code block. To get detailed information you can read Python Break, Continue, Pass Statements.

Else Statement in For Loops

When else statement is used in a For loop, Else code block is executed after for loop execution unless break statement is run.

In the sample code below, if John’s phone number exists in the phone directory, it’s printed on screen and break statement exits the for loop. Since break statement is run, else code block is not executed.

for name in phoneDirectory:
    if name == "John":
        print("John's phone number is : " + phoneDirectory[name])
        break
else:
    print("John is not in phone directory.")