computer scince and engineeringpython

python While loop For loop range() function break and continue pass and return statements with examples in hindi by unitdiploma


While Loop

•The while loop is used to iterate over a block of code as long as the test expression (condition) is true.


  while condition:

  Body of while


  In while loop, test expression is checked first. The body of the loop is entered only if the condition evaluates to True. After one iteration, the test expression is checked again. This process continues until the condition evaluates to False.

•The body of the while loop is determined through indentation.

While loop with else

•We can also use an optional else block with while loop.

•The else part is executed if the condition in the while loop evaluates to False.

The for loop

•The for loop is used to iterate (repeat) over a sequence (list, tuple, string) or other iterable objects. Iterating over a sequence is called traversal.


  for val in sequence:

  Body of for

  (val is the variable that takes the value of the item inside the sequence on each iteration)

•Loop continues until we reach the last item in the sequence. The body of for loop is separated from the rest of the code using indentation.

for loop with else

•A for loop can have an optional else block. The else part is executed if the items in the sequence used in for loop exhausts.

•break statement can be used to stop the loop. In such case, the else part is ignored.

•Hence, a for loop’s else part runs if no break occurs.


Range () Function

•It is used to provide a sequence of numbers.

•range(n) gives numbers from 0 to n-1.

•For example, range(10) returns numbers from 0 to 9.

•For example, range(5, 10) returns numbers from 5 to 9.

• We can also define the start, stop and step size as range(start, stop, step size), step size defaults to 1 if not provided.

•Step size represents the increment in the value of the variable at each step.

Example 1


Example 2


Break & Continue statement

•break and continue statements can alter the flow of a normal loop.

  break statement:-

•The break statement terminates the loop containing it. Control of the program flows to the statement immediately after the body of the loop.

•If break statement is inside a nested loop (loop inside another loop), break will terminate the innermost loop.

•Syntax :-


The Continue Statement

•The continue statement is used to skip the rest of the code inside a loop for the current iteration only. Loop does not terminate but continues on with the next iter

Leave a Response