Page 202 - Ai Book - 10
P. 202
In other words, this loop is used when you are sure about how many times a block of code will be executed. The
For loop is also known as definite loop. The basic syntax of for loop is as follows:
for<variable>in<sequence>:
Body of loop(Set of Statements)
Or
for<variable> in range( starting value, final value, step value)
You should remember that the initialisation statement is executed only once.
Let us write a program to print all the numbers defined in the sequence using for Foop.
Example:
In this example , the loop body gets executed ten times. The step by step process involved in the execution of
the for loop is as follows:
u Here, the first value of the sequence is assigned to the loop variable “num.”
u The body of the loop will be executed with the assigned value of the loop variable.
u After that, the loop variable is updated and the execution of loop body takes place on the basis of the new
updated value.
u The process of assigning and executing will continue until all the values in the sequence are exhausted.
While loop
The while loop is the simplest kind of loop among all the looping structures. While programming, sometimes
you are in a situation when the number of iterations is not known. In such a situation, you can use the concept
of while loop. In Python, while loop is used to execute a block of statements repeatedly until a given condition
is true. And when the condition becomes false, the program control passes to the statement after the body of
the loop.
The basic syntax of while loop in Python is as follows:
Initialization
While<condition>:
Body of loop/ Set of statements
stop value
Let us write a program to print the cube of first ten natural numbers using a while loop.
Example:
76
76