0% found this document useful (0 votes)
10 views62 pages

Chap_6 Flow of Control

The document provides an overview of flow control in Python, detailing types of statements including empty, simple, and compound statements. It explains control flow mechanisms such as sequence, selection (if statements), and iteration (loops), along with examples of decision-making statements like if, if-else, and nested if-else statements. Additionally, it covers practical applications and exercises to reinforce understanding of these concepts.

Uploaded by

8g.aditya.m.5570
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views62 pages

Chap_6 Flow of Control

The document provides an overview of flow control in Python, detailing types of statements including empty, simple, and compound statements. It explains control flow mechanisms such as sequence, selection (if statements), and iteration (loops), along with examples of decision-making statements like if, if-else, and nested if-else statements. Additionally, it covers practical applications and exercises to reinforce understanding of these concepts.

Uploaded by

8g.aditya.m.5570
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 62

Flow of control

Learning
Outcomes
 Types of statements in Python
 Statement of Flow Control
 Program Logic Development
Tools
 if statement of Python
 Repetition of Task - A necessity
 The range() function
 Iteration / Looping statement
 break and continue statement
Types o f Statement in Python

 Statements are the instructions given to


computer to perform any task. Task may be
simple calculation, checking the condition or
repeating action.
 Python supports 3 types of statement:
 Empty statement
 Simple statement
 Compound statement
Empty Statement

 It is the simplest statement i.e. a statement


which does nothing. It is written by using
keyword – pass
 Whenever python encountered pass it does
nothing and moves to next statement in
flow of control
 Required where syntax of python required
presence of a statement but where the logic
of program does. More detail will be
explored with loop.
Simple Statement

 Any single executable statement in Python


is simple statement. For e.g.
 Name = input(“enter your name “)
 print(name)
Compound Statement

 It represent group of statement executed as


unit. The compound statement of python
are written in a specific pattern:

Compound_Statement_Header :
indented_body containing
multiple simple or compound
statement
Compound Statement has:

 Header which begins with


keyword/function and ends with colon(:)
 A body contains of one or more python
statements each indented inside the header
line. All statement in the body or under any
header must be at the same level of
indentation.
Statement Flow Control

 In python program statement may execute


in a sequence, selectively or iteratively.
Python
programmin support 3 Control
g Flow
statements:
1. Sequence
2. Selection
3. Iteration
Sequence
 It means python statements are executed
one after another i.e. from the first
statement to last statement without any
jump.
Selection
 It means execution of statement will depend
upon the condition. If the condition is true
then it will execute Action 1 otherwise
Action 2. In Python we use if to perform
selection
Selection

Action
1

Condition True Statement Statement


? 1 2

Fals
e

Statement 1
Action

Statement
2
2
Selection

 We apply Decision making or selection in our


real life also like if age is 18 or above person
can vote otherwise not. If pass in every
subject is final exam student is eligible for
promotion.
 You can think of more real life examples.
Iteration - Looping

 Iteration means repeating of statement


depending upon the condition. Till the time a
condition is True statements are repeated again
and again. Iteration construct is also known as
Looping construct
 In real world we are using Looping construct
like learning table of any number we multiply
same number from 1 to 10, Washing clothes
using washing machine till the time is over, our
school hours starts from assembly to last
period, etc.
Iteration - Looping

Fals
Condition e Exit from
? iteration

Tru
e

Statement
1
Loop
Body Python supports for
Action

and while statement


Statement
2
2

for Looping construct


Control
Statements

Control statements are used to control the


flow of execution depending upon the specified
condition/logic.

There are three types of control statements.

1. Decision Making Statements


2. Iteration Statements (Loops)
3. Jump Statements (break, continue, pass)
Decision Making
Statement

Decision making statement used to control


the flow of execution of program depending upon
condition.

There are three types decision making


of statement.
1. if statements
2. if-else statements
3. Nested if-else
statement
Decision Making
Statement
1. if statements
An if statement is a programming conditional
statement that, if proved true, performs a
function or displays information.
Decision Making
Statement
1. if statements
Syntax:
if(condition):
statement
[statements]
e.g.
noofbooks = 2
if (noofbooks
== 2):
print('You have ')
print(‘two books’)
print(‘outside of if statement’)
Output
You have two books
Note:To indicate a block of code in Python, you must indent each line of
the block by the same amount. In above e.g. both print statements are
part of if condition because of both are at same level indented but not
the third print statement.
Decision Making
Statement
2. if-else Statements
#find absolute value
a=int(input("enter a
number")) if(a<0):
a=a*-1
print(a)

#it will always return value in


positive
Decision Making
Statement
1. if statements
Using logical operator in if statement
x=1

y=2
if(x
==1
an
d
y==
2):
p
ri
n
t(
‘c
o
n
di
ti
Decision Making
Statement
2. if-else Statements
If-else statement executes some code if the test
expression is true (nonzero) and some other code if
the test expression is false.
Decision Making
Statement
2. if-else Statements
Syntax:
if(condition):
statements
else:
statements
e.g.
a=10
if(a
<
100)
:
pri
nt(
‘le
ss
th
an
10
Decision Making
Statement

3. Nested if-else statement


The nested if...else statement allows you to check for
multiple test expressions and execute different codes
for more than two conditions.
Decision Making
Statement
3. Nested if-else statement
Syntax
If (condition):
statement
s elif (condition):
st
atements
else:
st
atements
E.G.
num = float(input("Enter a
number: ")) if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative
number")
OUTPUT
Enter a
Decision Making
Statement
3.Nested if-else Statements
#sort 3 numbers
first = int(input("Enter the first number: "))
second = int(input("Enter the second number: "))
third = int(input("Enter the third number: "))
small = 0
middle = 0
large = 0
if first < third and first < second:
small = first
if second < third and second < first:
small = second
else:
small = third
elif first < second and first < third:
middle = first
if second > first and second <
third:
middle = second
else:
middle = third
elif first > second and first > third:
large = first
if second > first and second > third:
large = second
else:
large = third
print("The numbers in accending
order are: ", small, middle, large)
Decision Making
Statement
3.Nested if-else Statements
#Check leap year / divisibility
year = int(input("Enter a year: "))

if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap
year".format(year))
else:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap
year".format(year))
i f Statement o f Python
 ‘if’ statement of python is used to execute
statements based on condition. It tests the
condition and if the condition is true it
perform certain action, we can also provide
action for false situation.
 if statement in Python is of many forms:
 if without false statement
 if with else
 if with elif
 Nested if
Simple “ i f ”
 In the simplest form if statement in Python
checks the condition and execute the
statement if the condition is true and do
nothing if the condition is false.
 Syntax: All statement
belonging to if
if condition: must have same
indentation
Statement1 level
Statements
* * if ….
statement is compound statement having
header and a body containing intended
statement.
Points to remember with “ i f ”

 It must contain valid condition


which evaluates to either True or False
 Condition must followed by Colon (:) , it
is mandatory
 Statement inside if must be at
same indentation level.
Input monthly sale of employee and give bonus of
10% if sale is more than 50000 otherwise bonus
will be 0
bonus = 0
sale = int(input("Enter Monthly
Sales :")) if sale>50000:
bonus=sale * 10 /100
print("Bonus = " + str(bonus))
1.WAP to enter 2 number and print the largest
number
2.WAP to enter 3 number and print the largest
number
1. WAP to enter 2 number and print the largest
number

n1 = int(input("Enter first number "))


n2 = int(input("Enter second number
")) large = n1
if (large<n2):
large=n2
print("Largest number is ", large)
2. WAP to enter 3 number and print the largest
number

n1 = int(input("Enter first number "))


n2 = int(input("Enter second number
"))
n3 = int(input("Enter third number
")) large = n1
if (large<n2):
large=n
2
if(large<n3):
lar
if with else

 if with else is used to test the condition and


if the condition is True it perform certain
action and alternate course of action if the
condition is false.
 Syntax:
if condition:
Statements
else:
Statements
Input Age of personand print whetherthe person
is eligible for voting or not

age = int(input("Enter your age


")) if age>=18:
print("Congratulation! you
are eligible for voting ")
else:
print("Sorry! You are not
eligible for voting")
To
D
1.o…
WAP to enter any number and check it is even
or odd
2. WAP to enter any age and check it is teenager
or not
3. WAP to enter monthly sale of Salesman and
give him commission i.e. if the monthly sale is
more than 500000 then commision will be 10%
of monthly sale otherwise 5%
4. WAP to input any year and check it is Leap Year
or Not
5. WAP to Input any number and print
Absolute value of that number
6. WAP to input any number and check it is
positive or negative number
if with elif
 if with elif is used where multiple chain of condition is
to be checked. Each elif must be followed by condition:
and then statement for it. After every elif we can give
else which will be executed if all the condition
evaluates to false
 Syntax:
if condition:
Statement
s elif condition:
Statement
s elif condition:
Stat
ements
else:
Stat
Input temperature of water and print its physical state

temp = int(input("Enter temperature of water


")) if temp>100:
print("Gaseous
State") elif temp<0:
print("Solid
State")
else:
print("Liquid
State")
Input 3 side of triangle and print the type of triangle –
Equilateral, Scalene, Isosceles

s1 = int(input("Enter side
1")) s2 = int(input("Enter
side 2")) s3 =
int(input("Enter side 3")) if
s1==s2==s3:
print("Equilateral")
elif s1!=s2!=s3!=s1:
print("Scale
ne")
else:
print("Isosce
les")
Program to calculate and print roots of a quadratic equation:
ax2+bx+c=0(a!=0)

import math
print("For quadratic equation, ax**2 + bx + c =
0, enter coefficients ")
a = int(input("enter
a")) b =
int(input("enter b"))
c = int(input("enter
c")) if a==0:
print("Value of
",a," should not
be zero")
print("Aborting!!!
Program to calculate and print roots of a quadratic equation:
ax2+bx+c=0(a!=0)

if delta >0:
root1=(-b+math.sqrt(delta))/(2*a)
root2=(-b-math.sqrt(delta))/(2*a)
print("Roots are Real and UnEqual")
print("Root1=",root1,"Root2=",root
2)
elif delta==0:
root1=-b/(2*a)
print("Roots are Real and Equal")
print("Root1=",root1,"Root2=",root
1)
else:
To
D o…
1. WAP to enter marks of 5 subject and calculate total, percentage
and also division.
Percentage Division
>=60 First
>=45 Second
>=33 Third
otherwise Failed
2. WAP to enter any number and check it is positive, negative or
zero
number
3.WAP to enter Total Bill amount and calculate discount as per
given table and also calculate Net payable amount (total bill –
discount)
>=20000 15% of Total
Total Bill Discount
>=15000 Bill 10% of
>=10000 Total Bill 5% of
otherwise Total Bill 0 of
Total Bill
To
D
4.oWAP
… to enter Bill amount and ask the user the payment
mode and give the discount based on payment mode. Also
display net payable amount
Mode Discount
Credit Card 10% of bill
Debit Card amount 5% of bill
Net amount 2% of
Banking bill amount 0
5.WAPotherwise
to enter two number and ask the operator (+ - * / )
from the user and display the result by applying operator on
the two number
6. WAP to enter any character and print it is Upper Case,
Lower Case, Digit or symbol
7.WAP to enter 3 number and print the largest number
8.WAP to input day number and print corresponding day
name for e.g if input is 1 output should be SUNDAY and so
on.
Nested i f
 In this type of “if” we put if within another if as a
statement of it. Mostly used in a situation where
we want different else for each condition. Syntax:
if condition1:
if condition2:
statements
else:
stateme
nts elif condition3:
stat
ements
else:
stat
WAP to check entered year is leap year or not

year = int(input("Enter any year


")) if year % 100 == 0:
if year % 400 == 0:
print("Year is Leap
Year ")
else:
print("Year is not Leap
Year") elif year %4 ==0:
print("Year is
Leap Year ")
else:
print("Year is
not Leap Year")
Program to read three numbers and prints them in
ascending order
x = int(input("Enter first number "))
y = int(input("Enter second number "))
z = int(input("Enter third number "))
if y>=x<=z:
if y<=z:
min,mid,max=x,y,
z
else:
min,mid,max=x,z,
y
elif x>=y<=z:
if x<=z:
min,mid,max=y,x,
z
else:
min,mid,max=y,z,
x
elif x>=z<=y:
if x<=y:
min,mid,max=z,x,
y
Storing Condition

 In a program if our condition is complex and


it is repetitive then we can store the
condition in a name and then use the
named condition in if statement. It makes
program more readable.
 For e.g.
 x_is_less=y>=x<=z
 y_is_less=x>=y<=z
 Even = num%2==0
Iteration Statements (Loo

Iteration statements(loop) are used to execute a block


of statements as long as the condition is true.
Loops statements are used when we need to run same
code again and again.
Python Iteration (Loops) statements are of three type :-

1. While Loop

2. For Loop

3. Nested For Loops


Iteration Statements
•1. While Loop (Loops)
•It is used to execute a block of statement as long
as a
•given condition is true. And when the condition
become false, the control will come out of the loop.
The condition is checked every time at the beginning
of the loop.
•Syntax
•while (condition):
• stmt
[stmts] Output
x=1 1
•e.g.
while (x <= 4): 2
print(x) 3
4
x=x+1
Iteration Statements (Loops)
While Loop continue
While Loop With Else
e.g.

x=1
while (x < 3):
print('inside while loop value of x is ',x)
x=x+1
else:
print('inside else value of x is ', x)

Output
inside while loop value of x is 1
inside while loop value of x is
2 inside else value of x is 3
*Write a program in python to
find out the factorial of a given
number
Iteration Statements
(Loops)
While Loop continue
Infinite While Loop
e.g.
x=5
while (x == 5):
print(‘inside loop')

Output
Inside loop
Inside
loop


Iteration Statements
(Loops)
2. For Loop
It is used to iterate over items of any sequence, such as a list
or a string.
Syntax
for val in sequence:
statements

e.g.
for i in range(3,5):
print(i)

Output
3
4
Iteration Statements (Loops)

2. For Loop continue


Example programs
for i in range(5,3,-1):
print(i)

Output
5
4
range() Function
Parameters
start: Starting number
of the sequence.
stop: Generate numbers up to, but not including this number.
step(Optional): Determines the increment between each numbers in
the sequence.
Iteration Statements (Loo

2. For Loop continue


Example programs with range() and len() function
fruits = ['banana', 'apple',
'mango'] for index in
range(len(fruits)):
print ('Current fruit :',
fruits[index])
range() with len() Function
Parameters
Iteration Statements (Loop
2. For Loop continue
For Loop With Else
e.g.
for i in range(1, 4):
print(i)
else: # Executed because no break
in for print("No Break")

Output
1
2
3
No Break
Iteration Statements
(Loops)
2. For Loop continue
Nested For Loop
e.g.
for i in range(1,3):
for j in range(1,11):
k=i*j
print (k, end=' ')
print()

Output
123456789
10
2 4 6 8 10 12 14
16 18 20
Iteration Statements
(Loops)
2. For Loop continue
Factorial of a number
factorial = int(input(‘enter a number’))

# check if the number is negative, positive or zero


if num < 0:
print("Sorry, factorial does not exist for negative
numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial
of",num,"is",factorial)
Iteration Statements
(Loops)
2. For Loop continue
Compound Interest calculation
n=int(input("Enter the principle amount:"))
rate=int(input("Enter the rate:"))
years=int(input("Enter the number of years:"))

for i in range(years):
n=n+((n*rate)/100)
print(n)
Iteration Statements
(Loops)
3. Jump Statements

Jump statements are used to transfer the program's


control from one location to another. Means these are
used to alter the flow of a loop like - to skip a part of a
loop or terminate a loop

There are three types of jump statements used in


python.
1.br
eak
2.continue
3.pass
Iteration Statements (Loops)
1.break
it is used to terminate the loop.
e.g.
for val in "string":
if val == "i":
break
print(val)

print("Th
e end")

Output
s

t
Iteration Statements
(Loops)
2.continue
It is used to skip all the remaining statements
in the loop and move controls back to the top of
the loop.
e.g.
for val in "init":
if val == "i":
continue
print(val)
print("The
end")

Outp
ut n
t
The
end
Iteration Statements
(Loops)
3. pass Statement
This statement does nothing. It can be used when a
statement is required syntactically but the program
requires no action.
Use in loop
while True:
pass # Busy-wait for keyboard interrupt (Ctrl+C)
In function
It makes a controller to pass by without executing any code.
e.g.
def myfun():
pass #if we don’t use pass here then error message will be shown
print(‘my program')

OUTPUT
My program
Iteration Statements
(Loops)
3. pass Statement continue
e.g.
for i in 'initial':
if(i == 'i'):
pass
else:
print(i)

OUTPUT
n

L
NOTE : continue forces the loop to start at the next iteration
while pass means "there is no code to execute here" and will

You might also like