0% found this document useful (0 votes)
5 views13 pages

Python Control Statements Explained

The document provides an overview of control statements in Python, including selection (if, if-else, nested if, if-elif-else) and iterative (while, for) control structures. It explains the syntax, flowcharts, and examples for each type of statement, as well as the use of break, continue, and pass statements. Additionally, it covers the else statement in loops and provides sample programs demonstrating various control structures.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views13 pages

Python Control Statements Explained

The document provides an overview of control statements in Python, including selection (if, if-else, nested if, if-elif-else) and iterative (while, for) control structures. It explains the syntax, flowcharts, and examples for each type of statement, as well as the use of break, continue, and pass statements. Additionally, it covers the else statement in loops and provides sample programs demonstrating various control structures.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Unit II

Control Statements
A control statement is a statement that determines the control flow of a set of
instructions, i.e., it decides the sequence in which the instructions in a program are to be
executed.
Types of Control Statements
 Selection/Conditional Control: To execute only a selected set
of statements.
 Iterative Control: To execute a set of statements repeatedly.
 Jump Statements / Un-conditional Control.
1. Selection /Conditional Branching Statements:
 Python language supports different types of conditional branching statements
which are as follows:
 if Statement
 if-else Statement
 Nested if statement
 if-elif-else statement
if Statement :
An if statement is a selection control statement which is based on the
value of a given Boolean Expression.
Syntax:
if test_expression:

statement 1
.....
statement n
statement x
 if structure may include 1 or n statements enclosed within if block.
 First, test expression is evaluated. If the test expression is true, the statement of if
block (statement 1 to n) are executed, otherwise these statements will be skipped
and the execution will jump to statement x.

SSASC Dept. Of Computer Science bbalaji@[Link] I B.C.A. Girls

1|Page
Flow chart:

Example:

if else Statement:
 The if ..... else statement executes a group of statements when a test
expression is true; otherwise, it will execute another group of statements.
Syntax:

if (test expression):

statement_block 1

else:

statement_block 2

statement x

If the condition is true, then it will execute statement block 1 and if the
condition is false then it will execute statement block 2.

Flowchart:

SSASC Dept. Of Computer Science bbalaji@[Link] I B.C.A. Girls

2|Page
Example: Write a program to determine whether a person is eligible to vote:

Nested if Statements:
 A statement that contains other statements is called a compound statement.
 To perform more complex checks, if statements can be nested, that is,
can be placed one inside the other.
 In such a case, the inner if statement is the statement part of the outer one.
 Nested if statements are used to check if more than one conditions
are satisfied.
 if statements can be nested resulting in multi-way selection.
Syntax:
if expression1:
statement(s)
if expression2:
statement(s)
else
statement(s)
else:
if expression3:
statement(s)
else:
statement(s)

SSASC Dept. Of Computer Science bbalaji@[Link] I B.C.A. Girls

3|Page
Flowchart:

Example:
num=8
print ("num = ",num)
if num%2==0:
if num%3==0:
print ("Divisible by 3 and 2")
else:
print ("divisible by 2 not divisible by 3")
else:
if num%3==0:
print ("divisible by 3 not divisible by 2")
else:
print ("not Divisible by 2 not divisible by 3")
Output:
num = 8
divisible by 2 not divisible by 3
num = 15
divisible by 3 not divisible by 2
num = 12
Divisible by 3 and 2
num = 5
not Divisible by 2 not divisible by 3

SSASC Dept. Of Computer Science bbalaji@[Link] I B.C.A. Girls

4|Page
if-elif-else Statement:
 Python supports if-elif-else statements to test additional conditions apart
from the initial test expression.
 The if-elif-else construct works in the same way as a usual if-else statement.
 If-elif-else construct is also known as nested-if construct.
 A series of if and elif statements have a final else block, which is executed if
none of the if or elif expressions is True.
Syntax:
if (test expression 1):

statement block1
elif (test expression 2):
statement block2
. . . . . . . . . . . . . . ..
elif( test expression N):
statement block N
else:
statement block X
Flowchart:

SSASC Dept. Of Computer Science bbalaji@[Link] I B.C.A. Girls

5|Page
Example: To test whether a number entered by the user is negative, positive, or zero

Looping Statements/Iterative Structure:


Iterative statements are decision control statements that are used to repeat the
execution of a list of statements.
Python supports 2 types of iterative statements-while loop and for loop.
while Loop:
The While loop provides a mechanism to repeat one or more statements while
a particular condition is TRUE.
Syntax:
Statement x
while (condition):
Statement block
Statement y

 In while loop, the condition is tested before any of the statements in


the statement block is executed.

 If the condition is TRUE, only then the statements will be executed


otherwise if the condition is False, the control will jump to statement
y, that is the immediate statement outside the while loop block.

Flowchart:

SSASC Dept. Of Computer Science bbalaji@[Link] I B.C.A. Girls

6|Page
Example: Program to print first 10 numbers using a while loop
i=0
while(i<=10):
print(i, end=” “)
i=i+1
Output: 0 1 2 3 4 5 6 7 8 9 10
for Loop:

 For loop provides a mechanism to repeat a task until a particular condition


is True. It is usually known as a determinate or definite loop because the
programmer knows exactly how many times the loop will repeat.

 The for...in statement is a looping statement used in Python to iterate over


a sequence of objects.

Syntax:

for loop_control_var in sequence:

statement block

Flowchart:

for Loop and range() Function:

The range( ) function is a built-in function in Python that is used to iterate


over a sequence of numbers.

Syntax: range(beg, end, [step])

SSASC Dept. Of Computer Science bbalaji@[Link] I B.C.A. Girls

7|Page
 The range( ) produces a sequence of numbers starting with beg (inclusive)
and ending with one less than the number end.

 The step argument is option (that is why it is placed in brackets). By


default, every number in the range is incremented by 1 but we can
specify a different increment using step. It can be both negative and
positive, but not zero.

Example: Program to print first n numbers using the range() in a for loop.

 If range( ) function is given a single argument, it produces an object with


values from 0 to argument-1. For example: range(10) is equal to writing
range(0, 10).

 If range( ) is called with two arguments, it produces values from the


first to the second. For example, range(0, 10) gives 0-9.

 If range( ) has three arguments then the third argument specifies the
interval of the sequence produced. In this case, the third argument must
be an integer. For example, range(1, 20, 3) gives 1, 4, 7, 10, 13, 16,
19.

Example:

Nested Loops:

 Python allows its users to have nested loops, that is, loops that can
be placed inside other loops.

 Although this feature will work with any loop like while loop as well as
for loop.
SSASC Dept. Of Computer Science bbalaji@[Link] I B.C.A. Girls

8|Page
 A for loop can be used to control the number of times a particular set of
statements will be executed.

 Another outer loop could be used to control the number of times that
a whole loop is repeated.

 Loops should be properly indented to identify which statements are


contained within each for statement.

Example: Program to print the following pattern

Condition-controlled and Counter-controlled Loops

The Break Statement:

 The break statement is used to terminate the execution of the nearest


enclosing loop in which it appears.

 The break statement is widely used with for loop and while loop.

 When compiler encounters a break statement, the control passes to the


statement that follows the loop in which the break statement appears.

Syntax: break

SSASC Dept. Of Computer Science bbalaji@[Link] I B.C.A. Girls

9|Page
Example: Program to demonstrate the break statement

 Above code is meant to print first 10 numbers using a while loop, but it
will actually print only numbers from 0 to 4. As soon as i becomes equal
to 5, the break statement is executed and the control jumps to the
following while loop.
 Hence, the break statement is used to exit a loop from any point with in its
body, by passing its normal termination expression. Below, Figure shows the
transfer of control when the break statement is encountered.

The Continue Statement

 Like the break statement, the continue statement can only appear in the
body of a loop.

 When the compiler encounters a continue statement then the rest of the
statements in the loop are skipped and the control is unconditionally
transferred to the loop-continuation portion of the nearest enclosing
loop.

Syntax: continue

SSASC Dept. Of Computer Science bbalaji@[Link] I B.C.A. Girls

10 | P a g e
Example: Program to demonstrate continue statement

 Note that the code is meant to print numbers from 0 to [Link] as soon as
i becomes equal to 5, the continue statement is encountered, so rest of the
statements in the loop are skipped. In the output, 5 is missing as continue
caused early increment of i and skipping of statement that printed the value
of i on screen.

 Below figure illustrates the use of continue statement in loops.

 It can be concluded that the continue statement is somewhat the opposite


of the break statement. It forces the next iteration of the loop to take place,
skipping any code in between itself and the test condition of the loop.

 The continue statement is usually used to restart a statement sequence when


an error occurs.
The Pass Statement

 Pass statement is used when a statement is required syntactically but no


command or code has to be executed.

SSASC Dept. Of Computer Science bbalaji@[Link] I B.C.A. Girls

11 | P a g e
 It specified a null operation or simply No Operation (NOP)
statement. Nothing happens when the pass statement is executed.

 The difference between a comment and pass statement is that while


the interpreter ignores a comment entirely, pass is not ignored.

 Comment is not executed but pass statement is executed but nothing


happens.

 Pass is a null statement.

Example: Program to demonstrate pass statement

Difference between break, continue and pass

 The break statement terminates the execution of the nearest enclosing loop
in which it appears.

 The continue statement skips the rest of the statements in the loop transfer
the control un-conditionally to the loop-continuation portion of the nearest
enclosing loop.

 The pass statement is a do-nothing statement in a loop. It is just added to


make the loop syntactically correct. i.e, a pass statement is written as we
can not have an empty body of the loop

The Else Statement Used With Loops

 In Python you can have the else statement associated with a


loop statements.

 If the else statement is used with a for loop, the else statement is executed
when the loop has completed iterating.
SSASC Dept. Of Computer Science bbalaji@[Link] I B.C.A. Girls

12 | P a g e
 But when used with the while loop, the else statement is executed when
the condition becomes false.

Example:
1. Write a python program to Test whether a given number is even or odd.
num = int(input("Enter a number: "))
if (num % 2==0):
print(num, "is an even number.")
else:
print(num, "is an odd number.")

2. Write a python program to Print out the decimal equivalents of 1/1, 1/2, 1/3, 1/4. 1/10
using for loop.
i=1
for i in range(1,11):
value=1.0/i
print("1/", i, "=", value)

3. Write a python program to Print a count down from the given number to zero using a while
loop.
num=int(input("Enter a number: "))
print("count down from ", num, "to 0 :")
while (num >= 0):
print(num) num = num – 1

4. Write a python program to Find the sum of all the primes below hundred.
sum=0
for j in range(1,100):
for i in range(2,j):
if( j % i)==0:
break
else:
sum=sum+j #where j is a prime number
print("Sum of prime numbers up to 100 is", sum)

5. Write a python program to find the factorial of a given number.


num=int(input("Enter a number: "))
fact=1
while (num>0): fact=fact*num num=num-1
print("Factorial of", num, "is",fact)

SSASC Dept. Of Computer Science bbalaji@[Link] I B.C.A. Girls

13 | P a g e

You might also like