Types of loops

There are two types of loops, namely:

  1. Definite: In this case, the code of block runs for a defined number of times. This is useful when the programmer exactly knows in how many counts the task will be executed or let's assume that he knows the number of elements inside the data structure. For example, the strength of a classroom.
  1. Indefinite: In this case, the code of block runs until the condition is true. This is useful where the count is unknown. For example, trying to figure out the number of times London appears in a literary article.

Before further delving into loops, let's try to understand the range() and xrange() functions in Python.

The range() function comes handy when you want to generate a list on-the-fly. Its syntax is as follows:

Syntax
range(start-value, end-value, difference between the values)

Here, range(10) will generate a list, which has elements starting from 0 upto 9. range(2,10) means the list will be generated starting from 2 and will have elements upto 9. The range(2,10,3) means the list will be generated starting with 2 and having a difference of 3 after each element.

Syntax
xrange(start-value, end-value, difference between the values)
The xrange() is quite similar to range() except that xrange() releases or frees the memory when not in use, whereas range() doesn't release the memory. 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.114.85