nested for loop in python
A loop may contain another loop in its body .This form of a loop is called Nested for loop .But in a nested for loop , inner loop must terminate before the outer loop.
Syntax
for iterator_var in sequence:
for iterator_var in sequence:
statements(s)
statements(s)
Example
Example 1
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for x in adj:
for y in fruits:
print(x, y)
Output
red apple
red banana
red cherry
big apple
big banana
big cherry
tasty apple
tasty banana
tasty cherry
Example2
# Python program to illustrate
# nested for loops in Python
from __future__ import print_function
for i in range(1, 5):
for j in range(i):
print(i, end=' ')
print()
Output
1
2 2
3 3 3
4 4 4 4
No comments:
Post a Comment
for more information please share like comment and subscribe