Home » Learn Python » Loops » “for” Loops

“for” Loops

The most common kind of loop in most programming languages is the for loop. This has a slightly different syntax in different programming languages. Python’s implementation of for loops is particularly unusual, and interestingly different. Here’s an example of how it looks in Python.

for i in range(5):
    print("hello", i)
hello 0
hello 1
hello 2
hello 3
hello 4

Here, i is simply the name of a loop variable which I’ve made up. It can be whatever you want.

The for … in construct loops over whatever is supplied to it, setting the loop variable to each value in turn. The object you use here must be something that can be “looped over”; in other words, it must be an iterator.

The range function creates a range object (an iterator) which supplies, in this case, five numbers, from 0 to 4.

The Range Function

The range function can take a maximum of three arguments. They must all be integers.

  • If only one argument is supplied, the loop counts from zero up to (but not including) the argument value.
  • If two arguments are supplied, the loop counts from the first argument up to (but not including) the second argument.
  • If a third argument is supplied, this specifies a step size.
for value in range(2, 10, 2):
    print("hello", value)
hello 2
hello 4
hello 6
hello 8

Leave a Reply

Blog at WordPress.com.