Informatics Practices · Ch 3 — Brief Overview of Python
For Loop
For Loop
Programs frequently need to do the same thing many times over. Think of a program that has to display the attendance of every student of a class: the print statement must execute once for each student. Writing it out separately for every student would be absurd — instead, the program should repeat it. In programming, this kind of repetition is called looping or iteration, and in Python it is done using the for statement.
What the for statement does
The for statement is used to iterate over a range of values or a sequence. The loop body executes once for each item in that range. The values iterated over can be numeric, string, list or tuple. When all the items in the range are exhausted, the statements within the loop stop executing, and the Python interpreter moves on to the statements immediately following the for loop.
One planning point: while using a for loop, we should know in advance the number of times the loop will execute — the for loop suits repetition whose count is fixed by the items being traversed.
Syntax
for <control-variable> in <sequence/items in range>:
<statements inside body of the loop>
The control variable takes each item of the sequence in turn, and for each such item the indented body runs once.
A worked program
Program 3-4 prints the even numbers in a given sequence:
#Program 3-4
#Print even numbers in the given sequence
numbers = [1,2,3,4,5,6,7,8,9,10]
for num in numbers:
if (num % 2) == 0:
print(num,'is an even Number')
Output:
2 is an even Number
4 is an even Number
6 is an even Number
8 is an even Number
10 is an even Number
``` …