Sunday, July 19, 2015

Python on the go - Revision of Repetitions

To repeat a certain task a fixed number of times, a for loop is used:-


 for x in range(5): 
    print x


To repeat a task until a certain condition is met, a while loop is used:-

def countdown(n):
    while n > 0:
          print n
          n = n-1
    print 'Blastoff!'


Another way a process can be repeated is recursion  which can be difficult to implement :-

def countdown(n):
    if n <= 0:
       print 'Blastoff!'
    else:
         print n
         countdown(n-1)


A recursion  usually consists of
(1)  a base case (when to stop)
(2) a work towards a base case
(3) a recursive call that calls itself


Updated - 27-7-2015

No comments:

Post a Comment