Loops in Python.

Looping

Looping is a continuous execution of a statement till the condition becomes false or till it set the end point. In python two types of looping supported , they are:

1. While Loop 2. For Loop

While loop

While loop is a conditional control statement. It will be executed based on the condition, if the condition is true it will execute the body of the loop till the condition become false

Syntax: while condition: Block Statement increment/decrement

Example:

Write a python program to add 10 consecutive number starting from 1 using while loop.

Syntax: count=0 sum=0 while count <=10: sum=sum+count count=count+1 print("sum of 10 consecutive numbers is :",sum) output: sum of 10 consecutive numbers is : 55

For loop

The for loop in python a slightly different from other programming language. The python for loop iterate through each value in a sequence,where squence of object hold multiple items of data store one after another.

Syntax: for variable_name in sequence: statement(s)

For loop in python which repeats a group of statement for specify number of times. The keyword 'for' and 'in' are essential key word to iterate the sequence of value.

Example:

Use for loop to print the numbers from 1 to 5.

Syntax: for a in range(1,5): print(a) print("End of sequence") output: 1 2 3 4 End of sequence

Range Function

This sis inbuilt function in python called Range function, which is used to generate list if integers. The range function has three parameters.

range(begin,end,step)

range(1,6,2)

[1,2,3,4,5,6] Output: 1,3,5

Nested Loop

The for and while loop statement can be nested in the same manner in which if statement are nested. Loop within the loop or when one loop is inserted within another loop then it is called Nested Loop.

Example:

for i in range(1,4,1): for j in range(1,4,1): print("i=",i,"j=",j,"i+j=",i+j)

output:

i= 1 j= 1 i+j= 2 i= 1 j= 2 i+j= 3 i= 1 j= 3 i+j= 4 i= 2 j= 1 i+j= 3 i= 2 j= 2 i+j= 4 i= 2 j= 3 i+j= 5 i= 3 j= 1 i+j= 4 i= 3 j= 2 i+j= 5 i= 3 j= 3 i+j= 6

Comments

Popular posts from this blog

Introduction to Python.

Decision Making Statement.