For loops

If you want to run some code until certain conditional stop being True, then, you need a while loop. Loops are basically the backbone of coding. To code a while loop you need the instruction "while(x):" (remember the indentation), where x is a conditional that might or might not change after each iteration.

Range function

To loop through some code a specified number of times, we can use the "range(start,end,step)" function, it can be used in 3 different ways:

Function Description
range(x) Returns a sequence of numbers, starting from 0, and increments by 1, and ends at "x-1".
range(x,y) Returns a sequence of numbers, starting from "x", and increments by 1, and ends at "y-1".
range(x,y,z) Returns a sequence of numbers, starting from "x", and increments by "z", and ends at a number different from "z".
# This loop will print the numbers 0, 1, 2, 3, 4, 5
for a in range(6):
    print(a)

# This loop will print the numbers 6, 7, 8, 9
for a in range(6,10):
    print(a)

# This loop will print the even numbers from 2 to 10
for a in range(2,11,2):
    print(a)

# This loop goes from 10 to 0
for a in range(10,-1,-1):
    print(a)

For loop through data types

You can loop through data types that stores other elements, such as tuples, lists, strings and more (we will talk about that more in a later topic). For now, you must learn that these indexable data types can use 2 types of for loops.

For loop Description
for ele in X: Iterate over the elements of X. "ele" changes per iteration to the current element in X.
for ele in sorted(X): Iterate over the sorted elements of X, keep in mind that the elements inside X must be of the same type. Keep in mind that the "sorted(X)" function has a complexity of O(N log N)
for i, ele in enumerate(X): Iterate over the elements of X, and "i" is the index of the current element per iteration. You can also apply the enumerate function over "sorted(X)".
A = [7,6,5,4,3,2,1]
B = 'HelloWorld!'

# These loops will print 7, 6, 5, 4, 3, 2, 1
for i in range(len(A)):
    print(A[i])

for ele in A:
    print(ele)

# This loop will print 1, 2, 3, 4, 5, 6, 7
for ele in sorted(A):
    print(ele)

# This loop will print the index and 2 times the element
for i,ele in enumerate(A):
    print(i,ele,A[i])

# This loop will print "H e l l o W o r l d ! "
for letter in B:
    print(letter, end=' ')

Extract multiple elements when you pass through the data type

You can iterate through the data type and extract the elements from it. Take care that the amount of variables you are using corresponds to the length of each element inside of the data type.

A = [
    [1,2],
    [3,4],
    [5,6]
]

"""
These loops will print:
1 + 2 = 3
3 + 4 = 7
5 + 6 = 11
"""

for row in A:
    first, second = row # Take care to have the same amount of elements on both sides
    print( "{} + {} = {}".format(first, second, first+second) )

"""
You can iterate and extract elements through a data type, 
but take care that the each element in the data type must have the same amount 
of elements you are extracting

arr = [
    [a1, a2, a3, ... an],
    [b1, b2, b3, ... bn],
    [c1, c2, c3, ... cn],
    ...
]

for (x1, x2, x3, ... xn) in arr:
    pass
"""

# Parentheses are optional
for first, second in A: # Take care than all elements in A have the same amount of elements
    print( "{} + {} = {}".format(first, second, first+second) )

Break statement

The "break" statement stops the loop right in that place, and get out of it.

# This will print 10, 9, 8, 7, 6, 5 per line
for i in range(10,0,-1):
    print(i)
    if i == 5:
        break

# This will search for a number in an array
search = 5
A = [6, 4, 7, 2, 3, 5, 9]
for i in range(len(A)):
    if A[i] == search:
        print("Found")
        break

Continue statement

The "continue" statement stops the current iteration, and continue with the next one.

# This code will print just even numbers
for i in range(10):
    if i%2:
        continue
    print(i)
    

Else statement

The "else" statement runs a block of code once when the condition no longer is true. This part of code will not run if we stop the for loop with a "break".

# This will search for a number in an array and print Found
search = 5
A = [6, 4, 7, 2, 3, 5, 9]
for a in A:
    if a == search:
        print("Found")
        break
else:
    print("Not found")

# This will search for a number in an array and print Not found
search = 5
A = [6, 4, 7, 2, 3, 9]
for a in A:
    if a == search:
        print("Found")
        break
else:
    print("Not found")

# This will search for a number in an array and won't print anything
search = 5
A = [6, 4, 7, 2, 3, 9]
for a in A:
    if a == search:
        print("Found")
        break

Nested for loop

A nested loop is a loop inside a loop. Pretty simple and well used.

"""
This code will print
        *
       ***
      *****
     *******
    *********
   ***********
  *************
 ***************
*****************
"""
lvl = 8
for i in range(lvl+1):
    for j in range(lvl-i):
        print(' ', end='')
    
    for k in range(2*i+1):
        print('*', end='')

    print('')