For loop in Python
The for statement is used to iterate/repeat itself over a range of values or a sequence. The for loop is executed for each of these items in the range. These values can be either numeric, or, as we shall see in the successive chapters, elements of a data structure like a string, list, or tuple.
With every iteration of the loop, the control variable checks whether each of the values in the range has been traversed or not. When all the items in the range are exhausted, the body of the loop is not executed anymore; the control is then transferred to the statement immediately following the for loop.
In for loop, it is known in advance how many times the loop is going to be executed.
Syntax:
for x in (iteratable object):
#Statement to be executed
The range() function
Syntax:
Range([start],stop[,step])
Command | Output |
>>>range(10) | [0,1,2,3,4,5,6,7,8,9] |
>>>range(1,11) | [1,2,3,4,5,6,7,8,9,10] |
>>>range(0,10,2) | [0,2,4,6,8] |
>>>range(0,-9,-1) | [0,-1,-2,-3,-4,-5,-6,-7,-8] |
Example:
for x in range(5):
print(x)
Output:
0
1
2
3
4
# program to display student's marks from record
student_name = 'James'
marks = {'James': 90, 'Jules': 55, 'Arthur': 77}
for student in marks:
if student == student_name:
print(marks[student])
break
else:
print('No entry with that name found.')
Output:
90
# Program to iterate through a list using indexing
mySubjects = ['Maths', 'Physics', 'Computer Science']
# iterate over the list using index
for i in range(len(mySubjects)):
print("I like", mySubjects[i])
Output:
I like Maths
I like Physics
I like Computer Science