Read more
Iteration or Looping constructs
Programming in Python
In Python, programs can be written in two ways namely Interactive mode and Script mode. The Interactive mode allows us to write codes in Python command prompt (>>>) whereas in script mode programs can be written and stored as separate file with the extension .py and executed. Script mode is used to create and edit python source file.
Looping constructs:
Iteration or loop are used in situation when the user need to execute a block of code several of times or till the condition is satisfied. A loop statement allows to execute a statement or group of statements multiple times.
Python provides two types of looping constructs:
• while loop
• for loop
i. while loop
Syntax:
while<condition>:
statements block 1
[else:
statements block2]
Example:
Output:
NOTE!
That the control variable is i, which is initialized to 10, the condition is tested i<=15, if true value of i gets printed, then the control variable i gets updated as i=i+1 (this can also be written as i +=1 using shorthand assignment operator). When i becomes 16, the condition is tested False and this will terminate the loop
ii. for loop
for loop is the most comfortable loop. It is also an entry check loop. The condition is checked in the beginning and the body of the loop(statements-block 1) is executed if it is only True otherwise the loop is not executed.
Syntax:
for counter_variable in sequence:
statements-block 1
[else: # optional block
statements-block 2]
The counter_variable mentioned in the syntax is similar to the control variable that we used in the for loop of C++ and the sequence refers to the initial, final and increment value. Usually in Python, for loop uses the range() function in the sequence to specify the initial, final and increment values. range() generates a list of values starting from start till stop-1.
The syntax of range() is as follows:
range (start,stop,[step])
Where,
start – refers to the initial value
stop – refers to the final value
step – refers to increment value, this is optional part.

0 Reviews