SlideShare una empresa de Scribd logo
1 de 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

Más contenido relacionado

La actualidad más candente

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
 

La actualidad más candente (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
 

Similar a Python programming –part 3

Python Decision Making And Loops.pdf
Python Decision Making And Loops.pdfPython Decision Making And Loops.pdf
Python Decision Making And Loops.pdfNehaSpillai1
 
Python for Machine Learning
Python for Machine LearningPython for Machine Learning
Python for Machine LearningStudent
 
07 control+structures
07 control+structures07 control+structures
07 control+structuresbaran19901990
 
PythonStudyMaterialSTudyMaterial.pdf
PythonStudyMaterialSTudyMaterial.pdfPythonStudyMaterialSTudyMaterial.pdf
PythonStudyMaterialSTudyMaterial.pdfdata2businessinsight
 
Introduction to python programming ( part-3 )
Introduction to python programming ( part-3 )Introduction to python programming ( part-3 )
Introduction to python programming ( part-3 )Ziyauddin Shaik
 
introduction to python in english presentation file
introduction to python in english presentation fileintroduction to python in english presentation file
introduction to python in english presentation fileRujanTimsina1
 
Introduction To Python.pptx
Introduction To Python.pptxIntroduction To Python.pptx
Introduction To Python.pptxAnum Zehra
 

Similar a 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 in english presentation file
introduction to python in english presentation fileintroduction to python in english presentation file
introduction to python in english presentation file
 
Introduction To Python.pptx
Introduction To Python.pptxIntroduction To Python.pptx
Introduction To Python.pptx
 

Más de 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
 

Más de 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)
 

Último

Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfChris Hunter
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.MateoGardella
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingTeacherCyreneCayanan
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docxPoojaSen20
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Shubhangi Sonawane
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfSanaAli374401
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxVishalSingh1417
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 

Último (20)

Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 

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