Python for loop Function

Python for loop iterates through all elements of a list or similar data types.

>>> x = [1,3,5,7,9]
>>> for i in x: i
1
3
5
7
9
Iterating by indices:
>>> for i in range(len(x)): i, x[i]
(0,1)
(1,3)
(2,5)
(3,7)
(4,9)
Python for loop use indent to mark the statements inside the loop, there is no "{ ... }" structure like other languages
>>> for i in range(1,8):
... if(i == 5):
... break #break out if i equals 5
... print (i)
...
1
2
3
4
>>> for i in range(1,8):
... if(i == 5):
... break #break out if i equals 5
... print (i) #Error, no indent here
...
File "", line 4
print (i)
^
SyntaxError: invalid syntax

















endmemo.com © 2024  | Terms of Use | Privacy | Home