FOR

This type of loop is used to iterate over the elements of a sequence, such as a list, string, tuple, dictionary, or any iterable object. Instead of relying on a condition like a while loop, a for loop processes each item in the sequence one by one, making it ideal when the number of iterations is known or directly tied to the items being iterated through. Python’s for loops are clean and readable, automatically handling iteration without needing manual counters unless you choose to use tools like range() or enumerate(). This makes them especially useful for tasks like processing collections, performing repeated actions for each item, or building new lists through comprehensions.

NUMBERS

numbers = [1, 6, 4, 3, 2, 5]
for number in numbers:
    print(number);

STRINGS

name = "Alice"
for char in name:
    print(char)

COUNTING SPECIFIC CHARACTERS

string = 'bolloon'

# use this variable to count occurrences of o
count_o = 0      

for i in string:
    if i == 'o':
        # iterate through the string, everytime you find an 'o', increase count_o by 1
        count_o = count_o + 1

print(count_o);

GENERATING RANGE OF NUMBERS

W/ STEP

TWO RANGE

SINGLE RANGE ARGUMENT

This it generates a sequence of numbers starting from 0 up to, but not including N.

Last updated