It has the ability to iterate over the items of any sequence, such as a list or a string.
The for statement in Python differs a bit from what you may be used to in C or Java. Rather than giving the user the ability to define both the iteration step and halting condition (as C), Python?s for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence.
Syntax of Loop
for iterating_var in sequence: statements(s)
The range() Function
# Example of range() function seq=range(5) for n in seq: print(n) # save file anyname.py # open cmd and type : python anyname.pyOutput:
0 1 2 3 4
Example: range(start, end)
# Example of range(start, end) function for i in range(1,6): print(i) # save file anyname.py # open cmd and type : python anyname.py
1 2 3 4 5
Example: printing the elements of list
# printing the elements of list list=['java','python','php','dotnet'] for x in list: print(x)
java python php dotnet
Example : print the numbers in reverse order
# printing the number in reverse order print(list(range(10))) for i in range(10,0,-1): print(i)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 10 9 8 7 6 5 4 3 2 1