Page 132 - Computer Genius Class 08
P. 132
for Loop
he for statement executes a simple or compound statement for a fixed number of times. he for
loop in Python is used to iterate over a sequence (list, tuple, string) or other iterable objects.
Syntax:
for x in range(n):
Statement1
Statement2
. . . . . . . . . .
l Here 'in' is the 'in operator' that checks whether the specified value is in the sequence or not. This
statement always outcomes to Boolean values i.e,. True or False.
l The body of ‘For’ loop is separated from the rest of the code using indentation.
l We can use for loop inside while loop and vice versa.
l We do have concept of for-else loop in Python.
Example 6: ‘for’ loop
# List of numbers
numbers = [ 6,5 ,3,8 ,4 ,2,5 ,4 ,11]
# V ariable to store the sum
sum = 0
# Iterate over the list
for val in numbers :
sum = sum+val
# Output: The sum is 4 8
print("The sum is", sum)
Output:
The sum is 48
Description:
In the above program, a list of numbers are created. sing Loop, sum of all items in the list have
been calculated.
While Loop
The while loop in Python is used to iterate over a block of code as long as the test expression
(condition) is true. We generally use this loop when we don’t know beforehand, the number of times
the loop will iterate.
Syntax:
while Condition1:
Statement1
Statement2
. . . . . . . . . .
130 Computer Genius-VIII

