MacLochlainns Weblog

Michael McLaughlin's Technical Blog

Site Admin

Archive for the ‘Python 3.x’ Category

Python for loops

without comments

It’s always interesting to explain a new programming language to students. Python does presents some challenges to that learning process. I think for-loops can be a bit of a challenge until you understand them. Many students are most familiar with the traditional for loop like Java:

for (i = 0; i < 5; i++) { ... }

Python supports three types of for-loops – a range for loop, a for-each expression, and a for-loop with enumeration. Below are examples of each of these loops.

  1. A range for-loop goes from a low numerical value to a high numerical value, like:
  2. for i in range(0,3):
      print i

    It prints the following range values:

    0
    1
    2
  1. A for-each loop goes from the first to the last item while ignoring indexes, like:
  2. list = ['a','b','c']
    for i in list:
      print i

    It prints the following elements of the list:

    a
    b
    c
  1. A for-loop with enumeration goes from the first to the last item while ignoring indexes, like:
  2. list = ['a','b','c']
      for i, e in enumerate(list):
        print "[" + str(i) + "][" + list[i] + "]"

    The i represents the index values and the e represents the elements of a list. The str() function casts the numeric value to a string.

    It prints the following:

    [0][a]
    [1][b]
    [2][c]

This should help my students and I hope it helps you if you’re trying to sort out how to use for loops in Python.

Written by maclochlainn

October 19th, 2016 at 9:02 pm