SlideShare a Scribd company logo
2
Control flow statements
• Decision control flow statements (if, if…..else, if…….elif….else, nested
if)
• Loop(while, for)
• continue statement
• break statement
02-11-2021 meghav@kannuruniv.ac.in 2
Most read
6
Decision making
• if…elif…else statements
Example
a = 15
b = 15
if a > b:
print("a is greater")
elif a == b:
print("both are equal")
else:
print("b is greater")
Output:
both are equal
02-11-2021 meghav@kannuruniv.ac.in 6
Most read
10
LOOPS
for loop
Example Program 1:
#Program to find the sum of all numbers stored in a list
numbers = [2,4,6,8,10]
# variable to store the sum
sum=0
# iterate over the list
for item in numbers:
sum = sum + item
#print the sum
print(“The sum is",sum)
Output
The sum is 30
02-11-2021 meghav@kannuruniv.ac.in 10
Most read
Python Programming –Part III
Megha V
Research Scholar
Kannur University
02-11-2021 meghav@kannuruniv.ac.in 1
Control flow statements
• Decision control flow statements (if, if…..else, if…….elif….else, nested
if)
• Loop(while, for)
• continue statement
• break statement
02-11-2021 meghav@kannuruniv.ac.in 2
Decision making
• Decision making is required when we want to execute a code only if a certain condition is
satisfied.
1. if statement
Syntax:
if test expression:
statement(s)
Example:
a = 15
if a > 10:
print("a is greater")
Output:
a is greater
02-11-2021 meghav@kannuruniv.ac.in 3
Decision making
2. if……else statements
• Syntax
if expression:
body of if
else:
body of else
• Example
a = 15
b = 20
if a > b:
print("a is greater")
else:
print("b is greater")
Output:
b is greater
02-11-2021 meghav@kannuruniv.ac.in 4
Decision making
3. if…elif…else statements
elif - is a keyword used in Python replacement of else if to place another
condition in the program. This is called chained conditional.
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, body of else is executed.
• Syntax
if test expression:
body of if
elif test expression:
body of elif
else:
body of else
02-11-2021 meghav@kannuruniv.ac.in 5
Decision making
• if…elif…else statements
Example
a = 15
b = 15
if a > b:
print("a is greater")
elif a == b:
print("both are equal")
else:
print("b is greater")
Output:
both are equal
02-11-2021 meghav@kannuruniv.ac.in 6
Decision making
4. Nested if statements
if statements inside if statements, this is called nested if statements.
Example:
x = 41
if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")
Output:
Above ten,
and also above 20!
02-11-2021 meghav@kannuruniv.ac.in 7
LOOPS
• There will be situations when we need to execute a block of code several
times.
• Python provides various control structures that allow repeated execution
for loop
while loop
for loop
• A for loop is used for iterating over a sequence (that is either a list, a tuple, a
dictionary, a set, or a string).
• With the for loop we can execute a set of statements, once for each item in a
list, tuple, set etc.
02-11-2021 meghav@kannuruniv.ac.in 8
LOOPS
for loop
Syntax:
for item in sequence:
Body of for
• Item is the variable that takes the value of the item inside the sequence of each
iteration.
• The sequence can be list, tuple, string, set etc.
• The body of for loop is separated from the rest of the code using indentation.
02-11-2021 meghav@kannuruniv.ac.in 9
LOOPS
for loop
Example Program 1:
#Program to find the sum of all numbers stored in a list
numbers = [2,4,6,8,10]
# variable to store the sum
sum=0
# iterate over the list
for item in numbers:
sum = sum + item
#print the sum
print(“The sum is",sum)
Output
The sum is 30
02-11-2021 meghav@kannuruniv.ac.in 10
LOOPS
for loop
Example Program 2:
flowers = [‘rose’,’lotus’,’jasmine’]
for flower in flowers:
print(‘Current flower :’,flower)
Output
Current flower : rose
Current flower : lotus
Current flower : jasmine
02-11-2021 meghav@kannuruniv.ac.in 11
LOOPS
• for loop with range() function
• We can use range() function in for loops to iterate through a sequence of numbers,
• It can be combined with len() function to iterate through a sequence using indexing
• len() function is used to find the length of a string or number of elements in a list,
tuple, set etc.
• Example program
flowers=[‘rose’,’lotus’,’jasmine’]
for i in range(len(flowers)):
print(‘Current flower:’, flowers[i])
Output
Current flower : rose
Current flower : lotus
Current flower : jasmine
02-11-2021 meghav@kannuruniv.ac.in 12
range() function
for x in range(6):
print(x)
• Note that range(6) is not the values of 0 to 6, but the values 0 to 5.
• The range() function defaults to 0 as a starting value, however it is possible to
specify the starting value by adding a parameter: range(2, 6), which means values
from 2 to 6 (but not including 6)
• The range() function defaults to increment the sequence by 1, however it is
possible to specify the increment value by adding a third parameter: range(2,
30, 3):
• increment the sequence with 3 (default is 1):
for x in range(2, 30, 3):
print(x)
02-11-2021 meghav@kannuruniv.ac.in 13
LOOPS
enumerate(iterable,start=0)function
• The enumerate() function takes a collection (eg tuple) and returns it as an enumerate object
• built in function returns an e
• numerate object
• The parameter iterable must be a sequence, an iterator, or some other objects like list which supports iteration
Example Program
# Demo of enumerate function using list
flowers = [‘rose’,’lotus’,’jasmine’,’sunflower’]
print(list(enumerate(flowers)))
for index,item in enumerate(flowers)
print(index,item)
Output
[(0,’rose’),(1,’lotus’),(2,’jasmine’),(3,’sunflower’)]
0 rose
1 lotus
2 jasmine
3 sunflower
02-11-2021 meghav@kannuruniv.ac.in 14
LOOPS
2. while loop
Used to iterate over a block of code as long as the test expression (condition) is True.
Syntax
while test_expression:
Body of while
Example Program
# Program to find the sum of first N natural numbers
n=int(input(“Enter the limit:”))
sum=0
i=1
while(i<=n)
sum = sum+i
i=i+1
print(“Sum of first ”,n,”natural number is”, sum)
Output
Enter the limit: 5
Sum of first 5 natural number is 15
02-11-2021 meghav@kannuruniv.ac.in 15
LOOPS
while loop with else statement
Example Program
count=1
while(count<=3)
print(“python programming”)
count=count+1
else:
print(“Exit”)
print(“End of program”)
Output
python programming
python programming
python programming
Exit
End of program
02-11-2021 meghav@kannuruniv.ac.in 16
Nested Loops
• Sometimes we need to place loop inside another loop
• This is called nested loops
Syntax for nested for loop
for iterating_variable in sequence:
for iterating_variable in sequence:
statement(s)
statement(s)
Syntax for nested while loop
while expression:
while expression:
statement(s)
statement(s)
02-11-2021 meghav@kannuruniv.ac.in 17
CONTROL STATEMENTS
• Control statements change the execution from normal sequence
• Python supports the following 3 control statements
• break
• continue
• pass
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 it is inside a nested loop, break will terminate the innermost loop
• It can be used with both for and while loops.
02-11-2021 meghav@kannuruniv.ac.in 18
CONTROL STATEMENTS
break statement
• Example
#Demo of break
for i in range(2,10,2):
if(i==6):break
print(i)
print(“End of program”)
Output
2
4
End of program
Here the for loop is intended to print the even numbers from 2 to 10. The if condition checks
whether i=6. If it is 6, the control goes to the next statement after the for loop.
02-11-2021 meghav@kannuruniv.ac.in 19
CONTROL STATEMENTS
continue statement
• The continue statement is used to skip the rest of the code inside a
loop for the current iteration only.
• Loop does not terminate but continues with next iteration
• continue returns the control to the beginning of the loop
• rejects all the remaining statements in the current iteration of the
loop
• It can be used with for loop and while loop
02-11-2021 meghav@kannuruniv.ac.in 20
CONTROL STATEMENTS
continue statement
Example
for letter in ‘abcd’:
if(letter==‘c’):continue
print(letter)
Output
a
b
d
02-11-2021 meghav@kannuruniv.ac.in 21
CONTROL STATEMENTS
pass statement
• In Python pass is a null statement
• while interpreter ignores a comment entirely, pass is not ignored
• nothing happens when it is executed
• used a a placeholder
• in the case we want to implement a function in future
• Normally function or loop cannot have an empty body.
• So when we use the pass statement to construct a body that does nothis
Example:
for val in sequence:
pass
02-11-2021 meghav@kannuruniv.ac.in 22
Reading input
• The function input() consider all input as strings.
• To convert the input string to equivalent integers, we need to use
function explicitly
• Example
cost = int(input(Enter cost price:’))
profit = int(input(Enter profit:’))
02-11-2021 meghav@kannuruniv.ac.in 23
LAB ASSIGNMENT
• Write a python program to find maximum of 3 numbers using if….elif…else
statement
• Program to find largest among two numbers using if…else
• Program to find the sum of first n positive integers using for loop
• Program to print prime numbers using for loop
• Python program to print prime numbers using while loop
• Program to print the elements in a list and tuple in reverse order
02-11-2021 meghav@kannuruniv.ac.in 24

More Related Content

What's hot (20)

Java Foundations: Lists, ArrayList<T>
Java Foundations: Lists, ArrayList<T>Java Foundations: Lists, ArrayList<T>
Java Foundations: Lists, ArrayList<T>
Svetlin Nakov
 
Python programming : Strings
Python programming : StringsPython programming : Strings
Python programming : Strings
Emertxe Information Technologies Pvt Ltd
 
Python lambda functions with filter, map & reduce function
Python lambda functions with filter, map & reduce functionPython lambda functions with filter, map & reduce function
Python lambda functions with filter, map & reduce function
ARVIND PANDE
 
Python : Functions
Python : FunctionsPython : Functions
Python : Functions
Emertxe Information Technologies Pvt Ltd
 
Embedded C - Day 2
Embedded C - Day 2Embedded C - Day 2
Embedded C - Day 2
Emertxe Information Technologies Pvt Ltd
 
Iteration
IterationIteration
Iteration
Pooja B S
 
Java Foundations: Maps, Lambda and Stream API
Java Foundations: Maps, Lambda and Stream APIJava Foundations: Maps, Lambda and Stream API
Java Foundations: Maps, Lambda and Stream API
Svetlin Nakov
 
Arrays
ArraysArrays
Arrays
archikabhatia
 
Python
PythonPython
Python
Kumar Gaurav
 
Python numbers
Python numbersPython numbers
Python numbers
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
Functions in advanced programming
Functions in advanced programmingFunctions in advanced programming
Functions in advanced programming
VisnuDharsini
 
String Manipulation in Python
String Manipulation in PythonString Manipulation in Python
String Manipulation in Python
Pooja B S
 
Java Foundations: Arrays
Java Foundations: ArraysJava Foundations: Arrays
Java Foundations: Arrays
Svetlin Nakov
 
The Ring programming language version 1.4.1 book - Part 29 of 31
The Ring programming language version 1.4.1 book - Part 29 of 31The Ring programming language version 1.4.1 book - Part 29 of 31
The Ring programming language version 1.4.1 book - Part 29 of 31
Mahmoud Samir Fayed
 
15. Streams Files and Directories
15. Streams Files and Directories 15. Streams Files and Directories
15. Streams Files and Directories
Intro C# Book
 
CBSE Class 12 Computer practical Python Programs and MYSQL
CBSE Class 12 Computer practical Python Programs and MYSQL CBSE Class 12 Computer practical Python Programs and MYSQL
CBSE Class 12 Computer practical Python Programs and MYSQL
Rishabh-Rawat
 
Python programing
Python programingPython programing
Python programing
hamzagame
 
Map, Reduce and Filter in Swift
Map, Reduce and Filter in SwiftMap, Reduce and Filter in Swift
Map, Reduce and Filter in Swift
Aleksandras Smirnovas
 
Arrays in python
Arrays in pythonArrays in python
Arrays in python
Lifna C.S
 
If You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongIf You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are Wrong
Mario Fusco
 
Java Foundations: Lists, ArrayList<T>
Java Foundations: Lists, ArrayList<T>Java Foundations: Lists, ArrayList<T>
Java Foundations: Lists, ArrayList<T>
Svetlin Nakov
 
Python lambda functions with filter, map & reduce function
Python lambda functions with filter, map & reduce functionPython lambda functions with filter, map & reduce function
Python lambda functions with filter, map & reduce function
ARVIND PANDE
 
Java Foundations: Maps, Lambda and Stream API
Java Foundations: Maps, Lambda and Stream APIJava Foundations: Maps, Lambda and Stream API
Java Foundations: Maps, Lambda and Stream API
Svetlin Nakov
 
Functions in advanced programming
Functions in advanced programmingFunctions in advanced programming
Functions in advanced programming
VisnuDharsini
 
String Manipulation in Python
String Manipulation in PythonString Manipulation in Python
String Manipulation in Python
Pooja B S
 
Java Foundations: Arrays
Java Foundations: ArraysJava Foundations: Arrays
Java Foundations: Arrays
Svetlin Nakov
 
The Ring programming language version 1.4.1 book - Part 29 of 31
The Ring programming language version 1.4.1 book - Part 29 of 31The Ring programming language version 1.4.1 book - Part 29 of 31
The Ring programming language version 1.4.1 book - Part 29 of 31
Mahmoud Samir Fayed
 
15. Streams Files and Directories
15. Streams Files and Directories 15. Streams Files and Directories
15. Streams Files and Directories
Intro C# Book
 
CBSE Class 12 Computer practical Python Programs and MYSQL
CBSE Class 12 Computer practical Python Programs and MYSQL CBSE Class 12 Computer practical Python Programs and MYSQL
CBSE Class 12 Computer practical Python Programs and MYSQL
Rishabh-Rawat
 
Python programing
Python programingPython programing
Python programing
hamzagame
 
Arrays in python
Arrays in pythonArrays in python
Arrays in python
Lifna C.S
 
If You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongIf You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are Wrong
Mario Fusco
 

Similar to Python programming –part 3 (20)

python ppt.pptx
python ppt.pptxpython ppt.pptx
python ppt.pptx
ssuserd10678
 
Python_Module_2.pdf
Python_Module_2.pdfPython_Module_2.pdf
Python_Module_2.pdf
R.K.College of engg & Tech
 
ppt3-conditionalstatementloopsdictionaryfunctions-240731050730-455ba0fa.ppt
ppt3-conditionalstatementloopsdictionaryfunctions-240731050730-455ba0fa.pptppt3-conditionalstatementloopsdictionaryfunctions-240731050730-455ba0fa.ppt
ppt3-conditionalstatementloopsdictionaryfunctions-240731050730-455ba0fa.ppt
avishekpradhan24
 
PPT3-CONDITIONAL STATEMENT LOOPS DICTIONARY FUNCTIONS.ppt
PPT3-CONDITIONAL STATEMENT LOOPS DICTIONARY FUNCTIONS.pptPPT3-CONDITIONAL STATEMENT LOOPS DICTIONARY FUNCTIONS.ppt
PPT3-CONDITIONAL STATEMENT LOOPS DICTIONARY FUNCTIONS.ppt
RahulKumar812056
 
Slide 6_Control Structures.pdf
Slide 6_Control Structures.pdfSlide 6_Control Structures.pdf
Slide 6_Control Structures.pdf
NuthalapatiSasidhar
 
2 Python Basics II meeting 2 tunghai university pdf
2 Python Basics II meeting 2 tunghai university pdf2 Python Basics II meeting 2 tunghai university pdf
2 Python Basics II meeting 2 tunghai university pdf
Anggi Andriyadi
 
Python unit 3 and Unit 4
Python unit 3 and Unit 4Python unit 3 and Unit 4
Python unit 3 and Unit 4
Anandh Arumugakan
 
Python unit 2 M.sc cs
Python unit 2 M.sc csPython unit 2 M.sc cs
Python unit 2 M.sc cs
KALAISELVI P
 
PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT 2
PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT 2PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT 2
PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT 2
MulliMary
 
Practical Python.pptx Practical Python.pptx
Practical Python.pptx Practical Python.pptxPractical Python.pptx Practical Python.pptx
Practical Python.pptx Practical Python.pptx
trwdcn
 
PYTHON 3.pptx
PYTHON 3.pptxPYTHON 3.pptx
PYTHON 3.pptx
2021bcs124
 
UNIT – 3.pptx for first year engineering
UNIT – 3.pptx for first year engineeringUNIT – 3.pptx for first year engineering
UNIT – 3.pptx for first year engineering
SabarigiriVason
 
Python if_else_loop_Control_Flow_Statement
Python if_else_loop_Control_Flow_StatementPython if_else_loop_Control_Flow_Statement
Python if_else_loop_Control_Flow_Statement
AbhishekGupta692777
 
iterations.docx
iterations.docxiterations.docx
iterations.docx
ssuser2e84e4
 
Looping Statements and Control Statements in Python
Looping Statements and Control Statements in PythonLooping Statements and Control Statements in Python
Looping Statements and Control Statements in Python
PriyankaC44
 
Loops in Python.pptx
Loops in Python.pptxLoops in Python.pptx
Loops in Python.pptx
Guru Nanak Dev University, Amritsar
 
While-For-loop in python used in college
While-For-loop in python used in collegeWhile-For-loop in python used in college
While-For-loop in python used in college
ssuser7a7cd61
 
While_for_loop presententationin first year students
While_for_loop presententationin first year studentsWhile_for_loop presententationin first year students
While_for_loop presententationin first year students
SIHIGOPAL
 
Python Flow Control
Python Flow ControlPython Flow Control
Python Flow Control
Mohammed Sikander
 
Control structures pyhton
Control structures  pyhtonControl structures  pyhton
Control structures pyhton
Prakash Jayaraman
 
ppt3-conditionalstatementloopsdictionaryfunctions-240731050730-455ba0fa.ppt
ppt3-conditionalstatementloopsdictionaryfunctions-240731050730-455ba0fa.pptppt3-conditionalstatementloopsdictionaryfunctions-240731050730-455ba0fa.ppt
ppt3-conditionalstatementloopsdictionaryfunctions-240731050730-455ba0fa.ppt
avishekpradhan24
 
PPT3-CONDITIONAL STATEMENT LOOPS DICTIONARY FUNCTIONS.ppt
PPT3-CONDITIONAL STATEMENT LOOPS DICTIONARY FUNCTIONS.pptPPT3-CONDITIONAL STATEMENT LOOPS DICTIONARY FUNCTIONS.ppt
PPT3-CONDITIONAL STATEMENT LOOPS DICTIONARY FUNCTIONS.ppt
RahulKumar812056
 
2 Python Basics II meeting 2 tunghai university pdf
2 Python Basics II meeting 2 tunghai university pdf2 Python Basics II meeting 2 tunghai university pdf
2 Python Basics II meeting 2 tunghai university pdf
Anggi Andriyadi
 
Python unit 2 M.sc cs
Python unit 2 M.sc csPython unit 2 M.sc cs
Python unit 2 M.sc cs
KALAISELVI P
 
PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT 2
PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT 2PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT 2
PROBLEM SOLVING AND PYTHON PROGRAMMING UNIT 2
MulliMary
 
Practical Python.pptx Practical Python.pptx
Practical Python.pptx Practical Python.pptxPractical Python.pptx Practical Python.pptx
Practical Python.pptx Practical Python.pptx
trwdcn
 
UNIT – 3.pptx for first year engineering
UNIT – 3.pptx for first year engineeringUNIT – 3.pptx for first year engineering
UNIT – 3.pptx for first year engineering
SabarigiriVason
 
Python if_else_loop_Control_Flow_Statement
Python if_else_loop_Control_Flow_StatementPython if_else_loop_Control_Flow_Statement
Python if_else_loop_Control_Flow_Statement
AbhishekGupta692777
 
Looping Statements and Control Statements in Python
Looping Statements and Control Statements in PythonLooping Statements and Control Statements in Python
Looping Statements and Control Statements in Python
PriyankaC44
 
While-For-loop in python used in college
While-For-loop in python used in collegeWhile-For-loop in python used in college
While-For-loop in python used in college
ssuser7a7cd61
 
While_for_loop presententationin first year students
While_for_loop presententationin first year studentsWhile_for_loop presententationin first year students
While_for_loop presententationin first year students
SIHIGOPAL
 
Ad

More from Megha V (19)

Soft Computing Techniques_Part 1.pptx
Soft Computing Techniques_Part 1.pptxSoft Computing Techniques_Part 1.pptx
Soft Computing Techniques_Part 1.pptx
Megha V
 
JavaScript- Functions and arrays.pptx
JavaScript- Functions and arrays.pptxJavaScript- Functions and arrays.pptx
JavaScript- Functions and arrays.pptx
Megha V
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
Megha V
 
Python Exception Handling
Python Exception HandlingPython Exception Handling
Python Exception Handling
Megha V
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
Megha V
 
Python programming -Tuple and Set Data type
Python programming -Tuple and Set Data typePython programming -Tuple and Set Data type
Python programming -Tuple and Set Data type
Megha V
 
Python programming
Python programmingPython programming
Python programming
Megha V
 
Strassen's matrix multiplication
Strassen's matrix multiplicationStrassen's matrix multiplication
Strassen's matrix multiplication
Megha V
 
Solving recurrences
Solving recurrencesSolving recurrences
Solving recurrences
Megha V
 
Algorithm Analysis
Algorithm AnalysisAlgorithm Analysis
Algorithm Analysis
Megha V
 
Genetic algorithm
Genetic algorithmGenetic algorithm
Genetic algorithm
Megha V
 
UGC NET Paper 1 ICT Memory and data
UGC NET Paper 1 ICT Memory and data  UGC NET Paper 1 ICT Memory and data
UGC NET Paper 1 ICT Memory and data
Megha V
 
Seminar presentation on OpenGL
Seminar presentation on OpenGLSeminar presentation on OpenGL
Seminar presentation on OpenGL
Megha V
 
Msc project_CDS Automation
Msc project_CDS AutomationMsc project_CDS Automation
Msc project_CDS Automation
Megha V
 
Gi fi technology
Gi fi technologyGi fi technology
Gi fi technology
Megha V
 
Digital initiatives in higher education
Digital initiatives in higher educationDigital initiatives in higher education
Digital initiatives in higher education
Megha V
 
Information and Communication Technology (ICT) abbreviation
Information and Communication Technology (ICT) abbreviationInformation and Communication Technology (ICT) abbreviation
Information and Communication Technology (ICT) abbreviation
Megha V
 
Basics of internet, intranet, e mail,
Basics of internet, intranet, e mail,Basics of internet, intranet, e mail,
Basics of internet, intranet, e mail,
Megha V
 
Information and communication technology(ict)
Information and communication technology(ict)Information and communication technology(ict)
Information and communication technology(ict)
Megha V
 
Soft Computing Techniques_Part 1.pptx
Soft Computing Techniques_Part 1.pptxSoft Computing Techniques_Part 1.pptx
Soft Computing Techniques_Part 1.pptx
Megha V
 
JavaScript- Functions and arrays.pptx
JavaScript- Functions and arrays.pptxJavaScript- Functions and arrays.pptx
JavaScript- Functions and arrays.pptx
Megha V
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
Megha V
 
Python Exception Handling
Python Exception HandlingPython Exception Handling
Python Exception Handling
Megha V
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
Megha V
 
Python programming -Tuple and Set Data type
Python programming -Tuple and Set Data typePython programming -Tuple and Set Data type
Python programming -Tuple and Set Data type
Megha V
 
Python programming
Python programmingPython programming
Python programming
Megha V
 
Strassen's matrix multiplication
Strassen's matrix multiplicationStrassen's matrix multiplication
Strassen's matrix multiplication
Megha V
 
Solving recurrences
Solving recurrencesSolving recurrences
Solving recurrences
Megha V
 
Algorithm Analysis
Algorithm AnalysisAlgorithm Analysis
Algorithm Analysis
Megha V
 
Genetic algorithm
Genetic algorithmGenetic algorithm
Genetic algorithm
Megha V
 
UGC NET Paper 1 ICT Memory and data
UGC NET Paper 1 ICT Memory and data  UGC NET Paper 1 ICT Memory and data
UGC NET Paper 1 ICT Memory and data
Megha V
 
Seminar presentation on OpenGL
Seminar presentation on OpenGLSeminar presentation on OpenGL
Seminar presentation on OpenGL
Megha V
 
Msc project_CDS Automation
Msc project_CDS AutomationMsc project_CDS Automation
Msc project_CDS Automation
Megha V
 
Gi fi technology
Gi fi technologyGi fi technology
Gi fi technology
Megha V
 
Digital initiatives in higher education
Digital initiatives in higher educationDigital initiatives in higher education
Digital initiatives in higher education
Megha V
 
Information and Communication Technology (ICT) abbreviation
Information and Communication Technology (ICT) abbreviationInformation and Communication Technology (ICT) abbreviation
Information and Communication Technology (ICT) abbreviation
Megha V
 
Basics of internet, intranet, e mail,
Basics of internet, intranet, e mail,Basics of internet, intranet, e mail,
Basics of internet, intranet, e mail,
Megha V
 
Information and communication technology(ict)
Information and communication technology(ict)Information and communication technology(ict)
Information and communication technology(ict)
Megha V
 
Ad

Recently uploaded (20)

Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_HyderabadWebcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Veera Pallapu
 
How to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 EmployeeHow to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 Employee
Celine George
 
Hemiptera & Neuroptera: Insect Diversity.pptx
Hemiptera & Neuroptera: Insect Diversity.pptxHemiptera & Neuroptera: Insect Diversity.pptx
Hemiptera & Neuroptera: Insect Diversity.pptx
Arshad Shaikh
 
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptxDiptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Arshad Shaikh
 
Strengthened Senior High School - Landas Tool Kit.pptx
Strengthened Senior High School - Landas Tool Kit.pptxStrengthened Senior High School - Landas Tool Kit.pptx
Strengthened Senior High School - Landas Tool Kit.pptx
SteffMusniQuiballo
 
How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18
Celine George
 
EUPHORIA GENERAL QUIZ FINALS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025
EUPHORIA GENERAL QUIZ FINALS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025EUPHORIA GENERAL QUIZ FINALS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025
EUPHORIA GENERAL QUIZ FINALS | QUIZ CLUB OF PSGCAS | 21 MARCH 2025
Quiz Club of PSG College of Arts & Science
 
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
parmarjuli1412
 
How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18
Celine George
 
Black and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdfBlack and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdf
AnnasofiaUrsini
 
Parenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independenceParenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independence
Pooky Knightsmith
 
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdfFEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
ChristinaFortunova
 
Final Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptxFinal Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptx
bobby205207
 
LDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad UpdatesLDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad Updates
LDM & Mia eStudios
 
Gibson "Secrets to Changing Behaviour in Scholarly Communication: A 2025 NISO...
Gibson "Secrets to Changing Behaviour in Scholarly Communication: A 2025 NISO...Gibson "Secrets to Changing Behaviour in Scholarly Communication: A 2025 NISO...
Gibson "Secrets to Changing Behaviour in Scholarly Communication: A 2025 NISO...
National Information Standards Organization (NISO)
 
Rose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdfRose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdf
kushallamichhame
 
Respiratory System , Urinary System
Respiratory  System , Urinary SystemRespiratory  System , Urinary System
Respiratory System , Urinary System
RushiMandali
 
Exploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle SchoolExploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle School
Marie
 
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition OecdEnergy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
razelitouali
 
Capitol Doctoral Presentation -June 2025.pptx
Capitol Doctoral Presentation -June 2025.pptxCapitol Doctoral Presentation -June 2025.pptx
Capitol Doctoral Presentation -June 2025.pptx
CapitolTechU
 
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_HyderabadWebcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Veera Pallapu
 
How to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 EmployeeHow to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 Employee
Celine George
 
Hemiptera & Neuroptera: Insect Diversity.pptx
Hemiptera & Neuroptera: Insect Diversity.pptxHemiptera & Neuroptera: Insect Diversity.pptx
Hemiptera & Neuroptera: Insect Diversity.pptx
Arshad Shaikh
 
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptxDiptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Diptera: The Two-Winged Wonders, The Fly Squad: Order Diptera.pptx
Arshad Shaikh
 
Strengthened Senior High School - Landas Tool Kit.pptx
Strengthened Senior High School - Landas Tool Kit.pptxStrengthened Senior High School - Landas Tool Kit.pptx
Strengthened Senior High School - Landas Tool Kit.pptx
SteffMusniQuiballo
 
How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18
Celine George
 
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
parmarjuli1412
 
How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18
Celine George
 
Black and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdfBlack and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdf
AnnasofiaUrsini
 
Parenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independenceParenting Teens: Supporting Trust, resilience and independence
Parenting Teens: Supporting Trust, resilience and independence
Pooky Knightsmith
 
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdfFEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
FEBA Sofia Univercity final diplian v3 GSDG 5.2025.pdf
ChristinaFortunova
 
Final Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptxFinal Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptx
bobby205207
 
LDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad UpdatesLDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad Updates
LDM & Mia eStudios
 
Rose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdfRose Cultivation Practices by Kushal Lamichhane.pdf
Rose Cultivation Practices by Kushal Lamichhane.pdf
kushallamichhame
 
Respiratory System , Urinary System
Respiratory  System , Urinary SystemRespiratory  System , Urinary System
Respiratory System , Urinary System
RushiMandali
 
Exploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle SchoolExploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle School
Marie
 
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition OecdEnergy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
Energy Balances Of Oecd Countries 2011 Iea Statistics 1st Edition Oecd
razelitouali
 
Capitol Doctoral Presentation -June 2025.pptx
Capitol Doctoral Presentation -June 2025.pptxCapitol Doctoral Presentation -June 2025.pptx
Capitol Doctoral Presentation -June 2025.pptx
CapitolTechU
 

Python programming –part 3

  • 1. Python Programming –Part III Megha V Research Scholar Kannur University 02-11-2021 [email protected] 1
  • 2. Control flow statements • Decision control flow statements (if, if…..else, if…….elif….else, nested if) • Loop(while, for) • continue statement • break statement 02-11-2021 [email protected] 2
  • 3. Decision making • Decision making is required when we want to execute a code only if a certain condition is satisfied. 1. if statement Syntax: if test expression: statement(s) Example: a = 15 if a > 10: print("a is greater") Output: a is greater 02-11-2021 [email protected] 3
  • 4. Decision making 2. if……else statements • Syntax if expression: body of if else: body of else • Example a = 15 b = 20 if a > b: print("a is greater") else: print("b is greater") Output: b is greater 02-11-2021 [email protected] 4
  • 5. Decision making 3. if…elif…else statements elif - is a keyword used in Python replacement of else if to place another condition in the program. This is called chained conditional. 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, body of else is executed. • Syntax if test expression: body of if elif test expression: body of elif else: body of else 02-11-2021 [email protected] 5
  • 6. Decision making • if…elif…else statements Example a = 15 b = 15 if a > b: print("a is greater") elif a == b: print("both are equal") else: print("b is greater") Output: both are equal 02-11-2021 [email protected] 6
  • 7. Decision making 4. Nested if statements if statements inside if statements, this is called nested if statements. Example: x = 41 if x > 10: print("Above ten,") if x > 20: print("and also above 20!") else: print("but not above 20.") Output: Above ten, and also above 20! 02-11-2021 [email protected] 7
  • 8. LOOPS • There will be situations when we need to execute a block of code several times. • Python provides various control structures that allow repeated execution for loop while loop for loop • A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string). • With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc. 02-11-2021 [email protected] 8
  • 9. LOOPS for loop Syntax: for item in sequence: Body of for • Item is the variable that takes the value of the item inside the sequence of each iteration. • The sequence can be list, tuple, string, set etc. • The body of for loop is separated from the rest of the code using indentation. 02-11-2021 [email protected] 9
  • 10. LOOPS for loop Example Program 1: #Program to find the sum of all numbers stored in a list numbers = [2,4,6,8,10] # variable to store the sum sum=0 # iterate over the list for item in numbers: sum = sum + item #print the sum print(“The sum is",sum) Output The sum is 30 02-11-2021 [email protected] 10
  • 11. LOOPS for loop Example Program 2: flowers = [‘rose’,’lotus’,’jasmine’] for flower in flowers: print(‘Current flower :’,flower) Output Current flower : rose Current flower : lotus Current flower : jasmine 02-11-2021 [email protected] 11
  • 12. LOOPS • for loop with range() function • We can use range() function in for loops to iterate through a sequence of numbers, • It can be combined with len() function to iterate through a sequence using indexing • len() function is used to find the length of a string or number of elements in a list, tuple, set etc. • Example program flowers=[‘rose’,’lotus’,’jasmine’] for i in range(len(flowers)): print(‘Current flower:’, flowers[i]) Output Current flower : rose Current flower : lotus Current flower : jasmine 02-11-2021 [email protected] 12
  • 13. range() function for x in range(6): print(x) • Note that range(6) is not the values of 0 to 6, but the values 0 to 5. • The range() function defaults to 0 as a starting value, however it is possible to specify the starting value by adding a parameter: range(2, 6), which means values from 2 to 6 (but not including 6) • The range() function defaults to increment the sequence by 1, however it is possible to specify the increment value by adding a third parameter: range(2, 30, 3): • increment the sequence with 3 (default is 1): for x in range(2, 30, 3): print(x) 02-11-2021 [email protected] 13
  • 14. LOOPS enumerate(iterable,start=0)function • The enumerate() function takes a collection (eg tuple) and returns it as an enumerate object • built in function returns an e • numerate object • The parameter iterable must be a sequence, an iterator, or some other objects like list which supports iteration Example Program # Demo of enumerate function using list flowers = [‘rose’,’lotus’,’jasmine’,’sunflower’] print(list(enumerate(flowers))) for index,item in enumerate(flowers) print(index,item) Output [(0,’rose’),(1,’lotus’),(2,’jasmine’),(3,’sunflower’)] 0 rose 1 lotus 2 jasmine 3 sunflower 02-11-2021 [email protected] 14
  • 15. LOOPS 2. while loop Used to iterate over a block of code as long as the test expression (condition) is True. Syntax while test_expression: Body of while Example Program # Program to find the sum of first N natural numbers n=int(input(“Enter the limit:”)) sum=0 i=1 while(i<=n) sum = sum+i i=i+1 print(“Sum of first ”,n,”natural number is”, sum) Output Enter the limit: 5 Sum of first 5 natural number is 15 02-11-2021 [email protected] 15
  • 16. LOOPS while loop with else statement Example Program count=1 while(count<=3) print(“python programming”) count=count+1 else: print(“Exit”) print(“End of program”) Output python programming python programming python programming Exit End of program 02-11-2021 [email protected] 16
  • 17. Nested Loops • Sometimes we need to place loop inside another loop • This is called nested loops Syntax for nested for loop for iterating_variable in sequence: for iterating_variable in sequence: statement(s) statement(s) Syntax for nested while loop while expression: while expression: statement(s) statement(s) 02-11-2021 [email protected] 17
  • 18. CONTROL STATEMENTS • Control statements change the execution from normal sequence • Python supports the following 3 control statements • break • continue • pass 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 it is inside a nested loop, break will terminate the innermost loop • It can be used with both for and while loops. 02-11-2021 [email protected] 18
  • 19. CONTROL STATEMENTS break statement • Example #Demo of break for i in range(2,10,2): if(i==6):break print(i) print(“End of program”) Output 2 4 End of program Here the for loop is intended to print the even numbers from 2 to 10. The if condition checks whether i=6. If it is 6, the control goes to the next statement after the for loop. 02-11-2021 [email protected] 19
  • 20. CONTROL STATEMENTS continue statement • The continue statement is used to skip the rest of the code inside a loop for the current iteration only. • Loop does not terminate but continues with next iteration • continue returns the control to the beginning of the loop • rejects all the remaining statements in the current iteration of the loop • It can be used with for loop and while loop 02-11-2021 [email protected] 20
  • 21. CONTROL STATEMENTS continue statement Example for letter in ‘abcd’: if(letter==‘c’):continue print(letter) Output a b d 02-11-2021 [email protected] 21
  • 22. CONTROL STATEMENTS pass statement • In Python pass is a null statement • while interpreter ignores a comment entirely, pass is not ignored • nothing happens when it is executed • used a a placeholder • in the case we want to implement a function in future • Normally function or loop cannot have an empty body. • So when we use the pass statement to construct a body that does nothis Example: for val in sequence: pass 02-11-2021 [email protected] 22
  • 23. Reading input • The function input() consider all input as strings. • To convert the input string to equivalent integers, we need to use function explicitly • Example cost = int(input(Enter cost price:’)) profit = int(input(Enter profit:’)) 02-11-2021 [email protected] 23
  • 24. LAB ASSIGNMENT • Write a python program to find maximum of 3 numbers using if….elif…else statement • Program to find largest among two numbers using if…else • Program to find the sum of first n positive integers using for loop • Program to print prime numbers using for loop • Python program to print prime numbers using while loop • Program to print the elements in a list and tuple in reverse order 02-11-2021 [email protected] 24