Python For Loop Statements

For Loop

The for loop is used to iterate objects for a number of times. The for loop is responsible for visiting every item and do a specific task. The for loop always iterate over an arithmetic number or index number.

Syntax:

for items in iterable_variable:
     # statement or body

Sample Code:

cars = ["ford", "bmw", "toyota", "kia", "audi"]
for x in cars :
  print(x)

# Output
# ford
# bmw
# toyota
# kia
# audi

Looping String:

Using python for loop, you can iterate the string values since it contains the sequence of characters.

Sample Code:

for i in "techieclues":
  print(i)

# Output
# t
# e
# c
# h
# i
# e
# c
# l
# u
# e
# s

Break and Continue Statements With For Loop:

The break keyword is used to terminate the currently executing loop. In the case of a nested loop, the break keyword can terminate the innermost loop. This break keyword can also stop the currently executing loop when a loop condition is in a true state.  

cars = ["ford", "bmw", "toyota", "kia", "audi", "Suzuki"]
for x in cars :
  print(x)
  if x == "kia"   # Stop execute the loop when the "kia" matches
     break

# Output
# ford
# bmw
# toyota
# kia

The continue keyword is used to skip the currently executing iteration of the loop and start the execution from the next iteration. 

cars = ["ford", "bmw", "toyota", "kia", "audi", "Suzuki"]
for x in cars :
    if x == "kia"   # Stop execute the current loop and continue next loop
       continue
    print(x)

# Output
# ford
# bmw
# toyota
# audi
# Suzuki

The range() function:

This is a built-in function. This range() function is used to iterate a number of sequences. It is used index number or arithmetic progression to iterate over and over.

Syntax:

for item in range (length):
     #Statement or body

Sample Code:

for i in range(8):
  print(i) 

# Output
# 0
# 1 
# 2
# 3
# 4
# 5
# 6
# 7