Python Beginners Tutorial # 6: For Loops

For Loops

Are used for iterating over a sequence. For loops can be used on lists, tuples, a dictionaries, sets, and strings .

pets = ["dog", "cat", "fish"]
for x in pets:
  print(x)
Output :
["dog", "cat", "fish"]
For Loop on String

Loops can be used on strings. In the example below, a loops is used to print out each letter of the word Python.

for x in "Python":
  print(x)
Output :
P
y
t
h
o
n
For Loops with Break

Breaks will stop the loop at certain item in sequence

pets = ["dog", "cat", "fish"]
for x in pets:
  print(x)
  if x == "cat":
    break
Output :
dog
cat
Using Range() and For Loops

Function range() is used to create a sequence of numbers. Keep in mind that the sequence starts from 0. Example, range(3) would result in a sequence of 0,1,2.

# Creates range 0 - 4
for x in range(5):
  print(x)

# select range 1 - 3
for x in range(1, 3):
  print(x)

Using Else statement in For Loops

for x in range(4):
  print(x)
else:
  print("Times Up!")
Output :
0
1
2
3
Times Up!

Nested For Loops

Nested loops have a loop with in a loop.

adj = ["small", "big", "med"]
pets = ["dog", "cat", "fish"]

for x in adj:
  for y in pets:
    print(x, y)
Output
small dog
small cat
small fish
big dog
big cat
big fish
med dog
med cat
med fish
Click here for Part Seven : Functions