A for loops allows us to execute a block of code multiple times with some parameters updated each time through the loop .A for loop begins with the for statement:
iterable=[1,2,3]
for item in iterable:
# code block indented 4 spaces
print(item)
1
2
3
The main points to observe are:
for and in keywords
iterable is a sequence object such as a list, tuple or range
item is a variable which takes each value in iterable
ends for statement with a colon:
code block indented 4 spaces which executes once for each value initerable
For example ,let's print n*2 for n from 0 to 5:
for n in [0,1,2,3,4,5]:
square=n**2
print(n,'squared is ',square)
print('The for loop is complete!)
0 squared is 0
1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25
The for loop is comlete!
Get Answers For Free
Most questions answered within 1 hours.