SlideShare a Scribd company logo
๏‚—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
Ad

More Related Content

What's hot (20)

Python programming : Standard Input and Output
Python programming : Standard Input and OutputPython programming : Standard Input and Output
Python programming : Standard Input and Output
Emertxe Information Technologies Pvt Ltd
ย 
Set methods in python
Set methods in pythonSet methods in python
Set methods in python
deepalishinkar1
ย 
Python exception handling
Python   exception handlingPython   exception handling
Python exception handling
Mohammed Sikander
ย 
Python Functions
Python   FunctionsPython   Functions
Python Functions
Mohammed Sikander
ย 
Strings
StringsStrings
Strings
Mitali Chugh
ย 
Data Structures in Python
Data Structures in PythonData Structures in Python
Data Structures in Python
Devashish Kumar
ย 
Exception handling c++
Exception handling c++Exception handling c++
Exception handling c++
Jayant Dalvi
ย 
Python : Functions
Python : FunctionsPython : Functions
Python : Functions
Emertxe Information Technologies Pvt Ltd
ย 
Function in C program
Function in C programFunction in C program
Function in C program
Nurul Zakiah Zamri Tan
ย 
stack & queue
stack & queuestack & queue
stack & queue
manju rani
ย 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
Megha V
ย 
Loops in Python
Loops in PythonLoops in Python
Loops in Python
Arockia Abins
ย 
Python dictionary
Python   dictionaryPython   dictionary
Python dictionary
Mohammed Sikander
ย 
Python tuple
Python   tuplePython   tuple
Python tuple
Mohammed Sikander
ย 
Character Array and String
Character Array and StringCharacter Array and String
Character Array and String
Tasnima Hamid
ย 
Python built in functions
Python built in functionsPython built in functions
Python built in functions
Rakshitha S
ย 
Dictionaries in Python
Dictionaries in PythonDictionaries in Python
Dictionaries in Python
baabtra.com - No. 1 supplier of quality freshers
ย 
Unit 3. Input and Output
Unit 3. Input and OutputUnit 3. Input and Output
Unit 3. Input and Output
Ashim Lamichhane
ย 
Python programming : Control statements
Python programming : Control statementsPython programming : Control statements
Python programming : Control statements
Emertxe Information Technologies Pvt Ltd
ย 
Conditional and control statement
Conditional and control statementConditional and control statement
Conditional and control statement
narmadhakin
ย 

Similar to Python Control structures (20)

Chapter 2-Python and control flow statement.pptx
Chapter 2-Python and control flow statement.pptxChapter 2-Python and control flow statement.pptx
Chapter 2-Python and control flow statement.pptx
atharvdeshpande20
ย 
pythonQuick.pdf
pythonQuick.pdfpythonQuick.pdf
pythonQuick.pdf
PhanMinhLinhAnxM0190
ย 
python notes.pdf
python notes.pdfpython notes.pdf
python notes.pdf
RohitSindhu10
ย 
python 34๐Ÿ’ญ.pdf
python 34๐Ÿ’ญ.pdfpython 34๐Ÿ’ญ.pdf
python 34๐Ÿ’ญ.pdf
AkashdeepBhattacharj1
ย 
Python for Beginners(v2)
Python for Beginners(v2)Python for Beginners(v2)
Python for Beginners(v2)
Panimalar Engineering College
ย 
Python programing
Python programingPython programing
Python programing
hamzagame
ย 
TN 12 computer Science - ppt CHAPTER-6.pptx
TN 12 computer Science - ppt CHAPTER-6.pptxTN 12 computer Science - ppt CHAPTER-6.pptx
TN 12 computer Science - ppt CHAPTER-6.pptx
knmschool
ย 
Python for Machine Learning
Python for Machine LearningPython for Machine Learning
Python for Machine Learning
Student
ย 
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
RujanTimsina1
ย 
Bikalpa_Thapa_Python_Programming_(Basics).pptx
Bikalpa_Thapa_Python_Programming_(Basics).pptxBikalpa_Thapa_Python_Programming_(Basics).pptx
Bikalpa_Thapa_Python_Programming_(Basics).pptx
Bikalpa Thapa
ย 
Conditional Statements
Conditional StatementsConditional Statements
Conditional Statements
MuhammadBakri13
ย 
2 Python Basics II meeting 2 tunghai university pdf
2 Python Basics II meeting 2 tunghai university pdf2 Python Basics II meeting 2 tunghai university pdf
2 Python Basics II meeting 2 tunghai university pdf
Anggi Andriyadi
ย 
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
ย 
1. control structures in the python.pptx
1. control structures in the python.pptx1. control structures in the python.pptx
1. control structures in the python.pptx
DURAIMURUGANM2
ย 
made it easy: python quick reference for beginners
made it easy: python quick reference for beginnersmade it easy: python quick reference for beginners
made it easy: python quick reference for beginners
SumanMadan4
ย 
03b loops
03b   loops03b   loops
03b loops
Manzoor ALam
ย 
Loops in Python.pptx
Loops in Python.pptxLoops in Python.pptx
Loops in Python.pptx
Guru Nanak Dev University, Amritsar
ย 
Programming fundamental 02
Programming fundamental 02Programming fundamental 02
Programming fundamental 02
Suhail Akraam
ย 
Learning C programming - from lynxbee.com
Learning C programming - from lynxbee.comLearning C programming - from lynxbee.com
Learning C programming - from lynxbee.com
Green Ecosystem
ย 
loopingstatementinpython-210628184047 (1).pdf
loopingstatementinpython-210628184047 (1).pdfloopingstatementinpython-210628184047 (1).pdf
loopingstatementinpython-210628184047 (1).pdf
DheeravathBinduMadha
ย 
Chapter 2-Python and control flow statement.pptx
Chapter 2-Python and control flow statement.pptxChapter 2-Python and control flow statement.pptx
Chapter 2-Python and control flow statement.pptx
atharvdeshpande20
ย 
python notes.pdf
python notes.pdfpython notes.pdf
python notes.pdf
RohitSindhu10
ย 
Python programing
Python programingPython programing
Python programing
hamzagame
ย 
TN 12 computer Science - ppt CHAPTER-6.pptx
TN 12 computer Science - ppt CHAPTER-6.pptxTN 12 computer Science - ppt CHAPTER-6.pptx
TN 12 computer Science - ppt CHAPTER-6.pptx
knmschool
ย 
Python for Machine Learning
Python for Machine LearningPython for Machine Learning
Python for Machine Learning
Student
ย 
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
RujanTimsina1
ย 
Bikalpa_Thapa_Python_Programming_(Basics).pptx
Bikalpa_Thapa_Python_Programming_(Basics).pptxBikalpa_Thapa_Python_Programming_(Basics).pptx
Bikalpa_Thapa_Python_Programming_(Basics).pptx
Bikalpa Thapa
ย 
Conditional Statements
Conditional StatementsConditional Statements
Conditional Statements
MuhammadBakri13
ย 
2 Python Basics II meeting 2 tunghai university pdf
2 Python Basics II meeting 2 tunghai university pdf2 Python Basics II meeting 2 tunghai university pdf
2 Python Basics II meeting 2 tunghai university pdf
Anggi Andriyadi
ย 
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
ย 
1. control structures in the python.pptx
1. control structures in the python.pptx1. control structures in the python.pptx
1. control structures in the python.pptx
DURAIMURUGANM2
ย 
made it easy: python quick reference for beginners
made it easy: python quick reference for beginnersmade it easy: python quick reference for beginners
made it easy: python quick reference for beginners
SumanMadan4
ย 
03b loops
03b   loops03b   loops
03b loops
Manzoor ALam
ย 
Programming fundamental 02
Programming fundamental 02Programming fundamental 02
Programming fundamental 02
Suhail Akraam
ย 
Learning C programming - from lynxbee.com
Learning C programming - from lynxbee.comLearning C programming - from lynxbee.com
Learning C programming - from lynxbee.com
Green Ecosystem
ย 
loopingstatementinpython-210628184047 (1).pdf
loopingstatementinpython-210628184047 (1).pdfloopingstatementinpython-210628184047 (1).pdf
loopingstatementinpython-210628184047 (1).pdf
DheeravathBinduMadha
ย 
Ad

More from Siddique Ibrahim (20)

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

Recently uploaded (20)

The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
ย 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
ย 
"PHP and MySQL CRUD Operations for Student Management System"
"PHP and MySQL CRUD Operations for Student Management System""PHP and MySQL CRUD Operations for Student Management System"
"PHP and MySQL CRUD Operations for Student Management System"
Jainul Musani
ย 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
ย 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
ย 
Network Security. Different aspects of Network Security.
Network Security. Different aspects of Network Security.Network Security. Different aspects of Network Security.
Network Security. Different aspects of Network Security.
gregtap1
ย 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
ย 
Drupalcamp Finland โ€“ Measuring Front-end Energy Consumption
Drupalcamp Finland โ€“ Measuring Front-end Energy ConsumptionDrupalcamp Finland โ€“ Measuring Front-end Energy Consumption
Drupalcamp Finland โ€“ Measuring Front-end Energy Consumption
Exove
ย 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
ย 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
ย 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
ย 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
ย 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
ย 
Hands On: Create a Lightning Aura Component with force:RecordData
Hands On: Create a Lightning Aura Component with force:RecordDataHands On: Create a Lightning Aura Component with force:RecordData
Hands On: Create a Lightning Aura Component with force:RecordData
Lynda Kane
ย 
"Client Partnership โ€” the Path to Exponential Growth for Companies Sized 50-5...
"Client Partnership โ€” the Path to Exponential Growth for Companies Sized 50-5..."Client Partnership โ€” the Path to Exponential Growth for Companies Sized 50-5...
"Client Partnership โ€” the Path to Exponential Growth for Companies Sized 50-5...
Fwdays
ย 
Automation Dreamin' 2022: Sharing Some Gratitude with Your Users
Automation Dreamin' 2022: Sharing Some Gratitude with Your UsersAutomation Dreamin' 2022: Sharing Some Gratitude with Your Users
Automation Dreamin' 2022: Sharing Some Gratitude with Your Users
Lynda Kane
ย 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
ย 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
ย 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
ย 
Leading AI Innovation As A Product Manager - Michael Jidael
Leading AI Innovation As A Product Manager - Michael JidaelLeading AI Innovation As A Product Manager - Michael Jidael
Leading AI Innovation As A Product Manager - Michael Jidael
Michael Jidael
ย 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
ย 
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
AI EngineHost Review: Revolutionary USA Datacenter-Based Hosting with NVIDIA ...
SOFTTECHHUB
ย 
"PHP and MySQL CRUD Operations for Student Management System"
"PHP and MySQL CRUD Operations for Student Management System""PHP and MySQL CRUD Operations for Student Management System"
"PHP and MySQL CRUD Operations for Student Management System"
Jainul Musani
ย 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
ย 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
ย 
Network Security. Different aspects of Network Security.
Network Security. Different aspects of Network Security.Network Security. Different aspects of Network Security.
Network Security. Different aspects of Network Security.
gregtap1
ย 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
ย 
Drupalcamp Finland โ€“ Measuring Front-end Energy Consumption
Drupalcamp Finland โ€“ Measuring Front-end Energy ConsumptionDrupalcamp Finland โ€“ Measuring Front-end Energy Consumption
Drupalcamp Finland โ€“ Measuring Front-end Energy Consumption
Exove
ย 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
ย 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
ย 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
ย 
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In FranceManifest Pre-Seed Update | A Humanoid OEM Deeptech In France
Manifest Pre-Seed Update | A Humanoid OEM Deeptech In France
chb3
ย 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
ย 
Hands On: Create a Lightning Aura Component with force:RecordData
Hands On: Create a Lightning Aura Component with force:RecordDataHands On: Create a Lightning Aura Component with force:RecordData
Hands On: Create a Lightning Aura Component with force:RecordData
Lynda Kane
ย 
"Client Partnership โ€” the Path to Exponential Growth for Companies Sized 50-5...
"Client Partnership โ€” the Path to Exponential Growth for Companies Sized 50-5..."Client Partnership โ€” the Path to Exponential Growth for Companies Sized 50-5...
"Client Partnership โ€” the Path to Exponential Growth for Companies Sized 50-5...
Fwdays
ย 
Automation Dreamin' 2022: Sharing Some Gratitude with Your Users
Automation Dreamin' 2022: Sharing Some Gratitude with Your UsersAutomation Dreamin' 2022: Sharing Some Gratitude with Your Users
Automation Dreamin' 2022: Sharing Some Gratitude with Your Users
Lynda Kane
ย 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
ย 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
ย 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
ย 
Leading AI Innovation As A Product Manager - Michael Jidael
Leading AI Innovation As A Product Manager - Michael JidaelLeading AI Innovation As A Product Manager - Michael Jidael
Leading AI Innovation As A Product Manager - Michael Jidael
Michael Jidael
ย 

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

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