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

8.flow of Control

The document discusses different types of statements and flow control in Python. It covers empty, simple, and compound statements. For flow control, it describes sequence, selection, and repetition/iteration. Selection includes if, if-else, if-elif statements and nested if statements. Repetition includes for and while loops. It also discusses range() function, membership operators like in and not in, and syntax of for and while loops. Program logic development tools like flowcharts, decision trees and pseudocode are also mentioned.

Uploaded by

WERTY RRRFDD
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)
41 views13 pages

8.flow of Control

The document discusses different types of statements and flow control in Python. It covers empty, simple, and compound statements. For flow control, it describes sequence, selection, and repetition/iteration. Selection includes if, if-else, if-elif statements and nested if statements. Repetition includes for and while loops. It also discusses range() function, membership operators like in and not in, and syntax of for and while loops. Program logic development tools like flowcharts, decision trees and pseudocode are also mentioned.

Uploaded by

WERTY RRRFDD
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
You are on page 1/ 13

FLOW OF CONTROL

Types of statements in Python:


Statements are the instructions given to the computer to perform any kind of action.
Python statements can belong to one of the following three types:-

Empty Statement
A statement that does nothing.In Python an empty statement is pass statement.It takes the
following form:
Pass
Whenever Python encounters a pass statement, Python does nothing and moves to the next
statement in the flow of control.

Simple Statement
Any executable statement is a simple statement in Python. For example:
Name=input(“enter your name”)

Compound Statement
A compound statement represents a group of statements executed as a unit. The compound
statements in Python are written in a specific pattern .
It has :
● A header line which begins with a keyword and ends with a colon.
● A body consisting of one or more Python statements, each indented inside the header
line.

Statement Flow Control :


In a program statements may be executed sequentially,
selectively or iteratively. Every programming language provides
constructs to support sequence, selection or iteration.

SEQUENCE
● The sequence construct means the statements are
being executed sequentially.
● Sequence refers to the normal flow of control in a
program and is the simplest one.

1
SELECTION
● The selection of a construct means the execution of a statement. depending upon a
condition test.
● If a condition evaluates to true, a cause of action (a set of statements) is followed,
otherwise another course of action (a different set of statements) is followed.
● This construct (selection construct) is also called decision construct because it helps in
making decisions about which set of statements is to be executed.
● Decision making can be implemented in python using:
1. if statements
2. if-else statements
3. if-elif statements
4. nested if statements

REPETITION ITERATION (LOOPING)


● The iteration constructs mean repetition of a set of statements depending upon a
condition test.
● Till the time a condition is true, a set of statements are repeated again and again.
● As soon as the condition becomes False, the repetition stops.
● The iteration construct is also called a looping construct.

2
Program Logic Development Tools:
Before developing the solution of a problem in terms of a program, we should read and analyze
the given problem and decide about basic sub tasks needed to solve a problem i.e., algorithm.
The various logic development tools are:
● Flowcharts
● Decision trees
● Pseudocode

FLOWCHARTS:- A flowchart is a graphical representation of an algorithm. A flowchart


shows different subtasks with different symbols. Some commonly used flowchart symbols are :

3
DECISION TREES:- A decision tree is a decision support tool that uses a tree-like model
of decisions and their possible consequences, including chance event outcomes, resource
costs, and utility. It is one way to display an algorithm that only contains conditional control
statements.

PSEUDOCODE:- Pseudocode is an artificial and informal language that helps


programmers develop algorithms. Pseudocode is a "text-based" detail (algorithmic) design tool.

The if statements of Python :


The if statements are the conditional statements in Python and these implement selection
constructs.
An if statement tests a particular condition; if the condition evaluates to true, a
course-of-action is followed i.e. a statement or set-of-statements is executed.
Syntax :
if <condition>:
statement
For example:-
if grade==’A’:
print(“well done”)

FLOW CHART

4
If-else statement :
● An else statement can be combined with an if statement.
● An else statement contains the block of code that executes if the conditional expression
in the if statement resolves to 0 or a false value.
● The else statement is an optional statement and there could be at most only one else
statement following if.
The syntax of if..else is:
if expression:
statement(s)
else:
statement(s)
Example :
if grade == ‘A’ :
print (“well done”)
else:
print (”try again”)

FLOW CHART

The if-elif Statement:


● Sometimes there are more than two possibilities; in that case we can use the elif
statement.
● It stands for “else if,” which means that if the original if statement is false and the elif
statement is true, execute the block of code following the elif statement.
The Syntax of the if…elif statement is:
if expression1:
statement(s)
elif expression2:
statement(s)
elif expression3:
statement(s)
else:
statement(s)

5
Example :
num=int(input(“enter the number”))
if num<0:
print(“Invalid entry. Valid range is 0 to 999.’’
elif num<10:
print(“single digit number is entered”
elif num<100:
print(“double digit number is entered”
elif num<=999:
print(“three digit number is entered”)
else:
print(“invalid entry.valid range is 0 to 999.”)

FLOW CHART

The Nested-if statement :


● One conditional can also be nested within another. i.e., We can have an if...elif...else
statement inside another if...elif...else statement. This is called nesting in computer
programming.
● Any number of these statements can be nested inside one another. Indentation is the
only way to figure out the level of nesting.

Syntax of Nested if..else statement is:


if TEST EXPRESSION1:
if TEST EXPRESSION2:
STATEMENTS_B
else:
STATEMENTS_C
else:
if TEST EXPRESSION3:
STATEMENTS_D
else:
STATEMENTS_E

6
Example:
a=10
b=20
c=5
if a>b:
if a>c:
print("Greatest number is ",a)
else:
print("Greatest number is",c)
else:
if b>c:
print("Greatest number is ",b)
else:
print("Greatest number",c)

Flow Chart

STORING CONDITION
● Sometimes the conditions being used in code are complex and repetitive.
● In such cases, to make your program more readable, you can use named conditions
i.e., you can store conditions in a name and then use that named conditional in the if
statements.

THE RANGE( ) FUNCTION


● The range( ) function of python, which is used with the Python for loop.
● The range( ) function of python generates a list which is a special sequence type.
● A sequence in Python is a succession of values bound together by a single name e.g.,
list, tuple, string.
● It is used to create a list containing a sequence of integers from the given start value
upto stop value
(excluding stop value), with a difference of the given step value.
● In function range(), start, stop and step are parameters.

7
Syntax of range() function is:
range([start], [stop], [step])

For example:-
range(0,10, 2)
Output:- [ 0, 2, 4, 6, 8 ]

OPERATORS IN AND NOT IN


● The in operator tests if a given value is contained in a sequence or not and returns True
or False accordingly.
● Operators in and not in are also called membership operators.

For example:-
'a' in "trade"
Output:- True
as 'a' is contained in sequence. (string type) "trade".

ITERATION / LOOPING STATEMENTS


● The iteration statements or repetition statements allow a set of instructions to be
performed repeatedly until a certain condition is fulfilled.
● The iteration statements are also called loops or looping statements.
● Python provides two kinds of loops: for loop and while loop to represent two categories
of loops, which are :
Counting loops:- the loops that repeat a certain number of times ; Python's for loop is a
counting loop.
Conditional loops:- the loops that repeat until a certain thing happens i.e., they keep
repeating as long as some condition is true; Python's while loop is conditional loop.

THE FOR LOOP


● The for loop of Python is designed to process the items of any sequence, such as a list
or a string, one by one.
● for loop ends when the loop is repeated for the last value of the sequence.
● The for loop repeats n number of times, where n is the length of sequence given in for
loops header.
● Each time, when the loob-body is executed, it is called an iteration.
● The loop variable contains the highest value of the list after the for loop is over .

Syntax:-
for <variable> in <sequence>
statements_to_repeat
For example:-
for a in [ 1, 4, 7 ]
print(a)
print(a*a)
8
A for loop in Python is processed as:
● The loop-variable is assigned the first value in the sequence.
● All the statements in the body of the for loop are executed with the assigned value of the
loop variable (step 2).
● Once step 2 is over, the loop- variable is assigned the next value in the sequence and
the loop-body is executed (i.e., step 2 repeated) with the new value of loop-variable.
● This continues until all values in the sequences are processed.

THE WHILE LOOP


● A while loop is a conditional loop that will repeat the instructions within itself as long as a
conditional remains true.
● The variable used in the condition of the while loop must have some value before
entering into the while loop.
● The statements within the body of the while loop must ensure that the condition
eventually becomes false; otherwise the loop will become an infinite loop, leading to a
logical error in the program.

Syntax:-
while test_condition:
body of while

For example:-
a=5
while a > 0 :
print ("hello" , a)
a=a-3
print ("Loop Over !!")

Output:-
hello 5
hello 2
Loop Over !!

Anatomy of a while Loop (Loop Control Elements)


A while loop has four elements that have different purposes. These elements are as given
below:

1) Initialization Expression (starting)


✓ Before entering in a while loop, it's loop variable must be initialized.
✓ The initialisation of the loop variable (or control variable) takes place under initialization
expression(s).
✓ The initialisation expression(s) gives the loop variable(s) their first value(s).
✓ The initialization expression(s) for a while loop are outside the while loop before it starts.
9
2) Test Expression (Repeating or Stopping)
✓ The test expression is an expression whose truth value decides whether the loop-body will
be executed or not.
✓ If the test expression evaluates to true, the loop- body gets executed, otherwise the loop is
terminated.
✓ In a while loop, the test-expression is evaluated before entering into a loop.

3) The Body-of-the-Loop (doing)


✓ The statements that are executed repeatedly (as long as the test expression is true) form the
body of the loop.
✓ In a while loop, before every iteration the test-expression is evaluated and if it is true, the
body-of-the-loop is executed; if the test-expression evaluates to false, the loop is terminated.

4) Update Expression(s) (Charging)


✓ The update expressions change the value of the loop variable.
✓The update expression is given as a statement inside the body of the while loop.

IMPORTANT THINGS RELATED TO WHILE LOOP ARE :


● In a while loop, a loop control variable should be initialized before the loop begins as an
uninitialized variable cannot be used in an expression.
Consider the following code :
while p ! = 3:
:
This will result in error if variable p has not been created beforehand.

● The loop variable must be updated inside the body- of -the -while in a way that after
some time the test-condition becomes false otherwise the loop will become an endless
loop or infinite loop.
Consider the following code :
a=5
while a > 0 :
print(a)
print ("Thank You")
ENDLESS LOOP! Because the loop- variable a remains 5 always as its value is not updated in the loop-body hence the
loop-condition a>0 always remains true.
The corrected form of above loop will be:
a=5
while a > 0 :
print(a)
a -= 1
print ("Thank You")
● To cancel the running of an endless loop, we can press CTRL + C keys anytime during
its endless repetition to stop it.

10
JUMP STATEMENT - BREAK AND CONTINUE
Python offers two jump statements to be used within loops to jump out of loop-iterations.

THE BREAK STATEMENT


The break statement skips the rest of the loop and jumps over to the statement following the
loop.

Working of a break statement :

For example :-
a=b=c=0
for i in range(1,21):
a = int (input("Enter number 1 :"))
b = int (input("Enter number 2 :"))
if b == 0:
print ("Division by zero error! Aborting!")
break
else:
c = a // b
print ("Quotient = ", c)
print ("Program over !")
Output:-
Enter number 1 : 6
Enter number 2 : 2
Quotient = 3
Enter number 1 : 8
Enter number 2 : 3
Quotient = 2
Enter number 1 : 5
Enter number 2 : 0
Division by zero error! Aborting!
Program over !

11
INFINITE LOOPS AND BREAK STATEMENT
Sometimes, programmer's create infinite loops purposely by specifying an expression which
always remains true, but for such purposely created infinite loops, they incorporate some
condition inside the loop-body on which they can break out of the loop using a break statement.
For example:-
a=2
while True :
print (a)
a*=2
if a>100:
break

THE CONTINUE STATEMENT


● The continue statement is another jump statement like the break statement as both the
statements skip over a part of the code.But the continue statement is somewhat different
from break.
● The continuous statement skips the rest of the loop statements and causes the next
iteration of the loop to take place.

Working of a continue statement :

For example:-
a=b=c=0
for i in range(0,3):
print ("Enter 2 numbers")
a = int (input("Number 1 :"))
b = int (input("Number 2 :"))
if b == 0:
print ("\n The denominator cannot be zero. Enter again !")
continue
else:
c = a // b
print ("Quotient = ", c)
12
Output:-
Enter 2 numbers
Number 1 : 5
Number 2 : 0
The denominator cannot be zero. Enter again !
Enter 2 numbers
Number 1 : 5
Number 2 : 2
Quotient = 2
Enter 2 numbers
Number 1 : 6
Number 2 : 2
Quotient = 3

LOOP ELSE STATEMENT


● The else clause of a Python loop executes when the loop terminates normally, not when
the loop is terminated because of a break statement.
● The loop-else suite executes only in the case of normal termination of the loop.

Syntax of python loops along with the else clause is as given below:-
for <variable> in <sequence> : while <test condition> :
statement 1 statement 1
statement 2 statement 2
: :
else : else :
statement(s) statement(s)

The difference in working of loops in the absence and presence


of loop else clauses:-

(A) Control flow in Python loops in the absence of loop-else change.

13

You might also like