Skip to main content

Flow Control in Python

Flow Control in Python

The instructions in the code are executed, skipped or repeated based on flow control statements. These contain a set of conditions and a code block that is executed according to the conditions. These code blocks are identified by indentation, which is a unique feature of Python. Let us consider an if ... else statement.

if ... else

print 'Enter the password..'
pass=input()
if pass=='hari':

print 'Access granted ...'

else:

print 'Wrong password ...'

Many conditions are checked by the elif statement as

print 'Enter an integer...'
x=input()
if x<10:

print 'The number is less than 10 ...'

elif x<50:

print 'The number is less than 50'

elif x<100:

print 'The number is less than 100'

else:

print 'the number is greater than 100 ...'

for loop

for loop helps to do iterations in a fixed number of times and follows the following syntax

x=['tomato', 'cucumber', 'carrot', 'brinjal']
for i in x:

print i

The above code prints the elements of the list x. If you type i at the python terminal, it returns 'brinjal', indicating that the iteration is at the end.

while loop

While loop is meant for temporary and perpetual execution of iterative computation. The syntax follows

i=0
while i<100:

print i

i=i+1

The above code prints values from 0 to 99. A perpetual loop is attained by the following code

while True:

print "Hellow"
The infinite loop print the string Hellow forever. The execution is exited by pressing Cntrl+C. The boolean True may be replaced by the code
while 1:
as well. One may use the else statement within the while loop as shown below. i=0
while i<100:

print i

i=i+1
else:

exit

Comments