All Topics

Looping



Looping is done in the same way as in other languages.

Loops can execute a block of code as long as a specified condition is reached.
Loops are handy because they save time, reduce errors, and they make code more readable.


While Loop:-

The while loop loops through a block of code as long as a specified condition is true
Example:-


Break Statement:-


Break statement makes the control to exit the loop at i=3.

There is no do-while supported by python.

Continue Statement:-


Continues the next iteration when i=3;

With the else statement we can run a block of code once when the condition no longer is true


For Loop:-

A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).
This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages.



Similarly we can loop through a string or any other iterable.
The for loop does not require an indexing variable to set beforehand.

The range() Function
To loop through a set of code a specified number of times, we can use the range() function.
The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number.


In the above example, it is equivalent to 'for(i=2;i<30;i+=3)' in other languages.

Rest all things like break, continue, pass, else in looping, nested loops are similar to while loops



Hello