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

More Related Content

PPT
Industrial psychology
PPTX
Python
DOCX
Consumers Buying Behaviour at Pantaloons Patna 2017 (Part II)
PPTX
Python variables and data types.pptx
PPT
programming with python ppt
PPTX
Looping statement in python
PPTX
Scope rules : local and global variables
PDF
Line and staff authority, departmentalization
Industrial psychology
Python
Consumers Buying Behaviour at Pantaloons Patna 2017 (Part II)
Python variables and data types.pptx
programming with python ppt
Looping statement in python
Scope rules : local and global variables
Line and staff authority, departmentalization

What's hot (20)

PPTX
Tuple in python
PPTX
Variables in python
PDF
Datatypes in python
PDF
Operators in python
PPTX
Python Functions
PPTX
Values and Data types in python
PDF
Introduction to python programming
PPTX
Chapter 05 classes and objects
PPTX
python conditional statement.pptx
PDF
Python Flow Control
PDF
Control Structures in Python
PDF
Introduction to Python
PDF
Lesson 02 python keywords and identifiers
PPT
Basic concept of OOP's
ODP
Python Modules
PDF
Variables & Data Types In Python | Edureka
PDF
Python programming : Classes objects
PPTX
Python for loop
PPTX
Nested loops
Tuple in python
Variables in python
Datatypes in python
Operators in python
Python Functions
Values and Data types in python
Introduction to python programming
Chapter 05 classes and objects
python conditional statement.pptx
Python Flow Control
Control Structures in Python
Introduction to Python
Lesson 02 python keywords and identifiers
Basic concept of OOP's
Python Modules
Variables & Data Types In Python | Edureka
Python programming : Classes objects
Python for loop
Nested loops
Ad

Similar to Python Control structures (20)

PPTX
Chapter 2-Python and control flow statement.pptx
PDF
pythonQuick.pdf
PDF
python notes.pdf
PDF
python 34💭.pdf
PPTX
Python for Beginners(v2)
PPTX
Python programing
PPTX
TN 12 computer Science - ppt CHAPTER-6.pptx
PDF
Python for Machine Learning
PPT
introduction to python in english presentation file
PPTX
Bikalpa_Thapa_Python_Programming_(Basics).pptx
PDF
Conditional Statements
PDF
2 Python Basics II meeting 2 tunghai university pdf
PPTX
control statements of clangauge (ii unit)
PPTX
1. control structures in the python.pptx
PPTX
made it easy: python quick reference for beginners
PPT
03b loops
PPTX
PDF
Programming fundamental 02
PDF
Learning C programming - from lynxbee.com
PDF
loopingstatementinpython-210628184047 (1).pdf
Chapter 2-Python and control flow statement.pptx
pythonQuick.pdf
python notes.pdf
python 34💭.pdf
Python for Beginners(v2)
Python programing
TN 12 computer Science - ppt CHAPTER-6.pptx
Python for Machine Learning
introduction to python in english presentation file
Bikalpa_Thapa_Python_Programming_(Basics).pptx
Conditional Statements
2 Python Basics II meeting 2 tunghai university pdf
control statements of clangauge (ii unit)
1. control structures in the python.pptx
made it easy: python quick reference for beginners
03b loops
Programming fundamental 02
Learning C programming - from lynxbee.com
loopingstatementinpython-210628184047 (1).pdf
Ad

More from Siddique Ibrahim (20)

PPTX
List in Python
PPTX
Python programming introduction
PPT
Data mining basic fundamentals
PPT
Basic networking
PPT
Virtualization Concepts
PPT
Networking devices(siddique)
PPT
Osi model 7 Layers
PPT
Mysql grand
PPT
Getting started into mySQL
PPT
pipelining
PPT
Micro programmed control
PPTX
Hardwired control
PPT
interface
PPT
Interrupt
PPT
Interrupt
PPT
Io devies
PPT
Stack & queue
PPT
Metadata in data warehouse
PPTX
Data extraction, transformation, and loading
List in Python
Python programming introduction
Data mining basic fundamentals
Basic networking
Virtualization Concepts
Networking devices(siddique)
Osi model 7 Layers
Mysql grand
Getting started into mySQL
pipelining
Micro programmed control
Hardwired control
interface
Interrupt
Interrupt
Io devies
Stack & queue
Metadata in data warehouse
Data extraction, transformation, and loading

Recently uploaded (20)

PDF
Empathic Computing: Creating Shared Understanding
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
Electronic commerce courselecture one. Pdf
PDF
cuic standard and advanced reporting.pdf
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Approach and Philosophy of On baking technology
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PPTX
A Presentation on Artificial Intelligence
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Encapsulation theory and applications.pdf
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
Empathic Computing: Creating Shared Understanding
Network Security Unit 5.pdf for BCA BBA.
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Electronic commerce courselecture one. Pdf
cuic standard and advanced reporting.pdf
NewMind AI Weekly Chronicles - August'25 Week I
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
Agricultural_Statistics_at_a_Glance_2022_0.pdf
20250228 LYD VKU AI Blended-Learning.pptx
MYSQL Presentation for SQL database connectivity
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Unlocking AI with Model Context Protocol (MCP)
Approach and Philosophy of On baking technology
Understanding_Digital_Forensics_Presentation.pptx
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
A Presentation on Artificial Intelligence
The AUB Centre for AI in Media Proposal.docx
Encapsulation theory and applications.pdf
Mobile App Security Testing_ A Comprehensive Guide.pdf

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