Python Lesson 10: Creating loops in Python

  1. Writing a For Loop based on a range
  2. Writing a For Loop based on a subset of a range
  3. Writing a For Loop using step counts

Loops allow you to execute a block of code multiple times. There are 2 types of loops in Python:

  • For Loops
  • While Loops

Writing a For Loop based on a range: The range function generates a sequence of numbers starting with 0.

#creates a loop starting with 0 and ending in 4 
for x in range(5):
    print(x)
Notebook Output

Writing a For Loop based on a subset of a range: Use the range function to generate a loop starting at position 5 and ending at position 9

# for loop using range from item 5 to item 10 (5 items)
for x in range(5,10):
    print(x)
Notebook Output

Writing a For Loop using step counts: Use the range function to generate a loop with 10 positions and output only every 2 positions.

# for loop using range from items 0 to item 10 count by 2. (5 items)
for x in range(0,10,2):
    print(x)
Notebook Output

Recommended Books