SlideShare a Scribd company logo
1 of 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

More Related Content

What's hot

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
 

What's hot (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 to Python programming –part 3

Similar to 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
 

More from 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
 

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
 
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)
 

Recently uploaded

ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxJiesonDelaCerna
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupJonathanParaisoCruz
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...jaredbarbolino94
 

Recently uploaded (20)

ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptx
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized Group
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...
 

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