LOOPS PART -1

LOOPS:

While Loop:

A while loop will cause the loop statements to be executed until the loop condition is falsey. The following code will

execute the loop statements a total of 4 times.

i = 0

while i < 4:

    #loop statements

    i = i + 1

While the above loop can easily be translated into a more elegant for loop, while loops are useful for checking if

some condition has been met.

If the condition is always true the while loop will run forever (infinite loop) if it is not terminated by a break or return

statement or an exception.

while True:

    print "Infinite loop"

Example

Print i as long as i is less than 6:

i = 1
while i < 6:
  print(i)
  i += 1

OUTPUT:

1

2

3

4

5

 

 

For loops:

for loops iterate over a collection of items, such as list or dict, and run a block of code with each element from

the collection.

for i in [0, 1, 2, 3, 4]:

    print(i)

The above for loop iterates over a list of numbers.

Each iteration sets the value of i to the next element of the list. So first it will be 0, then 1, then 2, etc. The output

will be as follow:

0

1

2

3

4

range is a function that returns a series of numbers under an iterable form, thus it can be used in for loops:

for i in range(5):

    print(i)

gives the exact same result as the first for loop. Note that 5 is not printed as the range here is the first five

numbers counting from 0.

Iterating over lists:

To iterate through a list you can use for:

for x in ['one', 'two', 'three', 'four']:

    print(x)

This will print out the elements of the list:

one

two

three

four

The range function generates numbers which are also often used in a for loop.

for x in range(1, 6):

    print(x)

The result will be a special range sequence type in python >=3 and a list in python <=2. Both can be looped through

using the for loop.

1

2

3

4

5

If you want to loop though both the elements of a list and have an index for the elements as well, you can use

Python's enumerate function:

for index, item in enumerate(['one', 'two', 'three', 'four']):

    print(index, '::', item)

enumerate will generate tuples, which are unpacked into index (an integer) and item (the actual value from the list).

The above loop will print

(0, '::', 'one')

(1, '::', 'two')

(2, '::', 'three')

(3, '::', 'four')

Example:

Exit the loop when x is "banana", but this time the break comes before the print:

fruits = ["apple""banana""cherry"]
for x in fruits:
  if x == "banana":
    break
  print(x)

OUTPUT:

apple

 

 

 

 

 


Comments