LOOPING STATEMENTS
range() Function
Before, we move to iteration statements, let's know about range(). range() creates a sequence of values which can be used in repeating the given set of statements.
Syntax : range(lower limit, upper limit, step value) #all values should be integer
Example:
range(5,10) will produce sequence as 5,6,7,8,9
whereas range(5,10,2) will produce sequence as 5,7,9
and range(50,20,-10) will print 50, 40, 30
Note: Range() sequence begins with lower limit but goes till upper limit-1.
Iteration / Looping Statements
These statements are used to execute the set of instructions in a repeated order depending upon a particular condition. Sometimes we need to execute the block of code repeatedly till the condition evaluates to true, in that case we use loops. Python offers two types of loops for and while:
-
for loop- it is a counting loop, which is going to repeat certain number of times.
Syntax:
for in sequence:
Body of loop i.e Statements to be repeated
Here sequence can be given using range(), a string, a list or any valid sequence allowed in python.
2. while loop - It is a conditional loop, which will keep repeating till the condition evaluates to True.
Syntax:
while test condition:
body of loop
For Loop
Code
Output
While Loop
Code
Output
Try It Yourself
Problem Statement 1 - Input a number and print its table.
Problem Statement 2 - Input integer n, if n is an even number then display square of all natural numbers till n. And if, n is an odd number then display all numbers till n.
For example: Suppose n=7 then output should be 1,2,3,4,5,6,7
and if n=6 then output should be 1,4,9,16,25,36.