For Loops in Python

A for loop in python is an iterator that can be used to iterate over a sequence. This sequence can be a range, list, set, or string

  • Using range: range is a function that returns a sequence in the following order:
range(start, stop, step)

# Example 1
range(0,5)
# The following sequence will be returned: 0,1,2,3,4

range(0,5) == range(5) # True

# Example 2
range(0,10,2) 
# The following sequence will be returned: 0,2,4,6,8
"""
Note that range() function is exclusive.
This means that it does not include the last number in the result
"""
for x in range(0,100):
    print(x)
"""
Expected output will be all the values between 0 and 99
"""
  • Iterating over a list
universities  = ["TUK", "UON", "JKUAT", "DeKUT", "Moi", "KU"]
for university in universities:
    print(university)
  • Breaking a for loop The for loop break statement causes the loop to break(stop the iteration) once a set condition is met
universities  = ["TUK", "UON", "JKUAT", "DeKUT", "Moi", "KU"]
for university in universities:
    print(university)
    if university == "DeKUT":
        break
  • The continue statement
for university in universities:
    print(university)
    if university == "DeKUT":
        continue
# This code will print all the items in the list but will skip "DeKUT"