SlideShare a Scribd company logo
1
Programming with Python for Engineers
Lecture-6
Lecture : Week-6
Subject : Repetitive Execution
- while & for statements
- continue & break
- List comprehension
Lecturer: Hüseyin SAYIN
E-Mail : hsayin@metu.edu.tr
Coordinating Assistant : Alperen Dalkıran
Support E-Mail : 2xx@ceng.metu.edu.tr
2
Objectives
• In this chapter, you will learn:
– Repetitive execution in Python:
* while & for statements; continue & break;
* List comprehension;
3
Repetitive Execution
(iteration or loop)
iteration/loop: Repeating a sequence of
instructions over-and-over is a programming
ingredient
• iteration/loop is used for;
- to systematically deal with all possible cases
or all elements of a collection.
- to jump from one case to another as a
function of the previous case.
4
Repetitive Execution
(iteration or loop)
Python provides two statements for iteration.
Namely, while and for. whereas.
• for is used mostly for (Type I) iterations.
• while is used for both types.
5
Repetitive Execution
(iteration or loop)
The repetition of a sequence of instructions is
carried out either for a known number of times
or until a criterion is met
• Computing letter grades of a class (Type I)
for all students.
• Finding the shortest path from city A to city B in
a map (Type II).
• Root finding by Newton-Raphson method
(Type II).
• Finding darkest and brightest point(s) in an
image (Type I, for all pixels).
6
Repetitive Execution
(iteration or loop)
The repetition of a sequence of instructions is
carried out either for a known number of times or
until a criterion is met
• Computing a function value using Taylor’s
expansion (Type I).
• Computing the next move in a chess game
(Type II).
• Obtaining the letter frequency of a text (Type I)
for all letters.
7
Repetitive Execution
(iteration or loop)
Python provides two statements for iteration.
Namely, while and for. whereas.
• for is used mostly for (Type I) iterations.
• while is used for both types.
The syntax of while resembles the syntax of the if
statement:
• Certainly possible to have a statement group
subject to the while.
• while statement execution is;
8
The while Statement
Since a while statement is a statement, it can be
part of another while statement (or any other
compound statement):
9
The Nested Loops
The "inner loop" will be executed one time for
each iteration of the "outer loop".
Example: Print each adjective for every fruit.
Python Code: Output:
10
The while Statement
11
Structured-Programming Summary
12
• Infinite Loops
…
while 1: # while true
print(“Infinite Loop”)
…
while -9:
print (“Infinite Loop”)
…
The while Repetition Statement
13
• Infinite Loops
…
while true: # while true
print(“Infinite Loop”)
…
while -9:
print (“Infinite Loop”)
…
The while Repetition Statement
14
• Infinite Loops
…
vCounter = 1
while vCounter:
print (“{ounter}n”)
vCounter += 1
The while Repetition Statement
15
• Null Loops
…
while 0:
print(“Null Loop”)
…
…
while false:
print(“Null Loop”)
…
The while Repetition Statement
Example 1: Finding Average of Numbers in a
List:
• Finding a list of numbers average.
• The mathematical definition:
• Li is the ith number in the list which contains N
numbers
16
Examples with while Statement
Example 1: Finding Average of Numbers in a
List:
• The algorithm before implementing a solution in
Python.
• Pseudocode
17
Examples with while Statement
Example 1: Finding Average of Numbers in a
List:
Python Code
Program Output: 18
Examples with while Statement
Example 2: Factorial of a number
n! can be defined formally as.
• The mathematical definition:
19
Examples with while Statement
Example 2: Factorial of a number
n! can be defined formally as.
Pseudocode:
20
Examples with while Statement
Example 2: Factorial of a number
n! can be defined formally as:
Python Code:
Program Output: 21
Examples with while Statement
The syntax of for resembles the syntax of the if
statement:
• An iterator is an object that provides a
countable number of values on demand..
• It has an internal mechanism; that responds to
three requests:
1. Reset (initialize) it to the start.
2. Respond to the “Are we at the end?” question.
3. Provide the next value in line.
22
for Statement
The semantics of the for statement is;
23
for Statement
What iterators do we have?
1. All containers are also iterators (strings, lists,
dictionaries, sets).
2. The built-in function range returns an iterator
that generates a sequence of integers,
starting from 0 (default), and increments by 1
(default), and stops before a given number.
24
for Statement
Example 1: Using the start parameter.
Python Code:
Output:
25
Examples with for and range() Statement
Example 2: Using the start parameter.
Python Code:
Output:
26
Examples with for and range() Statement
Example 3: Using the start parameter.
Python Code:
Output:
27
Examples with for and range() Statement
Example 3: Using the start parameter.
Python Code:
Output:
28
Examples with for and range() Statement
The "inner loop" will be executed one time for
each iteration of the "outer loop".
Example: Print each adjective for every fruit.
Python Code: Output:
29
The Nested Loops
Example 1: split a list of words into two lists:
those that start with a vowel and those that start
with a consonant.
Python Code:
30
Examples with for Statement
To alter the flow of execution in a while or for
repetition:
• almost always used in combination with statement
grouping (a group of statements is subject to the while
or for),
• executing a sequence of statements by means of
statement grouping,
• Somewhere in the process, without waiting for the
terminating condition to become False in a while
statement or exhausting all items in the iterator in a for
statement, you decide to terminate looping.
31
continue and break Statements
To alter the flow of execution in a while or for
repetition:
• The break statement does exactly serve this purpose:
The while (or for) is stopped immediately and the
execution continues with the statement after the while
(or for).
• Stops the loop altogether, and goes on with
the next instruction after the loop end.
• Somewhere in the process you decide not to execute
the rest of the statements in the grouping and straight
away continue with the test. This is achieved by a
continue statement usage.
• stops the current iteration and tells Python to execute
the next one. 32
continue and break Statements
How continue and break statements change
execution in a while statement:
33
continue and break Statements
How continue and break statements change
execution in a for statement:
34
continue and break Statements
With the continue statement we can stop the
current iteration, and continue with the next.
Python Code: Output:
35
continue and break Statements
This notation has three parts (from left-to-right):
or as something more elaborate:
Python Code: Output:
36
continue and break Statements
This notation has three parts (from left-to-right):
or as something more elaborate:
Python Code: Output:
37
continue and break Statements
A well-known and extensively-used notation to
describe a set in mathematics is the so-called
‘set-builder notation’. This is also known as set
comprehension. List comprehensions are a way
to create lists in a very concise way.
This notation has three parts (from left-to-right):
1. an expression in terms of a variable,
2. a colon or vertical bar separator, and
3. a logical predicate.
38
set and list Comprehension
This notation has three parts (from left-to-right):
Something like this:
which defines the set:
39
set and list Comprehension
This notation has three parts (from left-to-right):
or as something more elaborate:
Python Code:
40
set and list Comprehension
This notation has three parts (from left-to-right):
or as something more elaborate:
which defines the set:
41
set and list Comprehension
This notation has three parts (from left-to-right):
or as something more elaborate:
Python Code:
42
set and list Comprehension
Example-3:
Python Code:
Output:
43
set and list Comprehension
Example-3:
Python Code:
print( [[0 for i in range(3)] for j in range(4)] )
Output:
[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0] ]
44
set and list Comprehension
Example-3:
Python Code:
print( [[0 for i in range(3)] for j in range(4)] )
Output:
[
[0, 0, 0],
[0, 0, 0],
[0, 0, 0],
[0, 0, 0]
]
45
set and list Comprehension
Example-4:
Python Code:
print( [[1 if i==j else 0 for i in range(3)] for j
in range(3)] )
Output:
[[1, 0, 0], [0, 1, 0], [0, 0, 1]]
46
set and list Comprehension
Example-4:
Python Code:
print( [[1 if i==j else 0 for i in range(3)] for j
in range(3)] )
Output:
[[1, 0, 0],
[0, 1, 0],
[0, 0, 1]]
47
set and list Comprehension
Example-5:
Python Code:
print( [[(i,j) for i in range(3)] for j
in range(4)] )
Output:
[[(0, 0),(1, 0),(2, 0)],[(0, 1),(1, 1),(2, 1)],
[(0, 2),(1, 2),(2, 2)],[(0, 3),(1, 3),(2, 3)]]
48
set and list Comprehension
Example-5:
Python Code:
print( [[(i,j) for i in range(3)] for j
in range(4)] )
Output:
[
[(0, 0), (1, 0), (2, 0)],
[(0, 1), (1, 1), (2, 1)],
[(0, 2), (1, 2), (2, 2)],
[(0, 3), (1, 3), (2, 3)]
]
49
set and list Comprehension
Example-6:
Python Code:
print( [[(i+j)%2 for i in range(3)] for j
in range(4)] )
Output:
[[0, 1, 0], [1, 0, 1], [0, 1, 0], [1, 0, 1]]
50
set and list Comprehension
Example-6:
Python Code:
print( [[(i+j)%2 for i in range(3)] for j
in range(4)] )
Output:
[[0, 1, 0],
[1, 0, 1],
[0, 1, 0],
[1, 0, 1]]
51
set and list Comprehension
Example-7:
Python Code:
print( [[i+3*j for i in range(3)] for j
in range(4)] )
Output:
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]]
52
set and list Comprehension
Example-7:
Python Code:
print( [[i+3*j for i in range(3)] for j
in range(4)] )
Output:
[[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[9,10,11]]
53
set and list Comprehension
54
Chapter Objectives
In this chapter, you will learn:
• Repetitive execution in Python
– Repetitive execution with while and for statements.
– Changing the flow of iterations with break and
continue statements,
– Set and list comprehension as a form of iterative
computation in an expression.
Questions?
56
The break and continue Statements
• break
– Causes immediate exit from a while or for statement
– Program execution continues with the first statement after
the structure
– Common uses of the break statement
• Escape early from a loop

More Related Content

PDF
Introduction-to-Python-print-datatype.pdf
PPTX
Mastering Python lesson 3a
PDF
Python Loop
PDF
Data Structure Algorithm - Recursion Book Slides
PPTX
Unit - 2 CAP.pptx
PPTX
Python Introduction controll structures and conprehansion
PDF
Unit 1- Part-2-Control and Loop Statements.pdf
PPTX
python BY ME-2021python anylssis(1).pptx
Introduction-to-Python-print-datatype.pdf
Mastering Python lesson 3a
Python Loop
Data Structure Algorithm - Recursion Book Slides
Unit - 2 CAP.pptx
Python Introduction controll structures and conprehansion
Unit 1- Part-2-Control and Loop Statements.pdf
python BY ME-2021python anylssis(1).pptx

Similar to ceng4315636732530_1245235week_06_0.7.pdf (20)

PDF
Python Decision Making And Loops.pdf
PPTX
Introduction To Python.pptx
PPT
Python Basics
PPT
pysdasdasdsadsadsadsadsadsadasdasdthon1.ppt
PPT
python1.ppt
PPT
Introductio_to_python_progamming_ppt.ppt
PPT
python1.ppt
PPT
python1.ppt
PPT
python1.ppt
PPT
Lenguaje Python
PPT
python1.ppt
PPT
python1.ppt
PPT
python1.ppt
PPT
coolstuff.ppt
PPT
Learn Python in Three Hours - Presentation
PDF
ch2 Python flow control.pdf
PPTX
manish python.pptx
PPTX
Basic of Python- Hands on Session
PPT
ENGLISH PYTHON.ppt
PDF
Python Interview Questions PDF By ScholarHat.pdf
Python Decision Making And Loops.pdf
Introduction To Python.pptx
Python Basics
pysdasdasdsadsadsadsadsadsadasdasdthon1.ppt
python1.ppt
Introductio_to_python_progamming_ppt.ppt
python1.ppt
python1.ppt
python1.ppt
Lenguaje Python
python1.ppt
python1.ppt
python1.ppt
coolstuff.ppt
Learn Python in Three Hours - Presentation
ch2 Python flow control.pdf
manish python.pptx
Basic of Python- Hands on Session
ENGLISH PYTHON.ppt
Python Interview Questions PDF By ScholarHat.pdf
Ad

Recently uploaded (20)

PDF
Deliverable file - Regulatory guideline analysis.pdf
PPTX
3. HISTORICAL PERSPECTIVE UNIIT 3^..pptx
PDF
How to Get Approval for Business Funding
PDF
Charisse Litchman: A Maverick Making Neurological Care More Accessible
PDF
Module 2 - Modern Supervison Challenges - Student Resource.pdf
PDF
SIMNET Inc – 2023’s Most Trusted IT Services & Solution Provider
PPTX
Slide gioi thieu VietinBank Quy 2 - 2025
PDF
kom-180-proposal-for-a-directive-amending-directive-2014-45-eu-and-directive-...
PPTX
2025 Product Deck V1.0.pptxCATALOGTCLCIA
PDF
How to Get Funding for Your Trucking Business
PDF
Family Law: The Role of Communication in Mediation (www.kiu.ac.ug)
PDF
Booking.com The Global AI Sentiment Report 2025
PPTX
TRAINNING, DEVELOPMENT AND APPRAISAL.pptx
PDF
1911 Gold Corporate Presentation Aug 2025.pdf
PPT
Lecture 3344;;,,(,(((((((((((((((((((((((
PPTX
sales presentation، Training Overview.pptx
PDF
Nante Industrial Plug Factory: Engineering Quality for Modern Power Applications
PDF
Daniels 2024 Inclusive, Sustainable Development
PPTX
Slide gioi thieu VietinBank Quy 2 - 2025
PDF
NEW - FEES STRUCTURES (01-july-2024).pdf
Deliverable file - Regulatory guideline analysis.pdf
3. HISTORICAL PERSPECTIVE UNIIT 3^..pptx
How to Get Approval for Business Funding
Charisse Litchman: A Maverick Making Neurological Care More Accessible
Module 2 - Modern Supervison Challenges - Student Resource.pdf
SIMNET Inc – 2023’s Most Trusted IT Services & Solution Provider
Slide gioi thieu VietinBank Quy 2 - 2025
kom-180-proposal-for-a-directive-amending-directive-2014-45-eu-and-directive-...
2025 Product Deck V1.0.pptxCATALOGTCLCIA
How to Get Funding for Your Trucking Business
Family Law: The Role of Communication in Mediation (www.kiu.ac.ug)
Booking.com The Global AI Sentiment Report 2025
TRAINNING, DEVELOPMENT AND APPRAISAL.pptx
1911 Gold Corporate Presentation Aug 2025.pdf
Lecture 3344;;,,(,(((((((((((((((((((((((
sales presentation، Training Overview.pptx
Nante Industrial Plug Factory: Engineering Quality for Modern Power Applications
Daniels 2024 Inclusive, Sustainable Development
Slide gioi thieu VietinBank Quy 2 - 2025
NEW - FEES STRUCTURES (01-july-2024).pdf
Ad

ceng4315636732530_1245235week_06_0.7.pdf

  • 1. 1 Programming with Python for Engineers Lecture-6 Lecture : Week-6 Subject : Repetitive Execution - while & for statements - continue & break - List comprehension Lecturer: Hüseyin SAYIN E-Mail : [email protected] Coordinating Assistant : Alperen Dalkıran Support E-Mail : [email protected]
  • 2. 2 Objectives • In this chapter, you will learn: – Repetitive execution in Python: * while & for statements; continue & break; * List comprehension;
  • 3. 3 Repetitive Execution (iteration or loop) iteration/loop: Repeating a sequence of instructions over-and-over is a programming ingredient • iteration/loop is used for; - to systematically deal with all possible cases or all elements of a collection. - to jump from one case to another as a function of the previous case.
  • 4. 4 Repetitive Execution (iteration or loop) Python provides two statements for iteration. Namely, while and for. whereas. • for is used mostly for (Type I) iterations. • while is used for both types.
  • 5. 5 Repetitive Execution (iteration or loop) The repetition of a sequence of instructions is carried out either for a known number of times or until a criterion is met • Computing letter grades of a class (Type I) for all students. • Finding the shortest path from city A to city B in a map (Type II). • Root finding by Newton-Raphson method (Type II). • Finding darkest and brightest point(s) in an image (Type I, for all pixels).
  • 6. 6 Repetitive Execution (iteration or loop) The repetition of a sequence of instructions is carried out either for a known number of times or until a criterion is met • Computing a function value using Taylor’s expansion (Type I). • Computing the next move in a chess game (Type II). • Obtaining the letter frequency of a text (Type I) for all letters.
  • 7. 7 Repetitive Execution (iteration or loop) Python provides two statements for iteration. Namely, while and for. whereas. • for is used mostly for (Type I) iterations. • while is used for both types.
  • 8. The syntax of while resembles the syntax of the if statement: • Certainly possible to have a statement group subject to the while. • while statement execution is; 8 The while Statement
  • 9. Since a while statement is a statement, it can be part of another while statement (or any other compound statement): 9 The Nested Loops
  • 10. The "inner loop" will be executed one time for each iteration of the "outer loop". Example: Print each adjective for every fruit. Python Code: Output: 10 The while Statement
  • 12. 12 • Infinite Loops … while 1: # while true print(“Infinite Loop”) … while -9: print (“Infinite Loop”) … The while Repetition Statement
  • 13. 13 • Infinite Loops … while true: # while true print(“Infinite Loop”) … while -9: print (“Infinite Loop”) … The while Repetition Statement
  • 14. 14 • Infinite Loops … vCounter = 1 while vCounter: print (“{ounter}n”) vCounter += 1 The while Repetition Statement
  • 15. 15 • Null Loops … while 0: print(“Null Loop”) … … while false: print(“Null Loop”) … The while Repetition Statement
  • 16. Example 1: Finding Average of Numbers in a List: • Finding a list of numbers average. • The mathematical definition: • Li is the ith number in the list which contains N numbers 16 Examples with while Statement
  • 17. Example 1: Finding Average of Numbers in a List: • The algorithm before implementing a solution in Python. • Pseudocode 17 Examples with while Statement
  • 18. Example 1: Finding Average of Numbers in a List: Python Code Program Output: 18 Examples with while Statement
  • 19. Example 2: Factorial of a number n! can be defined formally as. • The mathematical definition: 19 Examples with while Statement
  • 20. Example 2: Factorial of a number n! can be defined formally as. Pseudocode: 20 Examples with while Statement
  • 21. Example 2: Factorial of a number n! can be defined formally as: Python Code: Program Output: 21 Examples with while Statement
  • 22. The syntax of for resembles the syntax of the if statement: • An iterator is an object that provides a countable number of values on demand.. • It has an internal mechanism; that responds to three requests: 1. Reset (initialize) it to the start. 2. Respond to the “Are we at the end?” question. 3. Provide the next value in line. 22 for Statement
  • 23. The semantics of the for statement is; 23 for Statement
  • 24. What iterators do we have? 1. All containers are also iterators (strings, lists, dictionaries, sets). 2. The built-in function range returns an iterator that generates a sequence of integers, starting from 0 (default), and increments by 1 (default), and stops before a given number. 24 for Statement
  • 25. Example 1: Using the start parameter. Python Code: Output: 25 Examples with for and range() Statement
  • 26. Example 2: Using the start parameter. Python Code: Output: 26 Examples with for and range() Statement
  • 27. Example 3: Using the start parameter. Python Code: Output: 27 Examples with for and range() Statement
  • 28. Example 3: Using the start parameter. Python Code: Output: 28 Examples with for and range() Statement
  • 29. The "inner loop" will be executed one time for each iteration of the "outer loop". Example: Print each adjective for every fruit. Python Code: Output: 29 The Nested Loops
  • 30. Example 1: split a list of words into two lists: those that start with a vowel and those that start with a consonant. Python Code: 30 Examples with for Statement
  • 31. To alter the flow of execution in a while or for repetition: • almost always used in combination with statement grouping (a group of statements is subject to the while or for), • executing a sequence of statements by means of statement grouping, • Somewhere in the process, without waiting for the terminating condition to become False in a while statement or exhausting all items in the iterator in a for statement, you decide to terminate looping. 31 continue and break Statements
  • 32. To alter the flow of execution in a while or for repetition: • The break statement does exactly serve this purpose: The while (or for) is stopped immediately and the execution continues with the statement after the while (or for). • Stops the loop altogether, and goes on with the next instruction after the loop end. • Somewhere in the process you decide not to execute the rest of the statements in the grouping and straight away continue with the test. This is achieved by a continue statement usage. • stops the current iteration and tells Python to execute the next one. 32 continue and break Statements
  • 33. How continue and break statements change execution in a while statement: 33 continue and break Statements
  • 34. How continue and break statements change execution in a for statement: 34 continue and break Statements
  • 35. With the continue statement we can stop the current iteration, and continue with the next. Python Code: Output: 35 continue and break Statements
  • 36. This notation has three parts (from left-to-right): or as something more elaborate: Python Code: Output: 36 continue and break Statements
  • 37. This notation has three parts (from left-to-right): or as something more elaborate: Python Code: Output: 37 continue and break Statements
  • 38. A well-known and extensively-used notation to describe a set in mathematics is the so-called ‘set-builder notation’. This is also known as set comprehension. List comprehensions are a way to create lists in a very concise way. This notation has three parts (from left-to-right): 1. an expression in terms of a variable, 2. a colon or vertical bar separator, and 3. a logical predicate. 38 set and list Comprehension
  • 39. This notation has three parts (from left-to-right): Something like this: which defines the set: 39 set and list Comprehension
  • 40. This notation has three parts (from left-to-right): or as something more elaborate: Python Code: 40 set and list Comprehension
  • 41. This notation has three parts (from left-to-right): or as something more elaborate: which defines the set: 41 set and list Comprehension
  • 42. This notation has three parts (from left-to-right): or as something more elaborate: Python Code: 42 set and list Comprehension
  • 44. Example-3: Python Code: print( [[0 for i in range(3)] for j in range(4)] ) Output: [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0] ] 44 set and list Comprehension
  • 45. Example-3: Python Code: print( [[0 for i in range(3)] for j in range(4)] ) Output: [ [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0] ] 45 set and list Comprehension
  • 46. Example-4: Python Code: print( [[1 if i==j else 0 for i in range(3)] for j in range(3)] ) Output: [[1, 0, 0], [0, 1, 0], [0, 0, 1]] 46 set and list Comprehension
  • 47. Example-4: Python Code: print( [[1 if i==j else 0 for i in range(3)] for j in range(3)] ) Output: [[1, 0, 0], [0, 1, 0], [0, 0, 1]] 47 set and list Comprehension
  • 48. Example-5: Python Code: print( [[(i,j) for i in range(3)] for j in range(4)] ) Output: [[(0, 0),(1, 0),(2, 0)],[(0, 1),(1, 1),(2, 1)], [(0, 2),(1, 2),(2, 2)],[(0, 3),(1, 3),(2, 3)]] 48 set and list Comprehension
  • 49. Example-5: Python Code: print( [[(i,j) for i in range(3)] for j in range(4)] ) Output: [ [(0, 0), (1, 0), (2, 0)], [(0, 1), (1, 1), (2, 1)], [(0, 2), (1, 2), (2, 2)], [(0, 3), (1, 3), (2, 3)] ] 49 set and list Comprehension
  • 50. Example-6: Python Code: print( [[(i+j)%2 for i in range(3)] for j in range(4)] ) Output: [[0, 1, 0], [1, 0, 1], [0, 1, 0], [1, 0, 1]] 50 set and list Comprehension
  • 51. Example-6: Python Code: print( [[(i+j)%2 for i in range(3)] for j in range(4)] ) Output: [[0, 1, 0], [1, 0, 1], [0, 1, 0], [1, 0, 1]] 51 set and list Comprehension
  • 52. Example-7: Python Code: print( [[i+3*j for i in range(3)] for j in range(4)] ) Output: [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]] 52 set and list Comprehension
  • 53. Example-7: Python Code: print( [[i+3*j for i in range(3)] for j in range(4)] ) Output: [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9,10,11]] 53 set and list Comprehension
  • 54. 54 Chapter Objectives In this chapter, you will learn: • Repetitive execution in Python – Repetitive execution with while and for statements. – Changing the flow of iterations with break and continue statements, – Set and list comprehension as a form of iterative computation in an expression.
  • 56. 56 The break and continue Statements • break – Causes immediate exit from a while or for statement – Program execution continues with the first statement after the structure – Common uses of the break statement • Escape early from a loop