Python for Loop Statements

The most used looping control statement in Python is the for loop. For loop is used to iterate over a range of items like the list, tuples, strings or other iterable objects.

The syntax of for loop in python is given below.

for val in sequence:
loop body
Let us browse some examples to get a clearer picture of the loop in Python.
Example 1:- Print characters of a string
text = "Demo"

for val in text:
    print(val)
D
e
m
o
Example2:- Using range in for loop
range function is used to get the range of values in between two integers. Let’s use range function to print number from 1 to 10.
for val in range(0,10):
    print(val, end="\t")
print("\nEnd of loop")
0 1 2 3 4 5 6 7 8 9
End of loop
Example3:- Use for loop with a list
numbers = [1, 2, 3]
for val in numbers:
    print(val)
1
2
3

for loop with else

We can use an optional block with for loop that will execute once the loop is terminated. But one thing to notice is that, if the loop contains any loop control statement ( i.e. break, continue or pass ), then the else block is not executed.

numbers = [1, 2, 3]
for val in numbers:
    print(val)
else:
    print("Loop terminated")
1
2
3
Loop terminated
SHARE Python for Loop Statements

You may also like...

Leave a Reply

Your email address will not be published.

Share