[go: up one dir, main page]

0% found this document useful (0 votes)
14 views12 pages

Unit 2

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)
14 views12 pages

Unit 2

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/ 12

Scripting Language – Python (4330701)

Unit 2 Control Flow Structures


 Introduction to Control Structures
 A control structure (or flow of control) is a block of programming that analyses variables and chooses
a direction in which to go based on given parameters.
 A control structure is just a decision that the computer makes. So, it is the basic decision-making
process in programming and flow of control determines how a computer program will respond when
given certain conditions and parameters.
 There are two basic aspects of computer programming: data and instructions .
 To work with data, you need to understand variables and data types;
 to work with instructions, you need to understand control structures and statements.
 Flow of control through any given program is implemented with three basic types of control
structures: Sequential, Selection and Repetition.
 There are three types of Python control structures.

1. Sequential
2. Selection
3. Repetition (iteration).

1. Python Sequential: Flow of a program that executes in an order, without skipping, jumping or
switching to another block of code. You cannot execute the second instruction before executing the
instruction above it.
2. Python Iteration: Iteration repeats a body of code as long as condition is true. Python provides while
and for loop for iteration.
3. Python Selection: Selection allows programmer to ask questions, based on the reslt, perform different
action.

Prepared by: Mrs. Ami J. Patel (Lecturer in CE Dept.) Page 1


Scripting Language – Python (4330701)
 if Statement : In this control structure statement execute only if the result of condition is true .

Flowchart Syntax

if test expression:
statement(s)

 The program evaluates the test expression. If the test expression is True, then statement(s) will be
executed.
 If the test expression is False, the statement(s) is not executed.
 In Python, the body of the if statement is indicated by the indentation. The body starts with an
indentation and the first unindented line marks the end.
 Python interprets non-zero values as True. None and 0 are interpreted as False.
Example:
Example: Python if Statement
num = 3 a=3
if num > 0: if a > 2:
print(num, "is a positive number.") print(a, "is greater")
print("done")

a = -1
if a < 0:
print(a, "is smaller")
print("Finish")
Output:
3 is a positive number. Output:
3 is greater
done
-1 is smaller
Finish

Prepared by: Mrs. Ami J. Patel (Lecturer in CE Dept.) Page 2


Scripting Language – Python (4330701)
 if else Statement :When we have to select only one option from the given two option, then we use if
…else.
Flowchart Syntax

if test expression:
Body of if
else:
Body of else

 The if..else statement evaluates test expression and will execute the body of if only when the test
condition is True.
 If the condition is False, the body of else is executed. Indentation is used to separate the blocks.
Example: Python if…else Statement
num = 3 a=7
if num >= 0: b=0
print("Positive or Zero") if (a > b):
else: print("a is greater than b")
print("Negative number") else:
print("b is greater than a")
Output: Output:
Positive or Zero a is greater than b

 Nested if-else : Nested “if-else” statements mean that an “if” statement or “if-else” statement is
present inside another if or if-else block.
Syntax
if ( test condition 1):
if ( test condition 2):
Statement1
else:
Statement2
else:
Statement 3

 First test condition1 is checked, if it is true then check condition2.


 If test condition 2 is True, then statement1 is executed.
 If test condition 2 is false, then statement2 is executed.
 If test condition 1 is false, then statement3 is executed
Example: Python Nested if…else Statement
num = int(input("Enter a number: ")) a=int(input("Enter A: "))

Prepared by: Mrs. Ami J. Patel (Lecturer in CE Dept.) Page 3


Scripting Language – Python (4330701)
if num >= 0: b=int(input("Enter B: "))
if num == 0: c=int(input("Enter C: "))
print("Zero") if a>b:
else: if a>c:
print("Positive number") max=a
else: else:
print("Negative number") max=c
Output: else:
Enter a number: 12 if b>c:
Positive number max=b
else:
max=c

print("Maximum = ",max)

Output:
Enter A: 23
Enter B: 2
Enter C: 56
Maximum = 56
 if-elif-else statements
Flowchart Syntax

if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else

 The elif is short for else if. It allows us to check for multiple expressions.
 If the condition for if is False, it checks the condition of the next elif block and so on.
 If all the conditions are False, the body of else is executed.
 Only one block among the several if...elif...else blocks is executed according to the condition.
 The if block can have only one else block. But it can have multiple elif blocks.

Example: Python if-elif-else Statement

Prepared by: Mrs. Ami J. Patel (Lecturer in CE Dept.) Page 4


Scripting Language – Python (4330701)
num = -3 a,b,c=12,45,3
if num > 0: if a>b and a>c:
print("Positive number") print("a is max")
elif num == 0: elif b>a and b>c:
print("Zero") print("b is max")
else: else:
print("Negative number") print("c is max")

Output: Output:
Negative number b is max

 Switch Statement
 Python Switch case is a selection control statement.
 The witch expression evaluated once.The value of the expression is compared with the value of each
case.
 If there is a match, the associated block of code is executed.
 Python doesnot have its inbuilt switch case statement.
 We have to implement using different methods.
 Using Function and Lamda Function
 Using Dictionary Mapping
 Using Python classes
 Using if-elif-else
Using Dictionary Mapping:
def monday():
return "monday"
def tuesday():
return "tuesday"
def wednesday():
return "wednesday"
def thursday():
return "thursday"
def friday():
return "friday"
def saturday():
return "saturday"
def sunday():
return "sunday"
def default():
return "Incorrect day"

Day = {
1: monday,
2: tuesday,
3: wednesday,
4: thursday,
5: friday,
6: saturday,

Prepared by: Mrs. Ami J. Patel (Lecturer in CE Dept.) Page 5


Scripting Language – Python (4330701)
7: sunday
}

def DayName(dayofWeek):
return Day.get(dayofWeek,default)( )

print(DayName (3))
print(DayName (8))
Output:
Wednesday
Incorrect day

 First create different functions which return Day name.


 We create a dictionary in which stored different key-value pair.
 After that create main function which takes user input for finding day name.
 At last, called the function to print the desired output
 loop
 A loop statement allows us to execute a statement or group of statements multiple times as long as the
condition is true.
 Repeated execution of a set of statements with the help of loops is called iteration.
 Loops statements are used when we need to run same code again and again, each time with a different
value.
 In Python Iteration (Loops) statements are of three types:
1. While Loop
2. For Loop
3. Nested For Loops
 while loop
Flowchart Syntax

while test_expression:
Body of while

 Loops are either infinite or conditional.


 In the while loop, test expression is checked first.
 The body of the loop is entered only if the test_expression evaluates to True.

Prepared by: Mrs. Ami J. Patel (Lecturer in CE Dept.) Page 6


Scripting Language – Python (4330701)
 After one iteration, the test expression is checked again. This process continues until the
test_expression evaluates to False.
 The statements that are executed inside while can be a single line of code or a block ofmultiple
statements
Example:
x=1 a=5
while(x<=5): b=1
print(x) while b <= 5:
x+=1 print (a,"*",b,"=",a*b)
b+=1

Output: Output:
1 5*1=5
2 5 * 2 = 10
3 5 * 3 = 15
4 5 * 4 = 20
5 5 * 5 = 25

 for loop
 Python for loop is used for repeated execution of a group of statements for the desired number of
times.
 It iterates over the items of lists, tuples, strings, the dictionaries and other iterable objects

Flowchart:

Example:
for i in range(1,6): a=[10,12,13,14]
print(i) for i in a:

Prepared by: Mrs. Ami J. Patel (Lecturer in CE Dept.) Page 7


Scripting Language – Python (4330701)
print(i)
Output: Output:
1 10
2 12
3 13
4 14
5
sum of 1 to 5 no Print Multiplication table
sum=0 b=1
for i in range(1,6): a=int(input("enter n:"))
sum=sum+i for b in range(1,6):
print(sum) print (a,"*",b,"=",a*b)

Output: Output:
15 enter n:4
4 * 1=4
4 * 2=8
4 * 3=12
4 * 4=16
4 * 5=20
n=int(input ("enter n:")) n=int(input ("enter n"))
fact=1 n1=0
for i in range(1,n+1): n2=1
fact=fact*i print (n1)
print ("factorial=",fact) print(n2)
for i in range(3,n+1):
n3=n1+n2
print(n3)
n1=n2
n2=n3
Output:
enter n:3 Output:
factorial=6 0
1
1
2
3
5
 Nested loops
 In Python programming language there are two types of loops which are for loop and while loop.
 Using these loops we can create nested loops in Python.
 Nested loops mean loops inside a loop. For example, while loop inside the for loop, for loop inside the
for loop, etc.
Syntax: Syntax:

for var in sequence: while expression:


for var in sequence: while expression:
statements(s) statement(s)

Prepared by: Mrs. Ami J. Patel (Lecturer in CE Dept.) Page 8


Scripting Language – Python (4330701)
statements(s) statement(s)

Example :1(using for) Example :2(using for)

rows = 5 rows = 5
for i in range(1, rows + 1): for i in range(1, rows + 1):
for j in range(1, i + 1): for j in range(1, i + 1):
print('*',end=' ') print(j,end=' ')
print(‘ ‘) print(‘ ‘)

Output: Output:

* 1
** 12
*** 123
**** 1234
***** 12345
Example :3 (using while) Example :4(using while)
i=0 i=0
j=0 j=0
row=5 row=5

while(i<=row): while(i<=row):
while(j<i): while(j<i):
print('*',end="") print(i,end="")
j+=1 j+=1
j=0 j=0
i+=1 i+=1
print('') print('')

Output: Output:

* 1
** 22
*** 333
**** 4444
***** 55555
Example :5 Example :6
rows = 5 rows = 5
for i in range(1, rows + 1): n=65
for j in range(1, i + 1): for i in range(1, rows + 1):
print(i,end=' ') for j in range(1, i + 1):
print(‘\r’) ch=chr(n)

Prepared by: Mrs. Ami J. Patel (Lecturer in CE Dept.) Page 9


Scripting Language – Python (4330701)
print(ch,end=' ')
Output: n+=1
1 print('\r')
22 Output:
333
4444 A
55555 BB
CCC
DDDD
EEEEE
rows=5 rows=5
k=0 k=rows-1
for i in range(1, rows+1): for i in range(1, rows+1):
for j in range(1, k+1): for j in range(1, k+1):
print(end=" ") print(end=" ")
k=k-1
for j in range(1, rows+1-k):
print("*",end=" ") for j in range(1, i+1):
k=k+1 print("*",end=" ")
print(" ")
Output: print(" ")
*****
**** Output:
*** *
** * *
* * * *
* * * *
* * * * *

 break statement
 The break statement terminates the loop containing it. Control of the program flows to the statement
immediately after the body of the loop.
 If the break statement is inside a nested loop (loop inside another loop), the break statement will
terminate the innermost loop.The break statement can be used in both while and for loops.

Syntax:

break

Prepared by: Mrs. Ami J. Patel (Lecturer in CE Dept.) Page 10


Scripting Language – Python (4330701)
Example:
for i in range(1,11): i=1
print(i) while(i<=10):
if i == 2: print(i)
break if(i==5):
break
i=i+1

Output: Output:
1 1
2 2
3
4
5
 continue statement
 The continue statement in Python returns the control to the beginning of the while loop.
The continue statement rejects all the remaining statements in the current iteration of the loop and
moves the control back to the top of the loop.

 The continue statement can be used in both while and for loops.
Syntax:

continue

Example:
n=int(input("enter n")) i=0
for i in range(1,n): while(i<5):
if(i==5): i=i+1
continue if(i==3):
print("%d" %i) continue
print(i)
Output:
enter n10 Output:
12346789 1 24 5
 Pass Statement
 In Python programming, the pass statement is a null statement.
 The difference between a comment and a pass statement in Python is that while the interpreter ignores a
comment entirely, pass is not ignored.

Prepared by: Mrs. Ami J. Patel (Lecturer in CE Dept.) Page 11


Scripting Language – Python (4330701)
 Nothing happens when the pass is executed. It results in no operation (NOP).
 When the user does not know what code to write, so user simply places pass at that line.
Sometimes, pass is used when the user doesn’t want any code to execute. So user can simply
place pass where empty code is not allowed, like in loops, function definitions, class definitions, or in if
statements. So using pass statement user avoids this error.
 Syntax:
pass
 Example
a= {'h', 'e', 'l', 'l','o'}
for val in a:
pass

Prepared by: Mrs. Ami J. Patel (Lecturer in CE Dept.) Page 12

You might also like