SlideShare a Scribd company logo
1 of 62
Python Control Structure
by
S.P. Siddique Ibrahim
AP/CSE
Kumaraguru College ofTechnology
Coimbatore
1
IntroductionIntroduction
Says the control flow of the statement in
the programming language.
Show the control flow
2
Control StructuresControl Structures
3 control structures
◦ Sequential structure
 Built into Python
◦ Decision/ Selection structure
 The if statement
 The if/else statement
 The if/elif/else statement
◦ Repetition structure / Iterative
 The while repetition structure
 The for repetition structure
3
4
Sequential StructureSequential Structure
Normal flow/sequential execution of the
statement.
Line by line/Normal execution
If you want to perform simple addition:
A=5
B=6
Print(A+B)
5
Sequence Control StructureSequence Control Structure
6
Fig. 3.1 Sequence structure flowchart with pseudo code.
add grade to total
add 1 to counter
total = total + grade;
counter = counter + 1;
Decision Control flowDecision Control flow
There will be a condition and based on
the condition parameter then the control
will be flow in only one direction.
7
8
9
10
11
ifif Selection StructureSelection Structure
12
Fig. 3.3 if single-selection structure flowchart.
print “Passed”Grade >= 60
true
false
13
14
15
16
17
Control StructuresControl Structures
18
 >>> x = 0
 >>> y = 5
 >>> if x < y: # Truthy
 ... print('yes')
 ...
 yes
 >>> if y < x: # Falsy
 ... print('yes')
 ...
 >>> if x: # Falsy
 ... print('yes')
 ...
 >>> if y: # Truthy
 ... print('yes')
 ...
 yes
 >>> if x or y: # Truthy
 ... print('yes')
 ...
 yes
19
 >>> if x and y: # Falsy
 ... print('yes')
 ...
 >>> if 'aul' in 'grault': # Truthy
 ... print('yes')
 ...
 yes
 >>> if 'quux' in ['foo', 'bar', 'baz']: # Falsy
 ... print('yes')
20
If else:If else:
21
if/elseif/else StructureStructure
22
Fig. 3.4 if/else double-selection structure flowchart.
Grade >= 60
print “Passed”print “Failed”
false true
23
Class ActivityClass Activity
# Program checks if the number is
positive or negative and displays an
appropriate message
# Program checks if the number is
positive or negative –Get the input from
the user also checks the zero inside the
positive value
24
num = 3
# Try these two variations as well.
# num = -5
# num = 0
if num >= 0:
print("Positive or Zero")
else:
print("Negative number")
25
Contd.,Contd.,
26
if/elif/elseif/elif/else SelectionSelection
StructureStructure
27
condition a
true
false
.
.
.
false
false
condition z
default action(s)
true
true
condition b
case a action(s)
case b action(s)
case z action(s)
if statement
first elif
statement
last elif
statement
else
statement
Fig. 3.5 if/elif/else multiple-selection structure.
syntaxsyntax
28
Example Python codeExample Python code
29
Example with Python codeExample with Python code
30
# get price from user and convert it into a float:
price = float( raw_input(“Enter the price of one tomato: “))
if price < 1:
s = “That’s cheap, buy a lot!”
elif price < 3:
s = “Okay, buy a few”
else:
s = “Too much, buy some carrots instead”
print s
Control StructuresControl Structures
31
32
3.73.7 whilewhile Repetition StructureRepetition Structure
33
true
false
Product = 2 * productProduct <= 1000
Fig. 3.8 while repetition structure flowchart.
When we login to our homepage on Facebook, we have about 10
stories loaded on our newsfeed
As soon as we reach the end of the page, Facebook loads another 10
stories onto our newsfeed
This demonstrates how ‘while’ loop can be used to achieve this
34
35
36
37
Listing ‘Friends’ from your profile will display the names and photos of all of
your friends
To achieve this, Facebook gets your ‘friendlist’ list containing all the profiles of
your friends
Facebook then starts displaying the HTML of all the profiles till the list index
reaches ‘NULL’
The action of populating all the profiles onto your page is controlled by ‘for’
statement
38
3.133.13 forfor Repetition StructureRepetition Structure
The for loop
◦ Function range is used to create a list of values
 range ( integer )
 Values go from 0 up to given integer (i.e., not including)
 range ( integer, integer )
 Values go from first up to second integer
 range ( integer, integer, integer )
 Values go from first up to second integer but increases in intervals
of the third integer
◦ This loop will execute howmany times:
for counter in range ( howmany ):
and counter will have values 0, 1,..
howmany-1
39
for counter in range(10):
print (counter)
Output?
40
41
42
43
44
45
# Prints out 0,1,2,3,4
count = 0
while True:
 print(count)
 count += 1
 if count >= 5:
 break
# Prints out only odd numbers - 1,3,5,7,9
for x in range(10): # Check if x is even
 if x % 2 == 0:
 continue
 print(x)
46
47
Example for PassExample for Pass
48
Expression values?Expression values?
49
Python 2.2b2 (#26, Nov 16 2001, 11:44:11) [MSC 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> if 0:
... print "0 is true"
... else:
... print "0 is false"
...
0 is false
>>> if 1:
... print "non-zero is true"
...
non-zero is true
>>> if -1:
... print "non-zero is true"
...
non-zero is true
>>> print 2 < 3
1
Expressions have integer values. No true, false like in Java.
0 is false, non-0 is true.
3.16 Logical Operators3.16 Logical Operators
Operators
◦ and
 Binary. Evaluates to true if both expressions are true
◦ or
 Binary. Evaluates to true if at least one expression is
true
◦ not
 Unary. Returns true if the expression is false
50
Compare with &&, || and ! in Java
Logical operatorsLogical operators andand,, oror,, notnot
51
if gender == “female” and age >= 65:
seniorfemales = seniorfemales + 1
if iq > 250 or iq < 20:
strangevalues = strangevalues + 1
if not found_what_we_need:
print “didn’t find item”
# NB: can also use !=
if i != j:
print “Different values”
ExampleExample
52
3.11 Augmented Assignment3.11 Augmented Assignment
SymbolsSymbols
Augmented addition assignment symbols
◦ x = x + 5 is the same as x += 5
◦ Can’t use ++ like in Java!
Other math signs
◦ The same rule applies to any other
mathematical symbol
*, **, /, %
53
KeywordsKeywords
54
Python
keywords
and continue else for import not raise
assert def except from in or return
break del exec global is pass try
class elif finally if lambda print while
Fig. 3.2 Python keywords.
Can’t use as identifiers
keywordkeyword passpass : do nothing: do nothing
55
Python 2.2b2 (#26, Nov 16 2001, 11:44:11) [MSC 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> if 1 < 2:
... pass
...
Sometimes useful, e.g. during development:
if a <= 5 and c <= 5:
print “Oh no, both below 5! Fix problem”
if a > 5 and c <= 5:
pass # figure out what to do later
if a <= 5 and c > 5:
pass # figure out what to do later
if a > 5 and c > 5:
pass # figure out what to do later
Program OutputProgram Output
1 # Fig. 3.10: fig03_10.py
2 # Class average program with counter-controlled repetition.
3
4 # initialization phase
5 total = 0 # sum of grades
6 gradeCounter = 1 # number of grades entered
7
8 # processing phase
9 while gradeCounter <= 10: # loop 10 times
10 grade = raw_input( "Enter grade: " ) # get one grade
11 grade = int( grade ) # convert string to an integer
12 total = total + grade
13 gradeCounter = gradeCounter + 1
14
15 # termination phase
16 average = total / 10 # integer division
17 print "Class average is", average
56
Enter grade: 98
Enter grade: 76
Enter grade: 71
Enter grade: 87
Enter grade: 83
Enter grade: 90
Enter grade: 57
Enter grade: 79
Enter grade: 82
Enter grade: 94
Class average is 81
The total and counter, set to
zero and one respectively
A loop the continues as long as
the counter does not go past 10
Adds one to the counter to
eventually break the loop
Divides the total by the 10
to get the class average
Program OutputProgram Output1 # Fig. 3.22: fig03_22.py
2 # Summation with for.
3
4 sum = 0
5
6 for number in range( 2, 101, 2 ):
7 sum += number
8
9 print "Sum is", sum
57
Sum is 2550
Loops from 2 to 101
in increments of 2
A sum of all the even
numbers from 2 to 100
Another example
Program OutputProgram Output
1 # Fig. 3.23: fig03_23.py
2 # Calculating compound interest.
3
4 principal = 1000.0 # starting principal
5 rate = .05 # interest rate
6
7 print "Year %21s" % "Amount on deposit"
8
9 for year in range( 1, 11 ):
10 amount = principal * ( 1.0 + rate ) ** year
11 print "%4d%21.2f" % ( year, amount )
58
Year Amount on deposit
1 1050.00
2 1102.50
3 1157.63
4 1215.51
5 1276.28
6 1340.10
7 1407.10
8 1477.46
9 1551.33
10 1628.89
1.0 + rate is the same no matter
what, therefore it should have been
calculated outside of the loop
Starts the loop at 1 and goes to 10
Program OutputProgram Output
1 # Fig. 3.24: fig03_24.py
2 # Using the break statement in a for structure.
3
4 for x in range( 1, 11 ):
5
6 if x == 5:
7 break
8
9 print x,
10
11 print "nBroke out of loop at x =", x
59
1 2 3 4
Broke out of loop at x = 5
Shows that the counter does not get
to 10 like it normally would have
When x equals 5 the loop breaks.
Only up to 4 will be displayed
The loop will go from 1 to 10
Program OutputProgram Output
1 # Fig. 3.26: fig03_26.py
2 # Using the continue statement in a for/in structure.
3
4 for x in range( 1, 11 ):
5
6 if x == 5:
7 continue
8
9 print x,
10
11 print "nUsed continue to skip printing the value 5"
60
1 2 3 4 6 7 8 9 10
Used continue to skip printing the value 5
The value 5 will never be
output but all the others will
The loop will continue
if the value equals 5
continue skips rest of body but continues loop
Advantage of PythonAdvantage of Python
61
62

More Related Content

What's hot (20)

Python exception handling
Python   exception handlingPython   exception handling
Python exception handling
 
Arrays in python
Arrays in pythonArrays in python
Arrays in python
 
Loops in Python
Loops in PythonLoops in Python
Loops in Python
 
Python programming : Strings
Python programming : StringsPython programming : Strings
Python programming : Strings
 
Python : Data Types
Python : Data TypesPython : Data Types
Python : Data Types
 
Variables in python
Variables in pythonVariables in python
Variables in python
 
File in C language
File in C languageFile in C language
File in C language
 
Conditional and control statement
Conditional and control statementConditional and control statement
Conditional and control statement
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
String functions in C
String functions in CString functions in C
String functions in C
 
Control statements in c
Control statements in cControl statements in c
Control statements in c
 
Python Modules
Python ModulesPython Modules
Python Modules
 
Character Array and String
Character Array and StringCharacter Array and String
Character Array and String
 
Functions in Python
Functions in PythonFunctions in Python
Functions in Python
 
Functions in python
Functions in pythonFunctions in python
Functions in python
 
Python Flow Control
Python Flow ControlPython Flow Control
Python Flow Control
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
Strings Functions in C Programming
Strings Functions in C ProgrammingStrings Functions in C Programming
Strings Functions in C Programming
 
Python strings
Python stringsPython strings
Python strings
 
Python file handling
Python file handlingPython file handling
Python file handling
 

Similar to Python Control structures

Python programing
Python programingPython programing
Python programinghamzagame
 
Python for Machine Learning
Python for Machine LearningPython for Machine Learning
Python for Machine LearningStudent
 
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
 
Bikalpa_Thapa_Python_Programming_(Basics).pptx
Bikalpa_Thapa_Python_Programming_(Basics).pptxBikalpa_Thapa_Python_Programming_(Basics).pptx
Bikalpa_Thapa_Python_Programming_(Basics).pptxBikalpa Thapa
 
control statements of clangauge (ii unit)
control statements of clangauge (ii unit)control statements of clangauge (ii unit)
control statements of clangauge (ii unit)Prashant Sharma
 
Programming fundamental 02
Programming fundamental 02Programming fundamental 02
Programming fundamental 02Suhail Akraam
 
Learning C programming - from lynxbee.com
Learning C programming - from lynxbee.comLearning C programming - from lynxbee.com
Learning C programming - from lynxbee.comGreen Ecosystem
 
loopingstatementinpython-210628184047 (1).pdf
loopingstatementinpython-210628184047 (1).pdfloopingstatementinpython-210628184047 (1).pdf
loopingstatementinpython-210628184047 (1).pdfDheeravathBinduMadha
 
Slide07 repetitions
Slide07 repetitionsSlide07 repetitions
Slide07 repetitionsaltwirqi
 
Looping statement in python
Looping statement in pythonLooping statement in python
Looping statement in pythonRaginiJain21
 
Loops in C Programming | for Loop | do-while Loop | while Loop | Nested Loop
Loops in C Programming | for Loop | do-while Loop | while Loop | Nested LoopLoops in C Programming | for Loop | do-while Loop | while Loop | Nested Loop
Loops in C Programming | for Loop | do-while Loop | while Loop | Nested LoopPriyom Majumder
 
C Programming: Control Structure
C Programming: Control StructureC Programming: Control Structure
C Programming: Control StructureSokngim Sa
 
FLOW OF CONTROL-INTRO PYTHON
FLOW OF CONTROL-INTRO PYTHONFLOW OF CONTROL-INTRO PYTHON
FLOW OF CONTROL-INTRO PYTHONvikram mahendra
 

Similar to Python Control structures (20)

pythonQuick.pdf
pythonQuick.pdfpythonQuick.pdf
pythonQuick.pdf
 
python notes.pdf
python notes.pdfpython notes.pdf
python notes.pdf
 
python 34💭.pdf
python 34💭.pdfpython 34💭.pdf
python 34💭.pdf
 
Python for Beginners(v2)
Python for Beginners(v2)Python for Beginners(v2)
Python for Beginners(v2)
 
Python programing
Python programingPython programing
Python programing
 
Python for Machine Learning
Python for Machine LearningPython for Machine Learning
Python for Machine Learning
 
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
 
Bikalpa_Thapa_Python_Programming_(Basics).pptx
Bikalpa_Thapa_Python_Programming_(Basics).pptxBikalpa_Thapa_Python_Programming_(Basics).pptx
Bikalpa_Thapa_Python_Programming_(Basics).pptx
 
Conditional Statements
Conditional StatementsConditional Statements
Conditional Statements
 
control statements of clangauge (ii unit)
control statements of clangauge (ii unit)control statements of clangauge (ii unit)
control statements of clangauge (ii unit)
 
03b loops
03b   loops03b   loops
03b loops
 
Loops in Python.pptx
Loops in Python.pptxLoops in Python.pptx
Loops in Python.pptx
 
Programming fundamental 02
Programming fundamental 02Programming fundamental 02
Programming fundamental 02
 
Learning C programming - from lynxbee.com
Learning C programming - from lynxbee.comLearning C programming - from lynxbee.com
Learning C programming - from lynxbee.com
 
loopingstatementinpython-210628184047 (1).pdf
loopingstatementinpython-210628184047 (1).pdfloopingstatementinpython-210628184047 (1).pdf
loopingstatementinpython-210628184047 (1).pdf
 
Slide07 repetitions
Slide07 repetitionsSlide07 repetitions
Slide07 repetitions
 
Looping statement in python
Looping statement in pythonLooping statement in python
Looping statement in python
 
Loops in C Programming | for Loop | do-while Loop | while Loop | Nested Loop
Loops in C Programming | for Loop | do-while Loop | while Loop | Nested LoopLoops in C Programming | for Loop | do-while Loop | while Loop | Nested Loop
Loops in C Programming | for Loop | do-while Loop | while Loop | Nested Loop
 
C Programming: Control Structure
C Programming: Control StructureC Programming: Control Structure
C Programming: Control Structure
 
FLOW OF CONTROL-INTRO PYTHON
FLOW OF CONTROL-INTRO PYTHONFLOW OF CONTROL-INTRO PYTHON
FLOW OF CONTROL-INTRO PYTHON
 

More from Siddique Ibrahim (20)

List in Python
List in PythonList in Python
List in Python
 
Python programming introduction
Python programming introductionPython programming introduction
Python programming introduction
 
Data mining basic fundamentals
Data mining basic fundamentalsData mining basic fundamentals
Data mining basic fundamentals
 
Basic networking
Basic networkingBasic networking
Basic networking
 
Virtualization Concepts
Virtualization ConceptsVirtualization Concepts
Virtualization Concepts
 
Networking devices(siddique)
Networking devices(siddique)Networking devices(siddique)
Networking devices(siddique)
 
Osi model 7 Layers
Osi model 7 LayersOsi model 7 Layers
Osi model 7 Layers
 
Mysql grand
Mysql grandMysql grand
Mysql grand
 
Getting started into mySQL
Getting started into mySQLGetting started into mySQL
Getting started into mySQL
 
pipelining
pipeliningpipelining
pipelining
 
Micro programmed control
Micro programmed controlMicro programmed control
Micro programmed control
 
Hardwired control
Hardwired controlHardwired control
Hardwired control
 
interface
interfaceinterface
interface
 
Interrupt
InterruptInterrupt
Interrupt
 
Interrupt
InterruptInterrupt
Interrupt
 
DMA
DMADMA
DMA
 
Io devies
Io deviesIo devies
Io devies
 
Stack & queue
Stack & queueStack & queue
Stack & queue
 
Metadata in data warehouse
Metadata in data warehouseMetadata in data warehouse
Metadata in data warehouse
 
Data extraction, transformation, and loading
Data extraction, transformation, and loadingData extraction, transformation, and loading
Data extraction, transformation, and loading
 

Recently uploaded

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 

Recently uploaded (20)

How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 

Python Control structures

  • 1. Python Control Structure by S.P. Siddique Ibrahim AP/CSE Kumaraguru College ofTechnology Coimbatore 1
  • 2. IntroductionIntroduction Says the control flow of the statement in the programming language. Show the control flow 2
  • 3. Control StructuresControl Structures 3 control structures ◦ Sequential structure  Built into Python ◦ Decision/ Selection structure  The if statement  The if/else statement  The if/elif/else statement ◦ Repetition structure / Iterative  The while repetition structure  The for repetition structure 3
  • 4. 4
  • 5. Sequential StructureSequential Structure Normal flow/sequential execution of the statement. Line by line/Normal execution If you want to perform simple addition: A=5 B=6 Print(A+B) 5
  • 6. Sequence Control StructureSequence Control Structure 6 Fig. 3.1 Sequence structure flowchart with pseudo code. add grade to total add 1 to counter total = total + grade; counter = counter + 1;
  • 7. Decision Control flowDecision Control flow There will be a condition and based on the condition parameter then the control will be flow in only one direction. 7
  • 8. 8
  • 9. 9
  • 10. 10
  • 11. 11
  • 12. ifif Selection StructureSelection Structure 12 Fig. 3.3 if single-selection structure flowchart. print “Passed”Grade >= 60 true false
  • 13. 13
  • 14. 14
  • 15. 15
  • 16. 16
  • 17. 17
  • 19.  >>> x = 0  >>> y = 5  >>> if x < y: # Truthy  ... print('yes')  ...  yes  >>> if y < x: # Falsy  ... print('yes')  ...  >>> if x: # Falsy  ... print('yes')  ...  >>> if y: # Truthy  ... print('yes')  ...  yes  >>> if x or y: # Truthy  ... print('yes')  ...  yes 19
  • 20.  >>> if x and y: # Falsy  ... print('yes')  ...  >>> if 'aul' in 'grault': # Truthy  ... print('yes')  ...  yes  >>> if 'quux' in ['foo', 'bar', 'baz']: # Falsy  ... print('yes') 20
  • 22. if/elseif/else StructureStructure 22 Fig. 3.4 if/else double-selection structure flowchart. Grade >= 60 print “Passed”print “Failed” false true
  • 23. 23
  • 24. Class ActivityClass Activity # Program checks if the number is positive or negative and displays an appropriate message # Program checks if the number is positive or negative –Get the input from the user also checks the zero inside the positive value 24
  • 25. num = 3 # Try these two variations as well. # num = -5 # num = 0 if num >= 0: print("Positive or Zero") else: print("Negative number") 25
  • 27. if/elif/elseif/elif/else SelectionSelection StructureStructure 27 condition a true false . . . false false condition z default action(s) true true condition b case a action(s) case b action(s) case z action(s) if statement first elif statement last elif statement else statement Fig. 3.5 if/elif/else multiple-selection structure.
  • 29. Example Python codeExample Python code 29
  • 30. Example with Python codeExample with Python code 30 # get price from user and convert it into a float: price = float( raw_input(“Enter the price of one tomato: “)) if price < 1: s = “That’s cheap, buy a lot!” elif price < 3: s = “Okay, buy a few” else: s = “Too much, buy some carrots instead” print s
  • 32. 32
  • 33. 3.73.7 whilewhile Repetition StructureRepetition Structure 33 true false Product = 2 * productProduct <= 1000 Fig. 3.8 while repetition structure flowchart.
  • 34. When we login to our homepage on Facebook, we have about 10 stories loaded on our newsfeed As soon as we reach the end of the page, Facebook loads another 10 stories onto our newsfeed This demonstrates how ‘while’ loop can be used to achieve this 34
  • 35. 35
  • 36. 36
  • 37. 37
  • 38. Listing ‘Friends’ from your profile will display the names and photos of all of your friends To achieve this, Facebook gets your ‘friendlist’ list containing all the profiles of your friends Facebook then starts displaying the HTML of all the profiles till the list index reaches ‘NULL’ The action of populating all the profiles onto your page is controlled by ‘for’ statement 38
  • 39. 3.133.13 forfor Repetition StructureRepetition Structure The for loop ◦ Function range is used to create a list of values  range ( integer )  Values go from 0 up to given integer (i.e., not including)  range ( integer, integer )  Values go from first up to second integer  range ( integer, integer, integer )  Values go from first up to second integer but increases in intervals of the third integer ◦ This loop will execute howmany times: for counter in range ( howmany ): and counter will have values 0, 1,.. howmany-1 39
  • 40. for counter in range(10): print (counter) Output? 40
  • 41. 41
  • 42. 42
  • 43. 43
  • 44. 44
  • 45. 45
  • 46. # Prints out 0,1,2,3,4 count = 0 while True:  print(count)  count += 1  if count >= 5:  break # Prints out only odd numbers - 1,3,5,7,9 for x in range(10): # Check if x is even  if x % 2 == 0:  continue  print(x) 46
  • 47. 47
  • 48. Example for PassExample for Pass 48
  • 49. Expression values?Expression values? 49 Python 2.2b2 (#26, Nov 16 2001, 11:44:11) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> if 0: ... print "0 is true" ... else: ... print "0 is false" ... 0 is false >>> if 1: ... print "non-zero is true" ... non-zero is true >>> if -1: ... print "non-zero is true" ... non-zero is true >>> print 2 < 3 1 Expressions have integer values. No true, false like in Java. 0 is false, non-0 is true.
  • 50. 3.16 Logical Operators3.16 Logical Operators Operators ◦ and  Binary. Evaluates to true if both expressions are true ◦ or  Binary. Evaluates to true if at least one expression is true ◦ not  Unary. Returns true if the expression is false 50 Compare with &&, || and ! in Java
  • 51. Logical operatorsLogical operators andand,, oror,, notnot 51 if gender == “female” and age >= 65: seniorfemales = seniorfemales + 1 if iq > 250 or iq < 20: strangevalues = strangevalues + 1 if not found_what_we_need: print “didn’t find item” # NB: can also use != if i != j: print “Different values”
  • 53. 3.11 Augmented Assignment3.11 Augmented Assignment SymbolsSymbols Augmented addition assignment symbols ◦ x = x + 5 is the same as x += 5 ◦ Can’t use ++ like in Java! Other math signs ◦ The same rule applies to any other mathematical symbol *, **, /, % 53
  • 54. KeywordsKeywords 54 Python keywords and continue else for import not raise assert def except from in or return break del exec global is pass try class elif finally if lambda print while Fig. 3.2 Python keywords. Can’t use as identifiers
  • 55. keywordkeyword passpass : do nothing: do nothing 55 Python 2.2b2 (#26, Nov 16 2001, 11:44:11) [MSC 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> if 1 < 2: ... pass ... Sometimes useful, e.g. during development: if a <= 5 and c <= 5: print “Oh no, both below 5! Fix problem” if a > 5 and c <= 5: pass # figure out what to do later if a <= 5 and c > 5: pass # figure out what to do later if a > 5 and c > 5: pass # figure out what to do later
  • 56. Program OutputProgram Output 1 # Fig. 3.10: fig03_10.py 2 # Class average program with counter-controlled repetition. 3 4 # initialization phase 5 total = 0 # sum of grades 6 gradeCounter = 1 # number of grades entered 7 8 # processing phase 9 while gradeCounter <= 10: # loop 10 times 10 grade = raw_input( "Enter grade: " ) # get one grade 11 grade = int( grade ) # convert string to an integer 12 total = total + grade 13 gradeCounter = gradeCounter + 1 14 15 # termination phase 16 average = total / 10 # integer division 17 print "Class average is", average 56 Enter grade: 98 Enter grade: 76 Enter grade: 71 Enter grade: 87 Enter grade: 83 Enter grade: 90 Enter grade: 57 Enter grade: 79 Enter grade: 82 Enter grade: 94 Class average is 81 The total and counter, set to zero and one respectively A loop the continues as long as the counter does not go past 10 Adds one to the counter to eventually break the loop Divides the total by the 10 to get the class average
  • 57. Program OutputProgram Output1 # Fig. 3.22: fig03_22.py 2 # Summation with for. 3 4 sum = 0 5 6 for number in range( 2, 101, 2 ): 7 sum += number 8 9 print "Sum is", sum 57 Sum is 2550 Loops from 2 to 101 in increments of 2 A sum of all the even numbers from 2 to 100 Another example
  • 58. Program OutputProgram Output 1 # Fig. 3.23: fig03_23.py 2 # Calculating compound interest. 3 4 principal = 1000.0 # starting principal 5 rate = .05 # interest rate 6 7 print "Year %21s" % "Amount on deposit" 8 9 for year in range( 1, 11 ): 10 amount = principal * ( 1.0 + rate ) ** year 11 print "%4d%21.2f" % ( year, amount ) 58 Year Amount on deposit 1 1050.00 2 1102.50 3 1157.63 4 1215.51 5 1276.28 6 1340.10 7 1407.10 8 1477.46 9 1551.33 10 1628.89 1.0 + rate is the same no matter what, therefore it should have been calculated outside of the loop Starts the loop at 1 and goes to 10
  • 59. Program OutputProgram Output 1 # Fig. 3.24: fig03_24.py 2 # Using the break statement in a for structure. 3 4 for x in range( 1, 11 ): 5 6 if x == 5: 7 break 8 9 print x, 10 11 print "nBroke out of loop at x =", x 59 1 2 3 4 Broke out of loop at x = 5 Shows that the counter does not get to 10 like it normally would have When x equals 5 the loop breaks. Only up to 4 will be displayed The loop will go from 1 to 10
  • 60. Program OutputProgram Output 1 # Fig. 3.26: fig03_26.py 2 # Using the continue statement in a for/in structure. 3 4 for x in range( 1, 11 ): 5 6 if x == 5: 7 continue 8 9 print x, 10 11 print "nUsed continue to skip printing the value 5" 60 1 2 3 4 6 7 8 9 10 Used continue to skip printing the value 5 The value 5 will never be output but all the others will The loop will continue if the value equals 5 continue skips rest of body but continues loop
  • 62. 62

Editor's Notes

  1. https://www.edureka.co/blog/python-programming-language#FlowControl