SlideShare ist ein Scribd-Unternehmen logo
1 von 24
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

Weitere ähnliche Inhalte

Was ist angesagt?

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 functionARVIND 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 APISvetlin Nakov
 
Functions in advanced programming
Functions in advanced programmingFunctions in advanced programming
Functions in advanced programmingVisnuDharsini
 
String Manipulation in Python
String Manipulation in PythonString Manipulation in Python
String Manipulation in PythonPooja B S
 
Java Foundations: Arrays
Java Foundations: ArraysJava Foundations: Arrays
Java Foundations: ArraysSvetlin 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 31Mahmoud 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 programinghamzagame
 
Arrays in python
Arrays in pythonArrays in python
Arrays in pythonLifna 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 WrongMario Fusco
 

Was ist angesagt? (20)

Java Foundations: Lists, ArrayList<T>
Java Foundations: Lists, ArrayList<T>Java Foundations: Lists, ArrayList<T>
Java Foundations: Lists, ArrayList<T>
 
Python programming : Strings
Python programming : StringsPython programming : Strings
Python programming : Strings
 
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
 
Python : Functions
Python : FunctionsPython : Functions
Python : Functions
 
Embedded C - Day 2
Embedded C - Day 2Embedded C - Day 2
Embedded C - Day 2
 
Iteration
IterationIteration
Iteration
 
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
 
Arrays
ArraysArrays
Arrays
 
Python
PythonPython
Python
 
Python numbers
Python numbersPython numbers
Python numbers
 
Functions in advanced programming
Functions in advanced programmingFunctions in advanced programming
Functions in advanced programming
 
String Manipulation in Python
String Manipulation in PythonString Manipulation in Python
String Manipulation in Python
 
Java Foundations: Arrays
Java Foundations: ArraysJava Foundations: Arrays
Java Foundations: Arrays
 
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
 
15. Streams Files and Directories
15. Streams Files and Directories 15. Streams Files and Directories
15. Streams Files and Directories
 
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
 
Python programing
Python programingPython programing
Python programing
 
Map, Reduce and Filter in Swift
Map, Reduce and Filter in SwiftMap, Reduce and Filter in Swift
Map, Reduce and Filter in Swift
 
Arrays in python
Arrays in pythonArrays in python
Arrays in python
 
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
 

Ähnlich wie Python programming –part 3

Ähnlich wie Python programming –part 3 (20)

Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Unit - 2 CAP.pptx
Unit - 2 CAP.pptxUnit - 2 CAP.pptx
Unit - 2 CAP.pptx
 
Python Loop
Python LoopPython Loop
Python Loop
 
Python Decision Making And Loops.pdf
Python Decision Making And Loops.pdfPython Decision Making And Loops.pdf
Python Decision Making And Loops.pdf
 
Python for Machine Learning
Python for Machine LearningPython for Machine Learning
Python for Machine Learning
 
07 control+structures
07 control+structures07 control+structures
07 control+structures
 
85ec7 session2 c++
85ec7 session2 c++85ec7 session2 c++
85ec7 session2 c++
 
PythonStudyMaterialSTudyMaterial.pdf
PythonStudyMaterialSTudyMaterial.pdfPythonStudyMaterialSTudyMaterial.pdf
PythonStudyMaterialSTudyMaterial.pdf
 
Python.pptx
Python.pptxPython.pptx
Python.pptx
 
lecture 2.pptx
lecture 2.pptxlecture 2.pptx
lecture 2.pptx
 
Introduction to python programming ( part-3 )
Introduction to python programming ( part-3 )Introduction to python programming ( part-3 )
Introduction to python programming ( part-3 )
 
Introduction To Python.pptx
Introduction To Python.pptxIntroduction To Python.pptx
Introduction To Python.pptx
 
python ppt
python pptpython ppt
python ppt
 

Mehr von Megha V

Soft Computing Techniques_Part 1.pptx
Soft Computing Techniques_Part 1.pptxSoft Computing Techniques_Part 1.pptx
Soft Computing Techniques_Part 1.pptxMegha V
 
JavaScript- Functions and arrays.pptx
JavaScript- Functions and arrays.pptxJavaScript- Functions and arrays.pptx
JavaScript- Functions and arrays.pptxMegha V
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScriptMegha V
 
Python Exception Handling
Python Exception HandlingPython Exception Handling
Python Exception HandlingMegha V
 
File handling in Python
File handling in PythonFile handling in Python
File handling in PythonMegha 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 typeMegha V
 
Python programming
Python programmingPython programming
Python programmingMegha V
 
Strassen's matrix multiplication
Strassen's matrix multiplicationStrassen's matrix multiplication
Strassen's matrix multiplicationMegha V
 
Solving recurrences
Solving recurrencesSolving recurrences
Solving recurrencesMegha V
 
Algorithm Analysis
Algorithm AnalysisAlgorithm Analysis
Algorithm AnalysisMegha V
 
Genetic algorithm
Genetic algorithmGenetic algorithm
Genetic algorithmMegha 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 OpenGLMegha V
 
Msc project_CDS Automation
Msc project_CDS AutomationMsc project_CDS Automation
Msc project_CDS AutomationMegha V
 
Gi fi technology
Gi fi technologyGi fi technology
Gi fi technologyMegha V
 
Digital initiatives in higher education
Digital initiatives in higher educationDigital initiatives in higher education
Digital initiatives in higher educationMegha V
 
Information and Communication Technology (ICT) abbreviation
Information and Communication Technology (ICT) abbreviationInformation and Communication Technology (ICT) abbreviation
Information and Communication Technology (ICT) abbreviationMegha 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
 

Mehr von 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
 
JavaScript- Functions and arrays.pptx
JavaScript- Functions and arrays.pptxJavaScript- Functions and arrays.pptx
JavaScript- Functions and arrays.pptx
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
Python Exception Handling
Python Exception HandlingPython Exception Handling
Python Exception Handling
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
 
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
 
Python programming
Python programmingPython programming
Python programming
 
Strassen's matrix multiplication
Strassen's matrix multiplicationStrassen's matrix multiplication
Strassen's matrix multiplication
 
Solving recurrences
Solving recurrencesSolving recurrences
Solving recurrences
 
Algorithm Analysis
Algorithm AnalysisAlgorithm Analysis
Algorithm Analysis
 
Genetic algorithm
Genetic algorithmGenetic algorithm
Genetic algorithm
 
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
 
Seminar presentation on OpenGL
Seminar presentation on OpenGLSeminar presentation on OpenGL
Seminar presentation on OpenGL
 
Msc project_CDS Automation
Msc project_CDS AutomationMsc project_CDS Automation
Msc project_CDS Automation
 
Gi fi technology
Gi fi technologyGi fi technology
Gi fi technology
 
Digital initiatives in higher education
Digital initiatives in higher educationDigital initiatives in higher education
Digital initiatives in higher education
 
Information and Communication Technology (ICT) abbreviation
Information and Communication Technology (ICT) abbreviationInformation and Communication Technology (ICT) abbreviation
Information and Communication Technology (ICT) abbreviation
 
Basics of internet, intranet, e mail,
Basics of internet, intranet, e mail,Basics of internet, intranet, e mail,
Basics of internet, intranet, e mail,
 
Information and communication technology(ict)
Information and communication technology(ict)Information and communication technology(ict)
Information and communication technology(ict)
 

Kürzlich hochgeladen

Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Association for Project Management
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Projectjordimapav
 
Mental Health Awareness - a toolkit for supporting young minds
Mental Health Awareness - a toolkit for supporting young mindsMental Health Awareness - a toolkit for supporting young minds
Mental Health Awareness - a toolkit for supporting young mindsPooky Knightsmith
 
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxBIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxSayali Powar
 
4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptxmary850239
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptxiammrhaywood
 
MS4 level being good citizen -imperative- (1) (1).pdf
MS4 level   being good citizen -imperative- (1) (1).pdfMS4 level   being good citizen -imperative- (1) (1).pdf
MS4 level being good citizen -imperative- (1) (1).pdfMr Bounab Samir
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxVanesaIglesias10
 
Multi Domain Alias In the Odoo 17 ERP Module
Multi Domain Alias In the Odoo 17 ERP ModuleMulti Domain Alias In the Odoo 17 ERP Module
Multi Domain Alias In the Odoo 17 ERP ModuleCeline George
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmStan Meyer
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
How to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 DatabaseHow to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 DatabaseCeline George
 
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...Nguyen Thanh Tu Collection
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxkarenfajardo43
 
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptxDIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptxMichelleTuguinay1
 
week 1 cookery 8 fourth - quarter .pptx
week 1 cookery 8  fourth  -  quarter .pptxweek 1 cookery 8  fourth  -  quarter .pptx
week 1 cookery 8 fourth - quarter .pptxJonalynLegaspi2
 
Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationdeepaannamalai16
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxlancelewisportillo
 

Kürzlich hochgeladen (20)

Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
Team Lead Succeed – Helping you and your team achieve high-performance teamwo...
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Project
 
Mental Health Awareness - a toolkit for supporting young minds
Mental Health Awareness - a toolkit for supporting young mindsMental Health Awareness - a toolkit for supporting young minds
Mental Health Awareness - a toolkit for supporting young minds
 
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptxBIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
BIOCHEMISTRY-CARBOHYDRATE METABOLISM CHAPTER 2.pptx
 
4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
 
MS4 level being good citizen -imperative- (1) (1).pdf
MS4 level   being good citizen -imperative- (1) (1).pdfMS4 level   being good citizen -imperative- (1) (1).pdf
MS4 level being good citizen -imperative- (1) (1).pdf
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptx
 
Multi Domain Alias In the Odoo 17 ERP Module
Multi Domain Alias In the Odoo 17 ERP ModuleMulti Domain Alias In the Odoo 17 ERP Module
Multi Domain Alias In the Odoo 17 ERP Module
 
Oppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and FilmOppenheimer Film Discussion for Philosophy and Film
Oppenheimer Film Discussion for Philosophy and Film
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
How to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 DatabaseHow to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 Database
 
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
31 ĐỀ THI THỬ VÀO LỚP 10 - TIẾNG ANH - FORM MỚI 2025 - 40 CÂU HỎI - BÙI VĂN V...
 
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
 
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptxDIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
 
week 1 cookery 8 fourth - quarter .pptx
week 1 cookery 8  fourth  -  quarter .pptxweek 1 cookery 8  fourth  -  quarter .pptx
week 1 cookery 8 fourth - quarter .pptx
 
Congestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentationCongestive Cardiac Failure..presentation
Congestive Cardiac Failure..presentation
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
 

Python programming –part 3

  • 1. Python Programming –Part III Megha V Research Scholar Kannur University 02-11-2021 meghav@kannuruniv.ac.in 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 meghav@kannuruniv.ac.in 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 meghav@kannuruniv.ac.in 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 meghav@kannuruniv.ac.in 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 meghav@kannuruniv.ac.in 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 meghav@kannuruniv.ac.in 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 meghav@kannuruniv.ac.in 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 meghav@kannuruniv.ac.in 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 meghav@kannuruniv.ac.in 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 meghav@kannuruniv.ac.in 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 meghav@kannuruniv.ac.in 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 meghav@kannuruniv.ac.in 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 meghav@kannuruniv.ac.in 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 meghav@kannuruniv.ac.in 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 meghav@kannuruniv.ac.in 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 meghav@kannuruniv.ac.in 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 meghav@kannuruniv.ac.in 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 meghav@kannuruniv.ac.in 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 meghav@kannuruniv.ac.in 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 meghav@kannuruniv.ac.in 20
  • 21. 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
  • 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 meghav@kannuruniv.ac.in 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 meghav@kannuruniv.ac.in 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 meghav@kannuruniv.ac.in 24