Page 254 - AI Computer 10
P. 254
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
update value
Example: Program to print the cubes of first ten natural numbers using a while loop.
PYTHON INDENTATION
Most of the programming languages provide indentation for better code formatting but don’t enforce to have it.
However, in Python, it is mandatory to obey the indentation rules. Typically, we indent each line by four spaces
(or by the same amount) in a block of code.
Python uses the colon symbol (:) and indentation for showing where blocks of code begin and end. All blocks
start with a colon and then contain the indented lines below it.
if a>b: # if block starts here
print(a) # This is part of the if block
else: # else must be at the same level as if
print(b) # This line is part of the else block
Kno
Knowledge Botwledge Bot
Any statement without indentation will raise an error in Python.
120
120