Skip to content

Condition and Iteration

Condition

Conditionals - mostly in the form of if statements. are one of the essential features of a programming language and Python is no exception. You will find hardly any programming language without an if statement.1 There is hardly a way to program without having branches in the flow of code. At least, if the code has to solve some useful problem.

We will read in three float numbers in the following program and will print out the largest value:

x = float(input("1st Number: "))
y = float(input("2nd Number: "))
z = float(input("3rd Number: "))
if x > y and x > z:
    maximum = x
elif y > x and y > z:
    maximum = y
else:
    maximum = z

print("The maximal value is: " + str(maximum))


Iteration

In general, statements are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. There may be a situation when you need to execute a block of code several number of times.

Programming languages provide various control structures that allow for more complicated execution paths.

A loop statement allows us to execute a statement or group of statements multiple times.

Python programming language provides following types of loops to handle looping requirements.

  • for loop : Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable.
  • while loop : Repeats a statement or group of statements while a given condition is TRUE. It tests the condition before executing the loop body.
  • nested loops : You can use one or more loop inside any another while, for or do..while loop.


for loop

for letter in 'Python': # First Example
    print('Current Letter :', letter)

fruits = ['banana', 'apple', 'mango']
for fruit in fruits: # Second Example
    print('Current fruit :', fruit)

fruits = ['banana', 'apple', 'mango']
for index in range(len(fruits)):
    print('Current fruit :', fruits[index])

Current fruit : banana
Current fruit : apple
Current fruit : mango


for num in range(10,20): #to iterate between 10 to 20
    for i in range(2,num): #to iterate on the factors of the number
        if num%i == 0: #to determine the first factor
            j=num/i #to calculate the second factor
            print('%d equals %d * %d' % (num,i,j))
            break #to move to the next number, the #first FOR
        else: # else part of the loop
            print(num, 'is a prime number')

10 equals 2 * 5
11 is a prime number
12 equals 2 * 6
13 is a prime number
14 equals 2 * 7
15 equals 3 * 5
16 equals 2 * 8
17 is a prime number
18 equals 2 * 9
19 is a prime number


while loop

count = 0
while (count < 9):
    print('The count is:', count)
    count = count + 1

Infinite Loop

var = 1
while var == 1 : # This constructs an infinite loop
    num = raw_input("Enter a number :")
    print("You entered: ", num)

count = 0
while count < 5:
    print(count, " is less than 5")
    count = count + 1
else:
    print(count, " is not less than 5")

Single Statement Suites

flag = 1
while (flag): print 'Given flag is really true!'
    print("Good bye!")

nested loops

i = 2
while(i < 100):
    j = 2
    while(j <= (i/j)):
        if not(i%j): break
            j = j + 1
            if (j > i/j) : print i, " is prime"
            i = i + 1


Control Statement

Python supports the following control statements:

  • break statement : Terminates the loop statement and transfers execution to the statement immediately following the loop.
  • continue statement : Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.
  • pass statement : The pass statement in Python is used when a statement is required syntactically but you do not want any command or code to execute.


break statement

It terminates the current loop and resumes execution at the next statement, just like the traditional break statement in C.

The most common use for break is when some external condition is triggered requiring a hasty exit from a loop. The break statement can be used in both while and for loops.

If you are using nested loops, the break statement stops the execution of the innermost loop and start executing the next line of code after the block.

for letter in 'Python': # First Example
if letter == 'h':
    break
    print 'Current Letter :', letter

var = 10 # Second Example
while var > 0:
    print('Current variable value :', var)
    var = var -1
    if var == 5:
        break


continue statement

It returns the control to the beginning of the while loop.. The continue statement rejects all the remaining statements in the current iteration of the loop and moves the control back to the top of the loop.

The continue statement can be used in both while and for loops.

for letter in 'Python': # First Example
if letter == 'h':
    continue
    print('Current Letter :', letter)


var = 10 # Second Example
while var > 0:
    var = var -1
    if var == 5:
        continue
        print('Current variable value :', var)

Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : o
Current Letter : n
Current variable value : 9
Current variable value : 8
Current variable value : 7
Current variable value : 6
Current variable value : 4
Current variable value : 3
Current variable value : 2
Current variable value : 1
Current variable value : 0


pass statement

It is used when a statement is required syntactically but you do not want any command or code to execute.

The pass statement is a null operation; nothing happens when it executes. The pass is also useful in places where your code will eventually go, but has not been written yet.

for letter in 'Python':
    if letter == 'h':
        pass
    print 'This is pass block'
    print 'Current Letter :', letter

Current Letter : P
Current Letter : y
Current Letter : t
This is pass block
Current Letter : h
Current Letter : o
Current Letter : n