Repetitions with for loops¶
In Python, for loop is usually used with the range() or the xrange() function. To print a number from 1 to 10:
for i in range(1, 11):
print i
#output:
1
2
3
4
5
6
7
8
9
10
Using for loop with List¶
for loop is usually used to traverse the elements in a list. For example, to add all the numbers in a list:
num_list = [2, 5, 9, 1, 4]
total = 0
for num in num_list:
total += num
print "Total: ", total
#ouput:
'Total: 21'
More on the range() function¶
The range(start, end, step) function takes in 3 arguments and generate a list of number based on these arguments. Some examples are shown below:
>>> range(10) # by default, start = 0, step = 1, last number: 10 is not included
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(5, 10) # by default, step = 1
[5, 6, 7, 8, 9]
>>>> range(2, 10, 2)
[2, 4, 6, 8]
The code belows show a comparison of the for loop in Java and Python.
# Java code, printing 1, 3, 5, 7, 9
for (int i = 1; i < 10; i+=2)
System.out.println(i);
# Python code, printing 1, 3, 5, 7, 9
for i in range(1, 10, 2):
print i
See also
Ready for some practice? Test your understanding at PySchools: For Loops.