for
loop is used to iterate over elements of an iterable or sequence(i.e. list, tuple, dictionary, set, or string).
for item in iterable:
statement(s)
else:
statement(s)
Here,
break
statement.Note: When looping, after each iteration, the next item is retrieved from the iterable. The loop’s statement(s) will be continuously executed until the iterable container is empty.
Python has only one for loop, which is functionally the same as for each in some other languages. To loop a specified number of times range()
or xrange()
function is used.
>>> for i in range(7):
... print i
...
0
1
2
3
4
5
You can also iterate over files with a for loop:
>>> for line in open("/home/sagar/example.txt):
... print line
...
line 1
line 2
line 3
>>> for i in range(3):
... print i
... else:
... print("No break is used.")
...
0
1
2
No break is used.
In the following example, else condition won't be executed as there is break
statement used in for.
>>> for i in range(3):
... print(i)
... break
... else:
... print("Break used")
...
0