Tutorials

0


While Statement:

The while statement allows you to execute a block of statements till the condition is true.while statement is an example of looping statement. A while statement can have an optional else clause.
Example:
number = 1
running = True

while running:
 print (number)
 number = number + 1
 if number > 10:
  running = False    
    
else:
 print ('The while loop is over.')
 # Do anything else you want to do here

print ('Done')
Output:
1
2
3
4
5
6
7
8
9
10
The while loop is over.
Done

How It Works

In this program, we are printing a sequence of numbers from 1 to 10. This aptly demonstrates the use of the while statement. 
First, we check if the variable 'running' is True and then proceed to execute the corresponding while-block. After this block is executed, the condition is again checked, which in this case is the 'running' variable. If it is true, we execute the while-block again, else we continue to execute the optional else-block and then continue to the next statement. 
The else block is executed when the while loop condition becomes False. 
The True and False are called Boolean types and you can consider them to be equivalent to the value 1 and 0 respectively.

The for..in loop

This for..in statement is an another looping statement.It iterates over a sequence of objects. This is used when you want to specify a range of objects.
Example:
for i in range(1, 6):
    print (i)
else:
    print ('The program ends here')
Output:
1
2
3
4
5
The program ends here

How It Works

When we run this program, it will print a sequence of number. range() is a built-in function of Python. 
In range() we supply two numbers and range will return a sequence of numbers starting from the first number and up to the second number. In the above program range(1,6) gives the sequence [1,2,3,4,5]. By default range takes a step count of 1. If we supply third number then that becomes the step count.In the above code if we had written range(1,6,2) will give [1,3,5]. range() generates the sequence of numbers but will generate only one number at a time. Remember that range extends up to the second number i.e it does not include the second number.

Post a Comment

 
Top