Archive for the ‘Python 3.x’ Category
Python for loops
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.
- A range for-loop goes from a low numerical value to a high numerical value, like:
for i in range(0,3): print i |
It prints the following range values:
0 1 2 |
- A for-each loop goes from the first to the last item while ignoring indexes, like:
list = ['a','b','c'] for i in list: print i |
It prints the following elements of the list:
a b c |
- A for-loop with enumeration goes from the first to the last item while ignoring indexes, like:
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.