Loops in Python
Loops in Python
Loop definition:
In general, statements are executed sequentially: The first statement in a function is
executed first, followed by the second, and so on. There may be a situation when you
need to execute a block of code several number of times.
Programming languages provide various control structures that allow for more
complicated execution paths.
A loop statement allows us to execute a statement or group of statements multiple
times. The following diagram illustrates a loop statement −
For loop:
Def: For loops are used for sequential traversal. For example:
traversing a list or string or array etc. In Python, there is no C style for
loop, i.e., for (i=0; i<n; i++). There is “for in” loop which is similar to for
each loop in other languages
Syntax:
for i in (range or variable which can iterable):
@@@@//code which is going to execute throughout the loop
Note: @@@@ is indentation
Example: code
print("List Iteration")
l = ["geeks", "for", "geeks"]
for i in l:
print(i)
output:
List Iteration
geeks
for
geeks
While loop:
Def: In python, a while loop is used to execute a block of statements
repeatedly until a given condition is satisfied. And when the condition
becomes false, the line immediately after the loop in the program is
executed.
Syntax:
while expression:
@@@@//executable code
Example:CODE
count = 0
while (count < 3):
count = count + 1
print("Hello Geek")
output:
Hello Geek
Hello Geek
Hello Geek
Nested loop:
Def: Python programming language allows to use one loop inside
another loop. Following section shows few examples to illustrate the
concept.
Syntax:
while expression:
while expression:
statement(s)
statement(s)
A final note on loop nesting is that we can put any type of loop inside of
any other type of loop. For example, a for loop can be inside a while
loop or vice versa.
Example:
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