BASIC LOOP STRUCTURES
Python Supports basic loop structures through iterative
statements.
Iterative statements are decision control statements that are used
to repeat the execution of a list of statements.
Python language supports two types of iterative statement.
WHILE LOOP
The while loop provides a mechanism to repeat one or more
statements while a particular condition is True.
In python, While loop is used to execute a block of statements
repeatedly until the given condition is satisfied.
And when the condition becomes false, the line immediately after
the loop in the program is executed.
Syntax of While Loop
statement x
while (condition):
statement block
statement y
Condition An expression that evaluates to
True or False
The loop runs while the condition is True.
When the condition becomes False, the loop stops.
True
False
EXAMPLE
i=1 x = 10
while (i<=5): while (x>0):
print(i) print(x)
i += 1 x -= 2
OUTPUT OUTPUT
1 10
2 8
3 6
4 4
5 2
FOR LOOP
The For loop is usually known as a determinate or definite loop because
the programmer knows exactly how many times the loop will repeat.
The number of times the loop has to be executed can be determined
mathematically checking the logic of the loop.
The „for…in‟ statement is a looping statement used in python to iterate
over a sequence of objects.
Syntax of For Loop
for variable in sequence:
statement block
Variable Gets each value from the sequence one by
one
Sequence A collection [ range, list, string, etc….]
The code block inside the loop runs once for each item in
the sequence.
EXAMPLE
For loop using range()
for i in range(5): for x in range(1,6):
print(i,end = “ “) print(x,end=“\t“)
OUTPUT OUTPUT
0 1 2 3 4 1 2 3 4 5
For loop using range()
for y in range(2,10,2):
print(“NUMBER:”,y)
OUTPUT
NUMBER: 2
NUMBER: 4
NUMBER: 6
NUMBER: 8
For loop Through a List For loop Through a String
for letter in “python”:
fruits=[“Apple”,“Banana”,“Cherry”]
print (letter)
for x in fruits:
print(x)
OUTPUT
p
y
OUTPUT
t
Apple
h
Banana
Cherry o
n