Tuesday, 21 July 2015

Loops in python !

The concept of loop is important for both programmer and hackers.
For programmer, you want to execute some code 50 times then instead of writing that code 50 times, you can do it  by writing that code only one time and repeat the execution 50 times with the help of loop.
Simply we can say, A loop allow us to execute a statement multiple times in our program.
For hacker, you want to crack Facebook password ;-) and you have a word-list of 100 passwords, you can do it by attempt manually. The other way of cracking password is by writing a loop program which simply attempt password 100 times.

The for loop : The for loop in python iterates over a sequence of objects i.e. go through each item in a sequence.for loop is used when you want to loop for a certain number of iterations. for loops start counting at a beginning value, test the value for some condition,execute the statement, and increment the value for the next iteration.

for i in range(1, 5):
         print i
else:
        print 'The for loop is over'



What we do here is supply it two numbers and range returns a sequence of numbers starting from the first number and up to the second number. For example, range(1,5) gives the sequence [1, 2, 3, 4]. By default, range takes a step count of 1. If we supply a third number to range, then that becomes the step count. For example, range(1,5,2) gives [1,3]. The for loop then iterates over this range - for i in range(1,5) is equivalent to for i in [1, 2, 3, 4]

Basically The range function has 3 forms:
range (x) generates x distinct values, from 0 to x-1, incrementing by 1.
range (x, y) generates y-x distinct values from x to y-1, incrementing by 1.
range (x, y, i) generates values from x to y-1, incrementing by i: [ x, x+i, x+2i, ... x+ki < y ]


>>> for o in range(1,36,2):
...     print o
...
1
3
5
7
9
11
13
15
17
19
21
23
25
27
29
31
33
35


                                        



Note : The Python for loop is radically different from the C/C++ for loop.
In C/C++, if you want to write for (int i = 0; i < 5; i++), then in Python you write just for i in range(0,5).


The while Statement :
if you use while loop in your program that means you want to execute a set of instructions in a loop while a condition is true. It tests the conditions before executing the loop body.
Let's understand with  a example :
number = 23
running = True
while running:
    guess = int(raw_input('Enter an integer : '))
    if guess == number:
        print 'Congratulations, you guessed it.'
    running = False # this causes the while loop to stop
    elif guess < number:
        print 'No, it is a little higher than that.'
    else:
        print 'No, it is a little lower than that.'
else:
print 'The while loop is over.'

print 'Done'


We move the raw_input and if statements to inside the while loop and set the variable running to True before the while loop.

More Iteration Control: break and continue
The break statement terminates a loop prematurely. This allows a complex condition to terminate a loop. A break statement is always found within if statements within the body of a for or while loop. A break statement is typically used when the terminating condition is too complex to write as an expression in the while clause of a loop. A break statement is also used when a for loop must be abandoned before the end of the sequence has been reached.

The continue statement skips the rest of the loop's suite. Like a break statement, a continue statements is always found within an if statement within a for or while loop. The continue statement is used instead of deeply nested else clauses.

Using the break statement
#!/usr/bin/python
# Filename: break.py
while True:
s = raw_input('Enter something : ')
if s == 'quit':
break
print 'Length of the string is', len(s)
print 'Done'


We are providing a special condition to stop the program by checking if the user input is 'quit'. We stop the program by breaking out of the loop and reach the end of the program.

The continue statement :
#!/usr/bin/python
# Filename: continue.py
while True:
s = raw_input('Enter something : ')
if s == 'quit':
break
if len(s) < 3:
continue
print 'Input is of sufficient length'

In this program, we accept input from the user, but we process them only if they are at least 3 characters long.
  
If you like this post or have any question, please feel free to comment!
Facebook Twitter Google+

 
Back To Top