Conditional and Looping Constructs

Introduction:

In the programs we have seen till now, there has always been a series of statements faithfully executed by Python in exact top-down order. What if you wanted to change the flow of how it works? For example, you want the program to take some decisions and do different things depending on different situations, such as printing ‘Good Morning’ or ‘Good Evening’ depending on the time of the day?

Similarly while writing program(s), we almost always need the ability to check the condition and then change the course of program.

Types of Statements in Python:

Statement is the instructions given to the computer to perform any kind of action.

Three type of Statement:

a) Empty Statement: As the name suggested, this statement does not contain anything. In python an empty statement is pass statement.

b) Simple Statement (Single Statement): Simple statements are comprised within a single logical line. Several simple statements may occur on a single line separated by semicolons. For example,

                       A=10

                       B=int(input(“Enter Number”))

c) Compound Statement: Compound statements contain (groups of) other statements; they affect or control the execution of those other statements in some way.

For example:

i) def sum ( ):

           a=10           #Function sum ( ) contains multiple statements or compound statement.

            b=20

s=a+b

print (“The Sum is :”,s)

sum( )                                                  #calling of sum function

ii) a=int(input(“Enter Number: ”)

if a>0:

            print(“Number is positive”)

else

            print(“Number is negative”)

Statement Flow of Control:

The flow of activity through the program code is called the flow of control. Usually the flow of control is sequential, that is, the statements are executed in the order in which they appear in the code. In computer programming, there are three main types of control flows that occur. These are:

  • Sequential: The statements execute from top to bottom sequentially.

sequential

  • Conditional or selection: Out of two instructions, only one will be executed successfully depending on the condition. Because the condition produces a result as either True or False.

comp

  • Repetition or loop: In which the instruction(s) are repeated over a whole list whenever the condition is True.

loop

Program Logic Development:

Algorithm, flowchart and pseudo code are three types of tools to explain the process of a program.

Algorithm: An algorithm is a precise specification of a sequence of instructions to be carried out in order to solve a given problem.

  • An Algorithm is a technique to solve a given problem systematically.
  • An Algorithm is a step-by-step approach to solve a given problem in finite number of steps.
  • It takes a set of input values and processes it and gives the output.
  • Each instruction tells what task is to be performed.

Properties (characteristics) of an Algorithm:

  • It should be simple.
  • It may accept zero or more inputs.
  • It should be precise with no ambiguity.
  • It should have finite number of steps.
  • It should produce at least one output.

Flowchart: A flowchart is the graphical or pictorial representation of an algorithm with the help of different symbols, shapes and arrows in order to demonstrate a process or a program. With algorithms, we can easily understand a program. The main purpose of a flowchart is to analyze different processes. Several standard graphics are applied in a flowchart:

  • A flowchart depicts pictorially the sequence in which instructions are carried out in an algorithm.
  • A flowchart is a schematic representation of an algorithm or a stepwise process, showing the steps of boxes of various kinds and their order by connecting these with arrows.
  • Flowcharts are used not only as aids in developing algorithms but also to document algorithms.
  • Flowcharts are used in designing or documenting a process or program.

Flowcharts Symbols:

Symbol Name Function
1 Start and Stop

OR  Terminal

Indicates the starting or ending of the program, process, or interrupt program
2 Process Indicates any type of internal operation inside the Processor or Memory
3 input/output Used for any Input / Output (I/O) operation. Indicates that the computer is to obtain data or output results
4 Decision

 

Used to ask a question that can be answered in a binary format (Yes/No, True/False)
5 Connector

 

Allows the flowchart to be drawn without intersecting lines or without a reverse flow.
6 Predefined Process Used to invoke a subroutine or an interrupt program.
7 Flow Lines Shows direction of flow. It indicates the flow of data from one geometrical signal to another.

For Example: Write Algorithm to check whether entered number is even or odd and also draw the flowchart for the same.

Algorithm:                                                                                        Flowchart:

Step 1 : Start                                                                         flow1

Step 2 : Input Number

Step 3 : rem=number mod 2

Step 4 : if rem=0 then

              Display “Even Number”

           else

               Display “Odd Number”

           endif

Step 5 : Stop

Pseudocode: Pseudocode is an artificial and informal language that helps programmers develop algorithms. Pseudocode is a “text-based” detail (algorithmic) design tool.

Examples 1:

If student’s grade is greater than or equal to 60

Print “passed”

else

Print “failed”

Example 2:

  1. Initialize total to zero
  2. Initialize counter to zero
  3. Input the first grade
  4. while the user has not as yet entered the sentinel
  5. add this grade into the running total
  6. add one to the grade counter
  7. input the next grade (possibly the sentinel)
  8. if the counter is not equal to zero
  9. set the average to the total divided by the counter
  10. print the average
  11. else
  12. print ‘no grades were entered’

Example 3: Write a pseudo code and Python program code to calculate the sales tax of an item.

Solution Pseudo Code:

  1. Input Price of item
  2. Input Sales tax rate
  3. Calculate Sales tax = price of item X Sales tax rate/100
  4. Final price = Price of item plus Sales tax
  5. Display Final price
  6. Stop

Python Code:

# 1. Input Price of item

Price = float(input(“Enter item’s price: “))

# 2. Input Sales tax rate

Tax_rate = float(input(“Enter the sales tax rate, in decimal: “))

# 3. Sales tax = Price of item times Sales tax rate

Tax = Price * Tax_rate/100

#4. Final price = Price of item plus Sales tax

Final_price = Price + Tax # 5. Display Final price

print (“The final price is: %7.2F” % Final_price)

 Conditional Control:

Conditional control statements are also called branching or selection statements that execute one group of instructions depending on the outcome of a decision. In this category, Python programming language provides following types of decision making statements as

Statement Description
if statements An if statement consists of a Boolean expression followed by one or more statements.
If…….else statement An-if statement can be followed by an optional else statement, which executes\when the Boolean expression is false.
Nested if statement You can use one if or else if statement inside another if or else if statement(s).

if Selection Structure:-

Selection structures choose among alternative courses of action. For example, suppose that the passing grade on an examination is 60. Then the pseudo code statement

If student’s grade is greater than or equal to 60

Print “Passed”

Determines whether the condition “student’s grade is greater than or equal to 60” is true or false. If the condition is true, then “Passed” is printed.

The general Python syntax for a simple if statement is

if condition:                                                                                  

                     indented Statement Block                            Flow diagram of if condition

 

if1

If the condition is true, then do the indented statements. If the condition is not true, then skip the indented statements.

Example 1:

if balance < 0:

transfer = -balance

backupAccount = backupAccount – transfer # take enough from the backup acct.

balance = balance + transfer

In the examples above the choice is between doing something (if the condition is True) or nothing (if the condition is False). Often there is a choice of two possibilities, only one of which will be done, depending on the truth of a condition.

Example 2: Write a program to take a value from the user and print the square of it, unless it is more than 120. The message I cannot square numbers that appear if the user types too large a number.

Solution:

num = int(input(“What number do you want to see the square of? “))

 if num < 120:

                        square = num * num; print (“The square of %d is %d “ % (num, square))

 if num >= 120:

                          print (“*** Square is not allowed for numbers over 120 ***” )

print (“Run this program again and try a smaller value. “)

print (“Thank you for requesting squares.”)

if – else Statements:-

If the conditional statement under if is evaluated to be true then the statement under if block will be executed otherwise the statements under else block would be executed.

The general Python syntax is                                                             flow diagram                                                    ifelse

if condition :

         indentedStatementBlockForTrueCondition

else:

         indentedStatementBlockForFalseCondition

These statement blocks can have any number of statements, and can include about any kind of statement.

For Example:

x = 0

y = 3

x += y

if  x > y :

                print(”x is greater”)

else :

          print(”we are in else part because x and y both became equal”)

Output:

>>>  we are in else part because x and y both became equal

The above code produces an output as ―”we are in else part because x and y both became equal” because the conditional statement under if evaluates as false as x is not greater than y, it is same as that of y.

Example: Write a program to find greatest among 3 numbers

ALGORITHM:                                                                            FLOWCHART:

Step1:start                                                                                                                 flow2.png

Step2:input a,b,c

Step3:if(a>b) &&(a>c)

Step4: display a is grater

Step 5:else

Step6:if(b>c)

Step7: display b is grater

Step 8:else

Step: display c is grater

Step10:stop

 

Program:

a=b=c=0

a=float(input(“Enter value of a: “))

b=float(input(“Enter value of b: “))

c=float(input(“Enter value of c: “))

if a>b and a>c:

        print(“%.1f is greatest of  %.1f  %.1f  %.1f”%(a,a,b,c))

else:

        if b>c:

            print(“%.1f is greatest of  %.1f  %.1f  %.1f”%(b,a,b,c))

        else:

            print(“%.1f is greatest of  %.1f  %.1f  %.1f”%(c,a,b,c))

5) Result:

Enter the values of a: 10

Enter the values of b: 30

Enter the values of c: 20

30.0 is greatest of 10.0  30.0 20.0

Example: The program takes a number and checks whether it is positive or negative.

Problem Solution

  1. Take the value of the integer and store in a variable.
  2. Use an if statement to determine whether the number is positive or negative.
  3. Exit.

Program/Source Code

n=int(input(“Enter number: “))

if n>0 :

    print(“Number is positive”)

else:

    print(“Number is negative”)

Program Explanation

  1. User must first enter the value and store it in a variable.
  2. Use an if statement to make a decision.
  3. If the value of the number is greater than 0, “Number is positive” is printed.
  4. If the value of the number if lesser than 0, ”Number is negative” is negative.

Run time Test Cases

Case 1:

Enter number: 45

Number is positive

Case 2:

Enter number: -30

Number is negative

 Multiple Tests and if – elif Statements (Ladder if – else):-

The most elaborate syntax for an if statement, if- elif-…-else is indicated in general below:

if condition1 :                                                                            

indentedStatementBlockForTrueCondition1

elif condition2 :

indentedStatementBlockForFirstTrueCondition2

elif condition3 :

indentedStatementBlockForFirstTrueCondition3

elif condition4 :

indentedStatementBlockForFirstTrueCondition4

else:

indentedStatementBlockForEachConditionFalse 

flow3

In the above syntax there are ladder of multiple conditions presented by each if, all of these conditions are mutually exclusive that is only one of them would get satisfied and all the conditions below it would not be evaluated and is discarded.

Say suppose if condition-3 gets satisfy i.e. it yields a true value for the condition, the statement under the block of third if gets executed and all other n number of if conditions below it would be discarded.

If none of the n if conditions gets satisfied then the last else part always gets executed. It is not compulsory to add an else at the last of the ladder.

Example 1: Write a program to enter a number and check if the number is zero, positive or negative using if-else-if ladder.

SOLUTION:

N = int(input(“Enter any number: “))

if (N<=-1):

           print(“N is a negative number having value “, N)

elif (N ==0):

            print(“N is a zero number having value “)

elif (N > O):

            print(“N is a positive number having value N”)

Example 2: Program that reads two numbers and an arithmetic operator and displays the computed result.

Algorithm:

Step 1: Start

Step 2: Read x and y values

Step 3: Read option + or – or * or / or %

Step 4: If option is ‘+’ res = x + y

Step 5: If option is ‘-’ res = x – y

Step 6: If option is ‘*’ res = x * y

Step 7: If option is ‘/’ res = x / y

Step 8: If option is ‘%’ res = x % y

Step 9: If option does not match with + or – or * or / or %

           Print select option +, -, *, /, /, % only

Step 10: Print x, option, y, res values

Step 11: Stop

Solution:

Num1 = float ( input( “Enter first number :” ) )

Num2 = float ( input( “Enter second number :” ) )

op = input( “Enter operator [ + – * / % ] :” )

result = 0

if op ==’+’ :

          result = num1 + num2

elif op ==’-‘:

           result = num1 – num2

elif op == ‘*’ :

           result = num1* num2

elif op ==’/’ :

           result = num1 / num2

elif op ==’ %’ :

           result = num1% num2

else :

           print (“Invalid operator! !”)

print (num1, op, num2 , ‘=’, result)

Example 3: This program allows the user to enter any year and then it will check whether the user entered year is Leap year or not using the python elif.

year = int(input(“Please Enter the Year Number you wish: “))
if (year%400 == 0):
          print(“%d is a Leap Year” %year)
elif (year%100 == 0):
          print(“%d is Not the Leap Year” %year)
elif (year%4 == 0):
          print(“%d is a Leap Year” %year)
else:
          print(“%d is Not the Leap Year” %year)

 

NESTED IF STATEMENTS:-

There may be a situation when you want to check for another condition after a condition resolves to true. In such a situation, you can use the nested if construct.

In a nested if construct, you can have an if…elif…else construct inside another if…elif…else construct.

The syntax of the nested if…elif…else construct may be:nestedif else

If the test expression 1 present in the above structure is true then compiler will go to nested if statement

  • If the test expression 2 is True then Test expression 2 True statements will be executed
  • Else (it means test expression 2 is false) Test expression 2 false statements will be executed

If the test expression 1 is false then Test expression 3 will be test, if expression 3 will be false then else will be executed.

Example 1:  for Python Nested If Statement

age = int(input(” Please Enter Your Age Here:  “))
if age < 18:
    print(” You are Minor “)
    print(” You are not Eligible to Work “)
else:
    if age >= 18 and age <= 60:
        print(” You are Eligible to Work “)
        print(” Please fill in your details and apply”)
    else:
        print(” You are too old to work as per the Government rules”)
        print(” Please Collect your pension!”)

 

Example 2: Program that reads three numbers (integers) and prints them in ascending order.

Solution:

x = int(input( “Enter first number :” ))
y = int (input ( “Enter second number :” ))
z = int(input( “Enter third number :” ))
min = mid = max = None
if x < y and x < z :
if y < z :
min, mid, max = x, y, z
else :
min, mid, max = x, z, y
elif y < x and y < z :
if x < z :
min, mid, max = y, x, z
else :
min, mid, max = y, z, x
else :
if x < y :
min, mid, max = z, x, y
else:
min, mid, max = z, y, x
print (“Numbers in ascending order :”, min, mid, max)

Compound Boolean Expressions:-

The new Python syntax is for the operator and:

condition1 and condition2

It is true if both of the conditions are true. It is false if at least one of the conditions is false.

To be eligible to graduate from Jamia Millia Islamia, you must have 128 units of credit and a GPA of at least 2.0. This translates directly into Python as a compound condition:

Example:

Write an application to calculate your class grade and grade-point for a subject mark  as per the following table:

Marks Range Grade Grade Pint
91-100 A1 10.0
81-90 A2 9.0
71-80 B1 8.0
61-70 B2 7.0
51-60 C1 6.0
41-50 C2 5.0
33-40 D 4.0
21-32 E1 0.0
00-20 E2 0.0

Solution: 

# Calculating grade for a subject

Mark = input(“Enter a subject mark: “)
Grade, GrPoint = “Non”, 0.0
if Mark >= 91 and Mark <= 100:
Grade = “Al”
GrPoint = 10.0
elif Mark >= 81 and Mark < 91:
Grade = “A2”
GrPoint = 9.0
elif Mark >= 71 and Mark < 81:
Grade = “B1″
GrPoint = 8.0
elif Mark >= 61 and Mark < 71:
Grade =”B2”
GrPoint = 7.0
elif Mark >= 51 and Mark < 61:
Grade = “C1”
GrPoint = 6.0
elif Mark 41 and Mark < 51:
Grade = “C2”
GrPoint = 5.0
elif Mark >= 33 and Mark < 41:
Grade = “D”
GrPoint = 4.0
elif Mark >= 21 and Mark < 33:
Grade =”E1″
GrPoint = 0.0
elif Mark >= O and Mark < 21:
Grade = “E2”
GrPoint = 0.0
print (“The grade is: “, Grade)
print (“Grade point is: “, GrPoint)

Looping / Iteration Constructs:-

The iteration constructs means repetition of a set of statements depending upon a condition test. Till the time a condition is true (or False depending upon the loop), a set of statements are repeated again and again. As soon the condition becomes False (or True), the repetition stops. The iteration constructs is also called looping constructs.

Two types of looping construct in Python

  1. while loopwhile loop flowchart
  2. for loop

while loop:-

The while statement allows you to repeatedly execute a block of statements as long as a condition is true. A while statement is an example of what is called a looping statement. A while statement can have an optional else clause.

 

Its syntax is:

while (condition) :                # condition is Boolean expression returning True or False

                STATEMENT’s BLOCK 1

else:                                                   # optional part of while

STATEMENT’s BLOCK 2

Here,

  • We can see that while looks like if statement. The while statement star with keyword while followed by Boolean condition followed by colon (:).
  • A while loop consists of the keyword while.
  • It contains a Expression/Condition called Boolean expression which produce either a true of false result depending on the counter control.
  • The Expression/Condition controlled by a counter control variable which produces a true result for a number of times.
  • When the Expression/Condition becomes False, program control passes to the line immediately following the loop.
  • The Program statements are called the body of the loop, which can be a single statement or a block of statements and indented inside while and else loop.
  • The else statement is optional and executed the Program statements when the condition becomes False.
  • If you do not mention the else statement and when the condition is tested and the result is False, the loop body will be skipped and the first statement after the while loop will be executed.
  • To exit from the loop you can use break statement at any place in between the loop. Details about break statement will be discussed latter in the chapter.

NOTE:The statement(s) in BLOCK 1 keeps on executing till condition in while remains True; once the condition becomes False and if the else clause is written in while, and then else will get executed. While loop may not execute even once, if the condition evaluates to false, initially, as the condition is tested before entering the loop.

Some examples of while loop are:

Example 1:

num = 5

while num != O:

print (num)

num = num — 1

this loop prints a num starting from 5 and going down to 1, until the num becomes 0 which is the terminating condition of the loop.

Example 2:

n = int(input(“Enter value of n: “))

while (i < n):                       # This loop counts i up to n.

print (i)

i = i + 1

Here, the while loop is controlled by a loop counter variable i. The loop will only terminated when i equal to n or greater than n.

Example 3:

num = 5

while (num):

print (num)

num – = 1

Here, the while (num) is same as saying while (num != 0). So, this example is same as:

num = 5

while (num !=0):

print (num)

num – = 1

Example 4:

i = 4                            #line no. 1

while (i < 9):              #line no. 2

    print(i)                    #line no. 3

    i = i+2                       #line no. 4

The output is

4

6

8

The sequence order is important. The variable i is increased before it is printed, so the first number printed is 6. Another common error is to assume that 10 will not be printed, since 10 is past 9, but the test that may stop the loop is not made in the middle of the loop. Once the body of the loop is started, it continues to the end, even when i becomes 10.

line i comment
1 4
2 4 < 9 is true, do loop
3 6 4+2=6
4 print 6
2 6 < 9 is true, do loop
3 8 6+2= 8
4 print 8
2 8 < 9 is true, do loop
3 10 8+2=10
4 12 print 10
2 10 < 9 is false, skip loop

 SOLVED EXAMPLES:

Example 1: Write a program with a flowchart and Python program to print the numbers from 1 to 10 using while loop.
SOLUTION :
# Program to print numbers from 1 to 10      while ex1
count = 1
while (count < 11):
print (‘The count is: l, count)
count = count + 1
print (“Thank you!”)

which will produce the following output:

The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
The count is: 9
The count is: 10
Thank you!
Here, the block consisting of the print and increment statements, is executed repeatedly until the count is less than 11. With each iteration, the current value of the index count is displayed and then increased by 1.

Example 2:  Write a flowchart and program to find the sum of first 10 natural numbers. That is :
1+2+3+4+5+6+7+8+9+10=55
Also, explain the program code execution style.
SOLUTION : while ex2.jpg
Python Code:
# Program to find sum of first 10 natural numbers.
ctr = 1
SumN = 0
while (ctr <= 10):
SumN = SumN + ctr
ctr + = 1
print (“Sum of first 10 natural numbers is:”, SumN)

Here,
• The ctr variable in the above code is 1.
• The low value is 1 and the high value is 10.
• The body of the loop consists of a single statement to add ctr value with SumN.
• The effect of this code is to compute and then output the SumN of the numbers from 1 to 10.

Example 3: Draw a flowchart and write a Python program to find the factorial of an input number.
i.e., factorial of 5 x 4 x 3 x 2 x 1 = 120
SOLUTION : while ex3.jpg
# Program to find the factorial of a number
Fact = ctr = 1
N = int(input(“Enter any number to find factorial)
while (ctr <= N):
Fact = Fact * ctr
ctr+=l
print (“The factorial of %d is 0/0.2f”% (N, Fact))

  

Example 4: Write a program to find the Fibonacci Series upto 10 terms.

Note: A Fibonacci series is: O, 1, 1, 2, 3, 5, 8, 13,21,34                                                   

Solution:

# Program to find the Fibonacci Series of numbers till 20.

f1,f2=0,1
n=0
print(f1,f2,end=” “)
while(n<8):
f3=f1+f2
f1=f2
f2=f3
n+=1
print (f2, end=” “)

Example 5: Write a program that accepts two numbers and prints their highest common factor.
SOLUTION :
# Program to find HCF of two numbers
x = int(input(“Enter first number: “))
y = int(input(“Enter second number: “))
if x > y:
x1= x; y1 = Y
else:
y1= x; x1 = Y
rem = 1
hcf = 0
while (rem!=O):
hcf = y1
rem = x1 % y1
quotient = x1 / y1
y1 = rem
print (“HCF of %d and %d is: %(x, y, hcf))

The output is:
Enter first number: 10
Enter second number: 5
HCF of 10 and 5 is: 5

The else Statement used with while Loop: 

Python supports to have an else statement associated with while loop. If the else statement is used with a while loop, the else statement is executed when the condition becomes False.
The following example illustrates the combination of an else statement with a while statement that prints a number as long as it is less than 5 otherwise else statement gets executed.

# Program to demonstrate else statement with while loop

ctr = 5
while (ctr < 10):
print (“%d is less than 10” % ctr)
ctr = ctr + 1
else:
print (“%d is not less than 10” % ctr)

When the above code is executed, it produces the following results:
5 is less than 10
6 is less than 10
7 is less than 10
8 is less than 10
9 is less than 10
10 is not less than 10

The range( ) Function:

Before start with for loop, let us discuss the range (  ) function .

You can generate a sequence of numbers using range ( ) function. This function does not store all the values in memory, it would be inefficient. It just remembers the start, stop, step size and generates the next number on the go. It is most often used in for loops. The arguments must be plain integers. The general format of range ( ) function is:

Syntax is :

range ( [start,] stop[, step])

Here,

  • start and step are optional.
  • start is the staring number of range. If the start argument is omitted, it defaults to 0.
  • stop is the last number of range where the range will end. That is the exact end position is: stop -1.
  • step is the increment.

Examples :
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> range(1, 11)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

>>> range(0, 30, 5)
[0, 5, 10, 15, 20, 25]

>>> range(0, 10, 3)
[0, 3, 6, 9]

>>> range(0, -10, -1)
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]

range(x) is the simplest way to loop n times in Python is: range(x) returns a list whose items are consecutive integers from 0 (included) up to x (excluded).
for i in range(n):
statement(s)
Example:
x=10
for i in range(x):                           #1 value pass to range()
print (i),

output:
0 1 2 3 4 5 6 7 8 9

range(x,y):can take two numbers and tells Python to count from the one to the other. By default, it does this in increments of 1. range(x, y) returns a list whose items are consecutive integers from x(included) up to y (excluded). The result is the empty list if x is greater than or equal to y.
for i in range(x, y):
statement(s)
Example:
x=11
y=21
for i in range(x,y):                 #2 value pass to range()
print i,

Output:
11 12 13 14 15 16 17 18 19 20
We can also give 3 values to the range(), x the start point, y the end point and step is the number by which series will increase or decrease.

range(x, y, step): It returns a list of integers from x (included) up to y (excluded), such that the difference between each two continuous items in the list is step. range() returns the empty list when x is greater than or equal to y and step is greater than 0, or when x is less than or equal to y and step is less than 0. When step equals 0, range raises an exception.
for i in range(x, y, step):
statement(s)
Example:
x=11
y=21
step=3
for i in range(x,y,step):                     #3 value pass to range( )
print i,

Output:
11 14 17 20

for loop:- 

The for..in statement is another looping statement which iterates over a any sequence of objects i.e. go through each item in a sequence such as a list or a string. New Doc 2018-08-25 22.08.38.jpg

Its Syntax is:
for <variable> in <sequence>:
           STATEMENT BLOCK 1
else:
           STATEMENT BLOCK 2                           # optional block

  • The body of the loop can be any sequence of Python statements.
  • If a sequence contains an expression list, it is evaluated first, Then, the first item in the sequence is assigned to the iterating variable iterating_var.
  • The variable iterating_var after the keyword for is called the loop index. Figure 6.2 Flowchart of a for loop.
  • Next, the statements block is executed. Each item in the list is assigned to iterating_var, and the statements(s) block is executed until the entire sequence is exhausted.
  • The else statement is executed when the loop has exhausted iterating the list.
  • Let us take some examples.

Some Results using range function in for loop:

Statement Output Loop Description
for i in range(5, 10):

print (i, end=” “)

5 6 7 8 9 5 is the start, 9 is the stop and step is default 1.
for i in range(0, 10, 3):

print (i, end=” “)

0 3 6 9 0 is the start, 9 is the stop and step is default 3.
for i in range(-10, -100 -30):

print (i, end=” “)

-10 -40 -70 -10 is start, -100 is stop and step is  -30
for i in range(21,-1,-2):

print (i, end=” “)

21 19 17 15 13 11 9 7 5 3 2 1 21 is start,1 is stop, and step is -2
for i in range(11,3,-1):

print (i, end=” “)

11 10 9 8 7 6 5 4 11 is start, 3 is stop and -1 is step

Example 1: 

for a in [1,4,7]:
print (a)
output:
1
4
7
In the above example, for loop will be processed as follows:

  • Firstly, the loop – variable a will be assigned first value of list that is 1 and the statements in the body of the loop will be executed with this value of a. Hence value 1 will be printed.
  • Next, a will be assigned next value in the list that is 4 and loop – body executed. Thus 4 is printed.
  • Next, a will be assigned next value in the list that is 4 and loop – body executed. Thus 7 is printed.
  • All the values in the list are executed, hence loop ends.

 Example 2:

for A in [1,2,3]:
print (A*A*A)
output:
1
8
27

Example 3:

for ch in ‘Python’
print (ch)

output:
P
y
t
h
o
n

NOTE: variable ch given values are ‘P’, ‘y’, ‘t’, ‘h’, ‘o’, ‘n’  one at a time from string ‘Python’.