You are on page 1of 64

CHAPTER - 9

CONDITIONAL AND ITERATIVE STATEMENTS


Table of Contents – CHAPTER 9
9 Control and Iterative
Statements
9.5 Introduction to Looping
statements.
9.1 Introduction
9.5.1 The While Loop
9.2 Statements and its Types.
9.5.2 The For Loop
9.3 Introduction to Control
9.5.3 Nested Loops
Statements and its types.
Introduction to Jump
9.6
9.4 Introduction to Selection Statements.
Statements and its types.
9.6.1 Break statement
9.4.1 If- Statement
9.6.2 Continue Statement
9.4.2 If-else Statement
9.6.3 Pass Statement
9.4.3 If-elif-else Statement

9.4.4 Nested if Statement 9.7 Loop with else statements.


9.1 INTRODUCTION
In Python Statements in a program are executes one after another in order which they
are written.( This is called sequential execution of the program).

But, in some situation we need to execute/skip some part of the code according to the
condition.

To create a good program, we must plan using program logic and development tools.
9.2 STATEMENTS AND ITS TYPES IN PYTHON
Statements are the instructions given to the computer to perform any kind of action.

Statements form the smallest executable unit with in a Python Program.

Generally, In Python Statements are divided into three types. They are:

STATEMENTS

Simple Compound Empty


Statements Statements Statement
(i) Simple Statements:

Any single executable statement is called simple statement in Python.

These simple statements are executed one by one in python.

Example:

Age=int(input(“Enter your age:”)) Statement 1

print(Age) Statement 2

(ii) Compound Statement:

A compound statements contains one or more other statements and controls their
execution. Which consists of a header followed by one or more indented line.

Each header starting with a keyword and ending with a colon(:)


In Python , compound statements are written in specific pattern as shown below:
Header :
Statement 1
Statement 2 Body or block of header
Statement 3 (indented four space rightwards)
.
…..

(iii) Empty Statement:

The body of compound statement cannot be empty; it must always contains at least
one statement.

A pass statement is useful in in those situations. Which performs no actions , as a


place holder when a statement is syntactically required but you have nothing to do.
Header :
pass
9.3 CONTROL STATEMENTS (or) FLOW OF CONTROL
A control statements is a statement that determines the control flow of the set of
instructions.

Control statements are divided into three main categories. They are:

Control
Statement
s

Selection/Decision Looping (or)


Jumping
Making statements Iterative
Statements
Statements

if while loop break

if-else for loop


continue
if-elif while-else

nested if for -else pass


(i) Selection Statements/ Decision Making
statements
Decision making statements are used to select one or more statements based on the
condition.

In Python, there are Four types of selection/decision making statements are available
they are:

(i) if statement.

(ii) if-else statement.

(iii) if-elif-else statement

(iv) Nested if statement.


9.4.1 IF-STATEMENT
If statement is called one way decision making statement. Which is used to test the
condition True or False.

if condition is true , then it evaluates the true statements. Otherwise, it will execute
normal statements.

Note:

After executing true statements, the flow will continue with normal statements.

False
Syntax: if
Conditio
n

True
Statement(s)
EXAMPLES
1. Write a Python program to get a number from the user, check whether it is equal

to 12. If it is equal to 12 print "Yes, the given number is equal to 12“.

Source code:

2. Write a Python program to check whether the given number is positive.


EXAMPLES
3. Write a Python program to get a number from the user, check whether it is lies

between 5 to 10.

Source code:

(or)
9.4.2 IF-ELSE-STATEMENT
If else statement is called Two way decision making statement. Which is used to test
the condition True or False.

if condition is true , then it evaluates the true statements. Otherwise, it will execute else
statements.

Note:

After executing if statements or else statements, the flow will continue with normal
statements.

Syntax: True if False


Conditio
n

True False
Statement(s) Statement(s)

Normal
statements
EXAMPLES USING IF-ELSE STATEMENTS
1. Write a python program to get age from the user and check whether he (or) she

is eligible to vote or not

Source code:

2. Write a Python program to check whether the given number is positive or


negative.
PRACTICE QUESTIONS
1. Write a Python program to display greatest of two integer numbers.

2. Write a Python program to check whether a given number is divisible by 2 and 6.

3. Write a Python program to check whether a number is odd or even.

4. Write a Python program to take values of length and breadth of a rectangle and check
whether it is square or not.
APPLICATION BASED PROGRAM QUESTIONS
1. A Company decided to give bonus of 5% to their employees. If His/ Her year of
services are more than 5 years. Ask user for their salary and years of service and print
net bonus.

2. A student will not be allowed to sit in exam if his/her attendance is less than 75% .
Take the following input from the user: Number of class held, Number of classes
attended and print percentage of class attendance along with whether the student is
allowed to sit in exam hall or not.
9.4.3 IF-ELIF-ELSE STATEMENTS
If-elif statements are called multi way decision making statements.

If-elif-else statements works in situation where multiple conditions need to be check.

Syntax:
FLOW CHART OF if elif statements
EXAMPLE - 1
Write a Program that accepts a number (say ‘n’) and we wish do the following:

(i) if n is 0 do nothing.

(ii) if n is positive – print n*n.

(iii) if n is negative – print n*n*n.

Source Code:
EXAMPLE - 2
Write a Python program to input week number(1-7) and print day of week name.

Source Code:
EXAMPLE - 3
Write a Menu driven program to get two numbers from the user and find addition,
subtraction, multiplication and division depends on the user’s choice.
EXAMPLE - 4
Write a Program that accepts a country name as per the following table and assign to
a variable, then finally display it’s capital.
Country Name Capital
India New Delhi
France Paris
UK London
USA Washington D.C
EXAMPLE - 5
Write a Python program to input electricity unit charge and calculate the total electricity bill
according to the given condition:
For first 50 units Rs. 0.50/unit
For next 100 units Rs. 0.75/unit
For next 100 units Rs. 1.20/unit
For unit above 250 Rs. 1.50/unit
An additional surcharge of 20% is added to the bill.
PRACTICE QUESTION BASED ON if-elif-else
Q.No: 1

Mr. Rajesh provides the side of Measurements of a triangle. He asks the students to
check whether It is a Scalene triangle, Isosceles triangle or Equilateral triangle. Write a
suitable Python program to solve the above problem.

Note:

Scalene Triangle – It is a triangle that has no equal sides.

Isosceles Triangle – It is a triangle that has two equal triangles.

Equilateral triangle – It is a triangle that has three equal sides.


PRACTICE QUESTION BASED ON if-elif-else
Q.No 2:

Write a Python program to check whether a given year is leap year or not.

Q.No: 3

Write a menu driven program to find the area of circle, rectangle and square. The menu is given
below:

1 – Area of Circle.

2- Area of Rectangle.

3- Area of Square
PRACTICE QUESTION BASED ON if-elif-else
Q.No: 3

Write a Python program to input marks of five subjects Physics, Chemistry, Math and CS,

calculate average and print grade according to given conditions:

If average is 90 – 100 : Grade A

If average is 80 – 89 : Grade B

If average is 70- 79 : Grade C

If average is 60- 69 : Grade D

If average is 40 – 59 : Grade E

If average is < 40 : Grade F


PRACTICE QUESTIONS BASED ON if-elif-else
Q.No 4:
9.4.4 Nested If statements
Placing if statement inside another if statement is called nested if statements.

In Python we can use nested if in four ways.

WAY – 1: WAY – 2:
SYNTAX
WAY – 3: WAY – 4:
EXAMPLE - 1

Source Code:
EXAMPLE - 2
Write a Python Program to Find the Largest Among Three Numbers.

For example,

Source Code:
EXAMPLE - 3
Write a Python program to check whether a given year is leap year or not.

Source code:
HOME WORK
1. While purchasing certain items, a discount of 10% is offered if the quantity purchased is
more than 1000. If quantity and per item are input through the keyboard, write a Python
program to calculate the total expenses.

2. In a company an employee is paid as under:


If his/her basic salary is less than Rs.1500, then HRA=10% of basic salary and DA=90%
of basic salary. If his/her salary is equal to or above Rs.1500, then HRA=Rs.500
and DA=98% of basic salary. If the employee’s salary is input through keyboard, write a
Python program to find his/her gross salary.

3. A company insures its drivers in the following cases:


- If the driver is married.
- If the driver is unmarried, male and above 30 years of age.
- If the driver is unmarried, female and above 25 years of age.
In all other cases, the driver is not insured. If marital status, gender and age of the driver
are inputs, Write a Python program to determine whether the driver should be insured or
not.
9.5 LOOPING (or) ITERATIVE STATEMENTS
What is Looping? :

Looping is the process of repeating some set of statements again and again until
the condition becomes false or until it reaches the last element in sequence.

Types of Looping:

(i) while loop.

(ii) for loop.


9.5.1 The While Loop
While loop is used to repeatedly execute the instructions/statements as long as
condition is true.

To use while loop in Python we must use while keyword.

Properties of while loop:

A While loop has four properties. They are:

(i) Initialization Expression(s) - It indicates starting value of a loop variable.

(ii) Test Expression. - It is used to evaluate the condition.

(iii) The Body of the loop. - The statements that are executed repeatedly form the
body of the loop.

(iv) Update expression(s) - The update expression change the value of a loop
variable.
SYNTAX:

Body of the
Loop.

How while loop works?

At first the test expression is checked. If it is False the body of the loop will not
execute at all and control transfer to the next line of code after the while loop.

However, if the test expression is true, then the body of the loop is execute. After
executing the body of the loop, once again it will check the condition, if the
condition is true once again it will execute the body of the loop.

This process will repeat until the test expression becomes False.
EXAMPLES
Example -1:

Write a Python program to print "Welcome" five times using while loop.

Example -2:
Write a Python program to get five fruits name from the user using while loop.
Example -3:

Write a Python program to print numbers from 1 to 10 also finally print "Finished"
using while loop.

Example -4:
Write a Python program to print numbers from 1 to 10 in reverse order.
Example -5:

Write a Python program to print even numbers from 1 to 20 using while loop.

Example -6:
Write a Program to calculate and print the sums of even and odd integers of the first
‘n’ natural numbers.
Example -7:

Write a Python program to print table of a number. Say 5.

Example -8:

Write a Python program to print factorial of a number.


PRACTICE QUESTIONS
1. Write a Python program to enter your name and print it five times using while loop.

2. Write a Python program to find the sum of first 10 natural numbers.

I.e. (1+2+3+4+5+6+7+8+9+10=55)

2. Write a Python program to find and print square of numbers from 5 to 15.

3. Write a Python program to get four digit number from the user and print its reverse
form. (EX: I/P: Enter a Number: 1589 O/P: The reverse of given number is: 9851)

4. Write a Python program to find and display first 10 Fibonacci numbers.

(EX: The First 10 Fibonacci series is: 0,1,1,2,3,5,8,13,21,34)

5. Write a Python program to check whether a number entered by user is an Armstrong


number. Note: if sum of cubes of each digit of the number is equal to the number it
self then the number is called an Armstrong number.

For example 153 = 13 + 53 +33 (i.e. (1**3)+(5**3)+(3**3))


INFINITE LOOP
An infinite loop that never ends.

So, Whatever is in the loop gets executed forever unless the program is terminated.

We can achieve infinite loop using True keyword.

Example:

In the above example, Hi!!! will print Infinite number of times.


range()
It is a built-in function in python.

It is used to generate a sequence of integer numbers in specific range.

The list of numbers generated using range() can be iterate.

range() can be use in three ways:

i. range(stop)

ii. range(start, stop)

iii. range(start, stop, step)

Example:
Statement Values generated
>>>range(5) 0,1,2,3,4
>>>range(1,10) 1,2,3,4,5,6,7,8,9
>>>range(2,10,2) 2,4,6,8
>>>range(5,15,3) 5,8,11,14
>>>range(10,1,-2) 10,8,6,4,2
9.5.2 The for loop
In Python for loop is called "Counting loop" or "Definite loop“.

The for loop has the ability to iterate over the items of any sequence, such as a list or
a string.

We can also use for loop with range of values.

In Python, for loop can be write in two forms. They are:


How for loop works with sequence ?

Step 1: The iterate variable is assigned the first value in the sequence.

Step 2: All the statements in the body of for loop are executed with assigned value
of iterate variable.

Step 3: Once step 2 is over, the iterate variable is assigned the next value in
sequence and loop body is executed with the new value of iterate variable.

Step 4: This continues until all values in the sequences are processed.
Example – for loop using range()
Ex 1: Write a Python Program to print "Welcome" Ex 3: Write a Python program to print
even numbers from 1 to 10 using for
five times using for loop. loop.

Ex 2: Write a Python program to print Ex 4: Write a Python program to print


numbers from 1 to 10 using for loop. numbers from 20 to 30 in reverse order
using for loop.
Ex 5: Write a Python Program to print sum of first 10 natural numbers.

Ex 6: Write a Python program to print Fibonacci series’ first 10 elements .

Output:
Example - for loop using sequence.

Output: Output:
PRACTICE QUESTIONS
1. Write a Python program to obtain fruit name from user and print it five times using for
loop.
2. Write a Python program to print sum of even and sum of odd integer numbers from 1 to
20 using for loop.
3. Write a Python program to print the following series using for loop:
3 4 7 10 … 40.
4. Write a Python program to print the following series using for loop:
1 -4 7 -10 … -40.
5. Write a Python program to print sum of series: S= 1+ x+x2 +X3 + …. + xn
6. Write a Python program to input two numbers and print their LCM and GCD.
7. Write a Python program to print first 10 Prime numbers using for loop.
8. Write a Python program to get name from the user and print character by character using
for loop.
9.5.3 NESTED LOOPS
Nested Loop:

Placing of one loop within another loop is called "Nested Loop".

Both for and while statements can be used as in nested loop.

Nested while loop syntax: Nested for loop Syntaxes:

z
NESTED LOOP EXAMPLES
1. Write a Python Program to print multiplication table 1 to 5 using nested while loop
and nested for loop.

Using Nested while Loop: Using Nested for loop:


Example -2 :

Write a Python program to print the following patterns:


9.6 JUMP STATEMENTS
Jump statements are used to modify the flow of a loop.

Python offers three types of jump statements: (i) break (ii) continue (iii) pass.

(i) Break Statement:

The break statement is used to terminate the loop in between the execution.
9.6.1 Break Statement
(i) Break Statement:

The break statement is used to terminate the loop which it is defined in between the
execution.

Whenever, break keyword is encountered by Python, the control will transfer


immediately outside of current loop and starts to execute normal lines.

Syntax: break
How to use break in loops and nested loops
EXAMPLE PROGRAM USING break
Example :

Using While loop: Using for loop:

Sample Output:
Sample Output:
Here, upto 5 number of
Here, upto 5 number of i is printed. When it i=6
i is printed. When it i=6 then it will break loop
then it will break loop and transfer control to
and transfer control to normal statement. I.e.
normal statement. I.e. outside of loop,
outside of loop,
9.6.2 Continue Statement
(ii) Continue Statement:

The continue statement is used to transfer the control to the beginning of the loop.

Whenever, continue keyword is encountered by Python. It will skip the rest of the
statements in the current loop block and continue next iteration of the loop.

Syntax: continue
How to use continue in loops and nested loops
EXAMPLE PROGRAM USING continue
Example :

Using While loop: Using for loop:

Sample Output: Sample Output:

Here, When i=6 then it Here, When i=6 then it


will transfer control to will transfer control to
beginning of the loop. So, beginning of the loop.
that It will skip number 6. So, that It will skip
number 6.
9.6.3 Pass Statement
(iii) Pass Statement:

The Pass statement in Python is used when a statement required syntactically but you
don’t want any command or code to execute.

This is also called an “Empty statement”.

Nothing happens when pass statement is execute by python.

Sample Output: Sample Output:

Finished Finished

Sample Output:
Sample Output:
i value is: 9
i value is: 11
9.7 LOOP WITH ELSE STATEMENTS
Python allows the else keyword to be used with the for and while loops too.

The else block appears after the body of the loop.

In loop else statement work in two situations in looping:

i. Whenever the condition becomes false in the beginning itself.

ii. Whenever the loop finished its iteration.

The else statement will not work in the following situation:

i. If we use break in loop, then that time else will not work.
Loop with else statement
 
while condition: for variable in seq:
statement 1 statement 1
statement 2 statement 2
... ...
... ...
else: else:
statement(s) statement(s)

Note: The else block appears after the body of the


loop.
Loop with else and break statement
while condition: for variable in seq:
statement 1 statement 1
if condition: if condition:
break break
statement 2 statement 2
update exp
... else:
else: statement(s)
statement(s)
Normal Statement 1
Normal Statement 1 Normal Statement 2
Normal Statement 2 Normal Statement 3
Normal Statement 3
EXAMPLES
Example – 1 Example – 2:

(Loop else without break) (Loop else with break statement)

Sample Output:

Sample Output:
THE END

You might also like