SlideShare a Scribd company logo
8
Most read
9
Most read
13
Most read
For Loops and Nesting
Looping Structures
For Loops
 For loops are a pre-test loop
 In order to utilize a for loop you need 3 things:
1. Needs to initialize a counter
2. Must test the counter variable
3. It must update the counter variable
 Code:
for initialization in range(start, stop,
increment):
statement1
statement2
Example
for i in range(0, 5, 1):
print(“Hello”)
Step 1: Perform the initialization
expression
Step 2: Evaluate the test
expressions
Step 3: Execute the body of
the loop
Step 4: Perform the
update
Assign 0 to i
i < 5
Update iPrint “Hello”
True
False
Reasons to use a for loop
 Know the number of times the loop should iterate
 Using a counter
 Need a false condition to terminate the loop
Demonstrating when to use a for
loop
num = 1;
while ( num <= 10):
print( num, “tt”, num * num)
num+=1;
for i in range(1, 10, 1):
print( num, “tt”, num * num)
Initialization expression
Initialization
expression
Test
Update
UpdateTest
Other Ways to Update
 Most programmers and books refer to the update
expression as the incrementor
 Not only can you increment the expression but
decrement as well
 Additionally you can increase and decrease the
variable by values other than 1
 i++ i+=1 i = i + 1
 i-- i -=1 i = i - 1
 i+=2
 i -=5
Determining Which Loop to
Choose
 Each of the 3 loops is ideal to use in different
situations:
 The while loop. The while loop is a pre-test
conditional loop. It is ideal in situations where you
do not want the loop to iterate if the condition is
false from the beginning. For example, checking
health in a game until someone dies
 The for loop. The for loop is a pretest loop that has
built in expressions for initializing, testing and
updating a counter. This makes it convenient to
control the number of times the loop executes. For
Nested Loops
 A nested loop is a loop inside the body of another
loop
 Inner (inside), outer (outside) loops:
for row in range(1, 3, 1) //outer
for col in range(1, 3, 1)//inner
print(row * col)
 Inner loop goes through all repetitions for each
repetition of outer loop
 Inner loop repetitions complete sooner than outer loop
 Total number of repetitions for inner loop is product of
number of repetitions of the two loops.
 Can nest different styles of loops together
Nesting Loops
 Nested loops are necessary when a task is performs
a repetitive operation and that task itself must be
repeated.
 for initialize in range(start, stop, update):
while(condition):
for initialize in range(start, stop, update):
while(condition):
 Just like when we worked with nested conditionals
 if (condition):
if (condition):
 For example, a digital clock is a good example of
needing to nest for loops.
Digital Clock
 How can we use loops to simulate a digital clock?
 What would each loop be responsible for keeping
track of?
 There would be 3 loops:
 One would track the hour
 One would track the minutes
 One would track the seconds
 NOT AN ANALOG CLOCK, why??????
 What would it look like?
Digital Clock
 First let’s begin by creating a loop to display the
seconds up to a minute.
 Can anyone describe that loop???
for sec in range(0, 60, 1):
print(format(sec, ‘>2’)
 Question: What is the initialization, test and update
for the previous for loop?
 Question: What would it look like if we printed to
the left with setw(2)?
Digital Clock
 Now let’s add minutes by nesting our previous loop:
for min in range(0, 60, 1):
for sec in range(0, 60, 1):
print(format(min, ‘>2’), ”:”, format(sec,
‘>2’)
Digital Clock
 Write out the digital clock code to print the hour
as well
Digital Clock
for hour in range(0, 12, 1):
for min in range(0, 60, 1):
for sec in range(0, 60, 1):
print(format(hour, ‘>2’), ”:”, format(min, ‘>2’), ”:”, format(sec,
‘>2’)
 Question: What if we wanted to add
AM/PM
Digital Clock
Assign 0 to
hour
hour <
12
Assign 0 to
sec
Assign 0 to
min
True
False
min <
60
False
True
sec <
60
Fals
True Print clock
Checkpoint:
1. Name the three expressions that appear inside
the parentheses(header) of the for loop.
2. You want to write a for loop that displays “I love
to program!” 50 times.
A. What initialization expression will you use?
B. What test expression will you use?
C. What update expression will you use?
D. Write the loop
3. What will the following code segments produce:
A. for count in range(0, 6, 1):
print(count + count)
A. for j in range(20, 14, -2):
print(j)
4. When should I use each type of loop?

More Related Content

PDF
Python Loops Tutorial | Python For Loop | While Loop Python | Python Training...
PPTX
Classes, objects in JAVA
PPTX
Queue in Data Structure
PDF
Python GUI
PPTX
sql function(ppt)
PPTX
Binary Search Tree in Data Structure
Python Loops Tutorial | Python For Loop | While Loop Python | Python Training...
Classes, objects in JAVA
Queue in Data Structure
Python GUI
sql function(ppt)
Binary Search Tree in Data Structure

What's hot (20)

PPTX
Python for loop
PPT
enums
PDF
Datatypes in python
PPTX
Aggregate function
PPTX
Arrays in Java
PDF
Python If Else | If Else Statement In Python | Edureka
PPTX
sorting and its types
PPTX
Stack data structure
PDF
Applications of stack
PPTX
Switch statement, break statement, go to statement
PPTX
Recursion in Data Structure
PPTX
Conditional and control statement
PPTX
Control Statements in Java
PPTX
Passing an Array to a Function (ICT Programming)
PPTX
String Manipulation in Python
PDF
Data Structures
PDF
Java arrays
PPTX
Java Data Types
PPTX
List in Python
PPT
Python GUI Programming
Python for loop
enums
Datatypes in python
Aggregate function
Arrays in Java
Python If Else | If Else Statement In Python | Edureka
sorting and its types
Stack data structure
Applications of stack
Switch statement, break statement, go to statement
Recursion in Data Structure
Conditional and control statement
Control Statements in Java
Passing an Array to a Function (ICT Programming)
String Manipulation in Python
Data Structures
Java arrays
Java Data Types
List in Python
Python GUI Programming
Ad

Viewers also liked (13)

PPT
Conditional Loops Python
PPT
Formatting Output
PPT
Intro to Lists
PPTX
Functions
PPTX
Function Returns
PPTX
Variables and Expressions
PPT
PPT
Intro to Python
PPTX
Logical Operators
PPT
Intro to Jeroo Python
PPTX
Computer Logic
PDF
DSL in Clojure
PPTX
Python - Lesson 1
Conditional Loops Python
Formatting Output
Intro to Lists
Functions
Function Returns
Variables and Expressions
Intro to Python
Logical Operators
Intro to Jeroo Python
Computer Logic
DSL in Clojure
Python - Lesson 1
Ad

Similar to For Loops and Nesting in Python (20)

PPTX
Nested Loops
PDF
LOOPS TOPIC FOR CLASS XI PYTHON SYLLABUS
PDF
2 Python Basics II meeting 2 tunghai university pdf
PPTX
Introduction to Repetition Structures
PPTX
PDF
PPT
Conditional Loops
PPTX
python ppt.pptx
PPTX
Iterations FOR LOOP AND WHILE LOOP .pptx
PDF
While-For-loop in python used in college
PPTX
While_for_loop presententationin first year students
PPTX
Mastering Python lesson3b_for_loops
PPTX
Python programming –part 3
PPTX
ForLoops.pptx
PPTX
Loops in python including control statements and various test cases
PPT
Loops Do While Arduino Programming Robotics
PPTX
Matlab Script - Loop Control
PDF
011 LOOP.pdf cs project important chapters
PPT
Fundamentals of Programming Chapter 7
Nested Loops
LOOPS TOPIC FOR CLASS XI PYTHON SYLLABUS
2 Python Basics II meeting 2 tunghai university pdf
Introduction to Repetition Structures
Conditional Loops
python ppt.pptx
Iterations FOR LOOP AND WHILE LOOP .pptx
While-For-loop in python used in college
While_for_loop presententationin first year students
Mastering Python lesson3b_for_loops
Python programming –part 3
ForLoops.pptx
Loops in python including control statements and various test cases
Loops Do While Arduino Programming Robotics
Matlab Script - Loop Control
011 LOOP.pdf cs project important chapters
Fundamentals of Programming Chapter 7

More from primeteacher32 (20)

PPT
Software Development Life Cycle
PPTX
Variable Scope
PPTX
Returning Data
PPTX
Intro to Functions
PPTX
Introduction to GUIs with guizero
PPTX
Function Parameters
PPTX
Input Validation
PPTX
Windows File Systems
PPTX
Nesting Conditionals
PPTX
Conditionals
PPT
Intro to Python with GPIO
PPTX
Variables and Statements
PPTX
Variables and User Input
PPT
Intro to Python
PPTX
Raspberry Pi
PPT
Hardware vs. Software Presentations
PPTX
Block chain security
PPTX
PPTX
System Administration
PPTX
Robots.txt
Software Development Life Cycle
Variable Scope
Returning Data
Intro to Functions
Introduction to GUIs with guizero
Function Parameters
Input Validation
Windows File Systems
Nesting Conditionals
Conditionals
Intro to Python with GPIO
Variables and Statements
Variables and User Input
Intro to Python
Raspberry Pi
Hardware vs. Software Presentations
Block chain security
System Administration
Robots.txt

Recently uploaded (20)

PPTX
Digital Education Presentation for students.
PDF
Sheri Ann Lowe Compliance Strategist Resume
PPTX
ChandigarhUniversityinformationcareer.pptx
PPTX
microtomy kkk. presenting to cryst in gl
PPT
ALLIED MATHEMATICS -I UNIT III MATRICES.ppt
PPT
2- CELL INJURY L1 Medical (2) gggggggggg
PPT
Gsisgdkddkvdgjsjdvdbdbdbdghjkhgcvvkkfcxxfg
PPTX
STS CHAP 4 human development as reflected
PDF
Women’s Talk Session 1- Talking about women
PDF
202s5_Luciano André Deitos Koslowski.pdf
PPTX
DPT-MAY24.pptx for review and ucploading
PPTX
CYBER SECURITY PPT.pptx CYBER SECURITY APPLICATION AND USAGE
PDF
APNCET2025RESULT Result Result 2025 2025
PPTX
1751884730-Visual Basic -Unitj CS B.pptx
PPTX
Overview Planner of Soft Skills in a single ppt
PPTX
AREAS OF SPECIALIZATION AND CAREER OPPORTUNITIES FOR COMMUNICATORS AND JOURNA...
PPT
BCH3201 (Enzymes and biocatalysis)-JEB (1).ppt
PPTX
FINAL PPT.pptx cfyufuyfuyuy8ioyoiuvy ituyc utdfm v
PPTX
Principles of Inheritance and variation class 12.pptx
PPTX
Prokaryotes v Eukaryotes PowerPoint.pptx
Digital Education Presentation for students.
Sheri Ann Lowe Compliance Strategist Resume
ChandigarhUniversityinformationcareer.pptx
microtomy kkk. presenting to cryst in gl
ALLIED MATHEMATICS -I UNIT III MATRICES.ppt
2- CELL INJURY L1 Medical (2) gggggggggg
Gsisgdkddkvdgjsjdvdbdbdbdghjkhgcvvkkfcxxfg
STS CHAP 4 human development as reflected
Women’s Talk Session 1- Talking about women
202s5_Luciano André Deitos Koslowski.pdf
DPT-MAY24.pptx for review and ucploading
CYBER SECURITY PPT.pptx CYBER SECURITY APPLICATION AND USAGE
APNCET2025RESULT Result Result 2025 2025
1751884730-Visual Basic -Unitj CS B.pptx
Overview Planner of Soft Skills in a single ppt
AREAS OF SPECIALIZATION AND CAREER OPPORTUNITIES FOR COMMUNICATORS AND JOURNA...
BCH3201 (Enzymes and biocatalysis)-JEB (1).ppt
FINAL PPT.pptx cfyufuyfuyuy8ioyoiuvy ituyc utdfm v
Principles of Inheritance and variation class 12.pptx
Prokaryotes v Eukaryotes PowerPoint.pptx

For Loops and Nesting in Python

  • 1. For Loops and Nesting Looping Structures
  • 2. For Loops  For loops are a pre-test loop  In order to utilize a for loop you need 3 things: 1. Needs to initialize a counter 2. Must test the counter variable 3. It must update the counter variable  Code: for initialization in range(start, stop, increment): statement1 statement2
  • 3. Example for i in range(0, 5, 1): print(“Hello”) Step 1: Perform the initialization expression Step 2: Evaluate the test expressions Step 3: Execute the body of the loop Step 4: Perform the update Assign 0 to i i < 5 Update iPrint “Hello” True False
  • 4. Reasons to use a for loop  Know the number of times the loop should iterate  Using a counter  Need a false condition to terminate the loop
  • 5. Demonstrating when to use a for loop num = 1; while ( num <= 10): print( num, “tt”, num * num) num+=1; for i in range(1, 10, 1): print( num, “tt”, num * num) Initialization expression Initialization expression Test Update UpdateTest
  • 6. Other Ways to Update  Most programmers and books refer to the update expression as the incrementor  Not only can you increment the expression but decrement as well  Additionally you can increase and decrease the variable by values other than 1  i++ i+=1 i = i + 1  i-- i -=1 i = i - 1  i+=2  i -=5
  • 7. Determining Which Loop to Choose  Each of the 3 loops is ideal to use in different situations:  The while loop. The while loop is a pre-test conditional loop. It is ideal in situations where you do not want the loop to iterate if the condition is false from the beginning. For example, checking health in a game until someone dies  The for loop. The for loop is a pretest loop that has built in expressions for initializing, testing and updating a counter. This makes it convenient to control the number of times the loop executes. For
  • 8. Nested Loops  A nested loop is a loop inside the body of another loop  Inner (inside), outer (outside) loops: for row in range(1, 3, 1) //outer for col in range(1, 3, 1)//inner print(row * col)  Inner loop goes through all repetitions for each repetition of outer loop  Inner loop repetitions complete sooner than outer loop  Total number of repetitions for inner loop is product of number of repetitions of the two loops.  Can nest different styles of loops together
  • 9. Nesting Loops  Nested loops are necessary when a task is performs a repetitive operation and that task itself must be repeated.  for initialize in range(start, stop, update): while(condition): for initialize in range(start, stop, update): while(condition):  Just like when we worked with nested conditionals  if (condition): if (condition):  For example, a digital clock is a good example of needing to nest for loops.
  • 10. Digital Clock  How can we use loops to simulate a digital clock?  What would each loop be responsible for keeping track of?  There would be 3 loops:  One would track the hour  One would track the minutes  One would track the seconds  NOT AN ANALOG CLOCK, why??????  What would it look like?
  • 11. Digital Clock  First let’s begin by creating a loop to display the seconds up to a minute.  Can anyone describe that loop??? for sec in range(0, 60, 1): print(format(sec, ‘>2’)  Question: What is the initialization, test and update for the previous for loop?  Question: What would it look like if we printed to the left with setw(2)?
  • 12. Digital Clock  Now let’s add minutes by nesting our previous loop: for min in range(0, 60, 1): for sec in range(0, 60, 1): print(format(min, ‘>2’), ”:”, format(sec, ‘>2’)
  • 13. Digital Clock  Write out the digital clock code to print the hour as well
  • 14. Digital Clock for hour in range(0, 12, 1): for min in range(0, 60, 1): for sec in range(0, 60, 1): print(format(hour, ‘>2’), ”:”, format(min, ‘>2’), ”:”, format(sec, ‘>2’)  Question: What if we wanted to add AM/PM
  • 15. Digital Clock Assign 0 to hour hour < 12 Assign 0 to sec Assign 0 to min True False min < 60 False True sec < 60 Fals True Print clock
  • 16. Checkpoint: 1. Name the three expressions that appear inside the parentheses(header) of the for loop. 2. You want to write a for loop that displays “I love to program!” 50 times. A. What initialization expression will you use? B. What test expression will you use? C. What update expression will you use? D. Write the loop 3. What will the following code segments produce: A. for count in range(0, 6, 1): print(count + count) A. for j in range(20, 14, -2): print(j) 4. When should I use each type of loop?

Editor's Notes

  • #9: Think of it as searching a hotel. The outer loop operates the elevator and the inner loop searches the hotel rooms on each floor. Each loop controls a different aspect of the program.