Topics
range() Function
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
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 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:
# by default, start = 0, step = 1, last number: 10 is not included >>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # by default, step = 1 >>> range(5, 10) [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
Code Snippets
This section will contain some code snippets to show some practical use of the topic that you have learnt.
# Printing patterns
# -------------------
+
+ +
+ + +
+ + + +
+ + + + +
for i in range(1, 6):
print i * "+ "
# Printing more patterns
# ----------------------
@ @ @ @ @
+ + + + +
@ @ @ @ @
+ + + + +
@ @ @ @ @
for i in range(1, 6):
if i % 2 == 0:
print 5 * "+ "
else:
print 5 * "@ "
Python Challenge