SlideShare a Scribd company logo
1 of 36
3. Looping statement
ARULKUMAR V Ap/CSE SECE 1
Motivations
Suppose that you need to print a string (e.g.,
"Programming is fun!") a hundred times. It would
be tedious to have to write the following statement
a hundred times:
print("Programming is fun!");
So, how do you solve this problem?
2ARULKUMAR V Ap/CSE SECE
Opening Problem
Problem:
3
print("Programming is fun!");
print("Programming is fun!");
print("Programming is fun!");
print("Programming is fun!");
print("Programming is fun!");
print("Programming is fun!");
…
…
…
print("Programming is fun!");
print("Programming is fun!");
print("Programming is fun!");
100
times
ARULKUMAR V Ap/CSE SECE
Introducing while Loops
4
count = 0
while count < 100:
print("Programming is fun!")
count = count + 1
ARULKUMAR V Ap/CSE SECE
Objectives
ARULKUMAR V Ap/CSE SECE 5
 To write programs for executing statements repeatedly by using a
while loop (§5.2).
 To develop loops following the loop design strategy (§§5.2.1-5.2.3).
 To control a loop with the user’s confirmation (§5.2.4).
 To control a loop with a sentinel value (§5.2.5).
 To obtain a large amount of input from a file by using input
redirection instead of typing from the keyboard (§5.2.6).
 To use for loops to implement counter-controlled loops (§5.3).
 To write nested loops (§5.4).
 To learn the techniques for minimizing numerical errors (§5.5).
 To learn loops from a variety of examples (GCD, FutureTuition,
MonteCarloSimulation, PrimeNumber) (§§5.6, 5.8).
 To implement program control with break and continue (§5.7).
 To use a loop to control and simulate a random walk (§5.9).
while Loop Flow Chart
6
while loop-continuation-condition:
# Loop body
Statement(s)
count = 0
while count < 100:
print("Programming is fun!")
count = count + 1
loop-
continuation
condition?
True
Statement(s)
(loop body)
False
count < 100?
True
print("Programming is fun!")
count = count + 1
False
(a) (b)
count = 0
ARULKUMAR V Ap/CSE SECE
Trace while Loop
7
count = 0
while count < 2:
print("Programming is fun!")
count = count + 1
Initialize count
animation
ARULKUMAR V Ap/CSE SECE
Trace while Loop, cont.
8
count = 0
while count < 2:
print("Programming is fun!")
count = count + 1
(count < 2) is true
animation
ARULKUMAR V Ap/CSE SECE
Trace while Loop, cont.
9
count = 0
while count < 2:
print("Programming is fun!")
count = count + 1
Print Welcome to Python
animation
ARULKUMAR V Ap/CSE SECE
Trace while Loop, cont.
10
count = 0
while count < 2:
print("Programming is fun!")
count = count + 1
Increase count by 1
count is 1 now
animation
ARULKUMAR V Ap/CSE SECE
Trace while Loop, cont.
11
count = 0
while count < 2:
print("Programming is fun!")
count = count + 1
(count < 2) is still true since count
is 1
animation
ARULKUMAR V Ap/CSE SECE
Trace while Loop, cont.
12
count = 0
while count < 2:
print("Programming is fun!")
count = count + 1
Print Welcome to Python
animation
ARULKUMAR V Ap/CSE SECE
Trace while Loop, cont.
13
count = 0
while count < 2:
print("Programming is fun!")
count = count + 1
Increase count by 1
count is 2 now
animation
ARULKUMAR V Ap/CSE SECE
Trace while Loop, cont.
14
count = 0
while count < 2:
print("Programming is fun!")
count = count + 1
(count < 2) is false since count is 2
now
animation
ARULKUMAR V Ap/CSE SECE
Trace while Loop
15
count = 0
while count < 2:
print("Programming is fun!")
count = count + 1
The loop exits. Execute the next
statement after the loop.
animation
ARULKUMAR V Ap/CSE SECE
Problem: An Advanced Math Learning Tool
The Math subtraction learning tool program
generates just one question for each run. You can
use a loop to generate questions repeatedly. This
example gives a program that generates five
questions and reports the number of the correct
answers after a student answers all five questions.
16
SubtractionQuizLoop Run
ARULKUMAR V Ap/CSE SECE
Problem: Guessing Numbers
Write a program that randomly generates an
integer between 0 and 100, inclusive. The
program prompts the user to enter a number
continuously until the number matches the
randomly generated number. For each user input,
the program tells the user whether the input is
too low or too high, so the user can choose the
next input intelligently. Here is a sample run:
17
GuessNumberOneTime Run
GuessNumber Run
ARULKUMAR V Ap/CSE SECE
Ending a Loop with a Sentinel Value
Often the number of times a loop is executed is not
predetermined. You may use an input value to
signify the end of the loop. Such a value is known
as a sentinel value.
Write a program that reads and calculates the sum
of an unspecified number of integers. The input 0
signifies the end of the input.
18
SentinelValue Run
ARULKUMAR V Ap/CSE SECE
Caution
item = 1
sum = 0
while item != 0: # No guarantee item will be 0
sum += item
item -= 0.1
print(sum)
19
Variable item starts with 1 and is reduced by 0.1 every time the
loop body is executed. The loop should terminate when item
becomes 0. However, there is no guarantee that item will be
exactly 0, because the floating-point arithmetic is approximated.
This loop seems OK on the surface, but it is actually an infinite
loop.
Don’t use floating-point values for equality checking in a loop control.
Since floating-point values are approximations for some values, using
them could result in imprecise counter values and inaccurate results.
Consider the following code for computing 1 + 0.9 + 0.8 + ... + 0.1:
ARULKUMAR V Ap/CSE SECE
for Loops
i = initialValue # Initialize loop-control variable
while i < endValue:
# Loop body
...
i++ # Adjust loop-control variable
20
for i in range(initialValue, endValue):
# Loop body
ARULKUMAR V Ap/CSE SECE
range(a, b)
>>> for v in range(4, 8):
... print(v)
...
4
5
6
7
>>>
21ARULKUMAR V Ap/CSE SECE
range(b)
>>> for i in range(4):
... print(i)
...
0
1
2
3
>>>
22ARULKUMAR V Ap/CSE SECE
range(a, b, step)
>>> for v in range(3, 9, 2):
... print(v)
...
3
5
7
>>>
23ARULKUMAR V Ap/CSE SECE
range(a, b, step)
>>> for v in range(5, 1, -1):
... print(v)
...
5
4
3
2
>>>
24ARULKUMAR V Ap/CSE SECE
Nested Loops
Problem: Write a program that uses nested for
loops to print a multiplication table.
25
MultiplicationTable
Run
ARULKUMAR V Ap/CSE SECE
Minimizing Numerical Errors
Numeric errors involving floating-point
numbers are inevitable. This section discusses
how to minimize such errors through an
example.
Here is an example that sums a series that
starts with 0.01 and ends with 1.0. The
numbers in the series will increment by 0.01,
as follows: 0.01 + 0.02 + 0.03 and so on.
26
TestSum Run
ARULKUMAR V Ap/CSE SECE
Problem:
Finding the Greatest Common Divisor
27
Problem: Write a program that prompts the user to enter two positive
integers and finds their greatest common divisor.
Solution: Suppose you enter two integers 4 and 2, their greatest
common divisor is 2. Suppose you enter two integers 16 and 24, their
greatest common divisor is 8. So, how do you find the greatest
common divisor? Let the two input integers be n1 and n2. You know
number 1 is a common divisor, but it may not be the greatest commons
divisor. So you can check whether k (for k = 2, 3, 4, and so on) is a
common divisor for n1 and n2, until k is greater than n1 or n2.
GreatestCommonDivisor Run
ARULKUMAR V Ap/CSE SECE
Problem: Predicting the Future Tuition
28
Problem: Suppose that the tuition for a university is $10,000 this year
and tuition increases 7% every year. In how many years will the
tuition be doubled?
FutureTuition Run
ARULKUMAR V Ap/CSE SECE
Problem: Predicating the Future Tuition
29
year = 0 # Year 0
tuition = 10000
year += 1 # Year 1
tuition = tuition * 1.07
year += 1 # Year 2
tuition = tuition * 1.07
year += 1 # Year 3
tuition = tuition * 1.07
FutureTuition Run
ARULKUMAR V Ap/CSE SECE
Problem: Monte Carlo Simulation
30
The Monte Carlo simulation refers to a technique that uses random
numbers and probability to solve problems. This method has a wide
range of applications in computational mathematics, physics,
chemistry, and finance. This section gives an example of using the
Monto Carlo simulation for estimating .
MonteCarloSimulation Run
x
y
1-1
1
-1
circleArea / squareArea =  / 4.
 can be approximated as 4 *
numberOfHits / 1000000.
ARULKUMAR V Ap/CSE SECE
Using break and continue
31
Examples for using the break and continue
keywords:
 TestBreak.py
 TestContinue.py
TestBreak
TestContinue
Run
Run
ARULKUMAR V Ap/CSE SECE
break
32
sum = 0
number = 0
while number < 20:
number += 1
sum += number
if sum >= 100:
break
print("The number is ", number)
print("The sum is ", sum)
Break out of
the loop
ARULKUMAR V Ap/CSE SECE
continue
33
sum = 0
number = 0
while (number < 20):
number += 1
if (number == 10 or number == 11):
continue
sum += number
print("The sum is ", sum)
Jump to the
end of the
iteration
ARULKUMAR V Ap/CSE SECE
Guessing Number Problem Revisited
Here is a program for guessing a number. You can
rewrite it using a break statement.
34
GuessNumberUsingBreak Run
ARULKUMAR V Ap/CSE SECE
Problem: Displaying Prime Numbers
35
Problem: Write a program that displays the first 50 prime numbers in
five lines, each of which contains 10 numbers. An integer greater than
1 is prime if its only positive divisor is 1 or itself. For example, 2, 3,
5, and 7 are prime numbers, but 4, 6, 8, and 9 are not.
Solution: The problem can be broken into the following tasks:
•For number = 2, 3, 4, 5, 6, ..., test whether the number is prime.
•Determine whether a given number is prime.
•Count the prime numbers.
•Print each prime number, and print 10 numbers per line.
PrimeNumber Run
ARULKUMAR V Ap/CSE SECE
Turtle: Random Walk
36
RandomWalk Run
ARULKUMAR V Ap/CSE SECE

More Related Content

Similar to 3.2 looping statement

C code This program will calculate the sum of 10 positive .docx
 C code This program will calculate the sum of 10 positive .docx C code This program will calculate the sum of 10 positive .docx
C code This program will calculate the sum of 10 positive .docx
aryan532920
 
Slide07 repetitions
Slide07 repetitionsSlide07 repetitions
Slide07 repetitions
altwirqi
 
A simple project of computer program.docx
A simple project of computer program.docxA simple project of computer program.docx
A simple project of computer program.docx
write4
 
OverviewThis hands-on lab allows you to follow and experiment w.docx
OverviewThis hands-on lab allows you to follow and experiment w.docxOverviewThis hands-on lab allows you to follow and experiment w.docx
OverviewThis hands-on lab allows you to follow and experiment w.docx
gerardkortney
 

Similar to 3.2 looping statement (20)

Loops in Python.pptx
Loops in Python.pptxLoops in Python.pptx
Loops in Python.pptx
 
2. data types, variables and operators
2. data types, variables and operators2. data types, variables and operators
2. data types, variables and operators
 
Ch5(loops)
Ch5(loops)Ch5(loops)
Ch5(loops)
 
ICP - Lecture 9
ICP - Lecture 9ICP - Lecture 9
ICP - Lecture 9
 
C code This program will calculate the sum of 10 positive .docx
 C code This program will calculate the sum of 10 positive .docx C code This program will calculate the sum of 10 positive .docx
C code This program will calculate the sum of 10 positive .docx
 
L06
L06L06
L06
 
Python_Module_2.pdf
Python_Module_2.pdfPython_Module_2.pdf
Python_Module_2.pdf
 
Bikalpa_Thapa_Python_Programming_(Basics).pptx
Bikalpa_Thapa_Python_Programming_(Basics).pptxBikalpa_Thapa_Python_Programming_(Basics).pptx
Bikalpa_Thapa_Python_Programming_(Basics).pptx
 
Scilab as a calculator
Scilab as a calculatorScilab as a calculator
Scilab as a calculator
 
Week2 ch4 part1edited 2020
Week2 ch4 part1edited 2020Week2 ch4 part1edited 2020
Week2 ch4 part1edited 2020
 
Week2 ch4 part1edited 2020
Week2 ch4 part1edited 2020Week2 ch4 part1edited 2020
Week2 ch4 part1edited 2020
 
Slide07 repetitions
Slide07 repetitionsSlide07 repetitions
Slide07 repetitions
 
Algorithm and psuedocode
Algorithm and psuedocodeAlgorithm and psuedocode
Algorithm and psuedocode
 
A simple project of computer program.docx
A simple project of computer program.docxA simple project of computer program.docx
A simple project of computer program.docx
 
Python Control structures
Python Control structuresPython Control structures
Python Control structures
 
OverviewThis hands-on lab allows you to follow and experiment w.docx
OverviewThis hands-on lab allows you to follow and experiment w.docxOverviewThis hands-on lab allows you to follow and experiment w.docx
OverviewThis hands-on lab allows you to follow and experiment w.docx
 
03b loops
03b   loops03b   loops
03b loops
 
Introduction to programming - class 3
Introduction to programming - class 3Introduction to programming - class 3
Introduction to programming - class 3
 
C code examples
C code examplesC code examples
C code examples
 
lecture 2.pptx
lecture 2.pptxlecture 2.pptx
lecture 2.pptx
 

More from PhD Research Scholar

More from PhD Research Scholar (20)

Ajax
AjaxAjax
Ajax
 
Quiz servlet
Quiz servletQuiz servlet
Quiz servlet
 
Quiz
QuizQuiz
Quiz
 
servlet db connectivity
servlet db connectivityservlet db connectivity
servlet db connectivity
 
2.java script dom
2.java script  dom2.java script  dom
2.java script dom
 
1.java script
1.java script1.java script
1.java script
 
Quiz javascript
Quiz javascriptQuiz javascript
Quiz javascript
 
Thread&amp;multithread
Thread&amp;multithreadThread&amp;multithread
Thread&amp;multithread
 
String
StringString
String
 
Streams&amp;io
Streams&amp;ioStreams&amp;io
Streams&amp;io
 
Packages
PackagesPackages
Packages
 
Interface in java
Interface in javaInterface in java
Interface in java
 
Inner classes in java
Inner classes in javaInner classes in java
Inner classes in java
 
Inheritance
InheritanceInheritance
Inheritance
 
Exception handling
Exception handlingException handling
Exception handling
 
Applets
AppletsApplets
Applets
 
Abstract class
Abstract classAbstract class
Abstract class
 
7. tuples, set &amp; dictionary
7. tuples, set &amp; dictionary7. tuples, set &amp; dictionary
7. tuples, set &amp; dictionary
 
6. list
6. list6. list
6. list
 
5. string
5. string5. string
5. string
 

Recently uploaded

1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
MateoGardella
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
SanaAli374401
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
Chris Hunter
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 

Recently uploaded (20)

1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
SECOND SEMESTER TOPIC COVERAGE SY 2023-2024 Trends, Networks, and Critical Th...
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
An Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdfAn Overview of Mutual Funds Bcom Project.pdf
An Overview of Mutual Funds Bcom Project.pdf
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 

3.2 looping statement

  • 2. Motivations Suppose that you need to print a string (e.g., "Programming is fun!") a hundred times. It would be tedious to have to write the following statement a hundred times: print("Programming is fun!"); So, how do you solve this problem? 2ARULKUMAR V Ap/CSE SECE
  • 3. Opening Problem Problem: 3 print("Programming is fun!"); print("Programming is fun!"); print("Programming is fun!"); print("Programming is fun!"); print("Programming is fun!"); print("Programming is fun!"); … … … print("Programming is fun!"); print("Programming is fun!"); print("Programming is fun!"); 100 times ARULKUMAR V Ap/CSE SECE
  • 4. Introducing while Loops 4 count = 0 while count < 100: print("Programming is fun!") count = count + 1 ARULKUMAR V Ap/CSE SECE
  • 5. Objectives ARULKUMAR V Ap/CSE SECE 5  To write programs for executing statements repeatedly by using a while loop (§5.2).  To develop loops following the loop design strategy (§§5.2.1-5.2.3).  To control a loop with the user’s confirmation (§5.2.4).  To control a loop with a sentinel value (§5.2.5).  To obtain a large amount of input from a file by using input redirection instead of typing from the keyboard (§5.2.6).  To use for loops to implement counter-controlled loops (§5.3).  To write nested loops (§5.4).  To learn the techniques for minimizing numerical errors (§5.5).  To learn loops from a variety of examples (GCD, FutureTuition, MonteCarloSimulation, PrimeNumber) (§§5.6, 5.8).  To implement program control with break and continue (§5.7).  To use a loop to control and simulate a random walk (§5.9).
  • 6. while Loop Flow Chart 6 while loop-continuation-condition: # Loop body Statement(s) count = 0 while count < 100: print("Programming is fun!") count = count + 1 loop- continuation condition? True Statement(s) (loop body) False count < 100? True print("Programming is fun!") count = count + 1 False (a) (b) count = 0 ARULKUMAR V Ap/CSE SECE
  • 7. Trace while Loop 7 count = 0 while count < 2: print("Programming is fun!") count = count + 1 Initialize count animation ARULKUMAR V Ap/CSE SECE
  • 8. Trace while Loop, cont. 8 count = 0 while count < 2: print("Programming is fun!") count = count + 1 (count < 2) is true animation ARULKUMAR V Ap/CSE SECE
  • 9. Trace while Loop, cont. 9 count = 0 while count < 2: print("Programming is fun!") count = count + 1 Print Welcome to Python animation ARULKUMAR V Ap/CSE SECE
  • 10. Trace while Loop, cont. 10 count = 0 while count < 2: print("Programming is fun!") count = count + 1 Increase count by 1 count is 1 now animation ARULKUMAR V Ap/CSE SECE
  • 11. Trace while Loop, cont. 11 count = 0 while count < 2: print("Programming is fun!") count = count + 1 (count < 2) is still true since count is 1 animation ARULKUMAR V Ap/CSE SECE
  • 12. Trace while Loop, cont. 12 count = 0 while count < 2: print("Programming is fun!") count = count + 1 Print Welcome to Python animation ARULKUMAR V Ap/CSE SECE
  • 13. Trace while Loop, cont. 13 count = 0 while count < 2: print("Programming is fun!") count = count + 1 Increase count by 1 count is 2 now animation ARULKUMAR V Ap/CSE SECE
  • 14. Trace while Loop, cont. 14 count = 0 while count < 2: print("Programming is fun!") count = count + 1 (count < 2) is false since count is 2 now animation ARULKUMAR V Ap/CSE SECE
  • 15. Trace while Loop 15 count = 0 while count < 2: print("Programming is fun!") count = count + 1 The loop exits. Execute the next statement after the loop. animation ARULKUMAR V Ap/CSE SECE
  • 16. Problem: An Advanced Math Learning Tool The Math subtraction learning tool program generates just one question for each run. You can use a loop to generate questions repeatedly. This example gives a program that generates five questions and reports the number of the correct answers after a student answers all five questions. 16 SubtractionQuizLoop Run ARULKUMAR V Ap/CSE SECE
  • 17. Problem: Guessing Numbers Write a program that randomly generates an integer between 0 and 100, inclusive. The program prompts the user to enter a number continuously until the number matches the randomly generated number. For each user input, the program tells the user whether the input is too low or too high, so the user can choose the next input intelligently. Here is a sample run: 17 GuessNumberOneTime Run GuessNumber Run ARULKUMAR V Ap/CSE SECE
  • 18. Ending a Loop with a Sentinel Value Often the number of times a loop is executed is not predetermined. You may use an input value to signify the end of the loop. Such a value is known as a sentinel value. Write a program that reads and calculates the sum of an unspecified number of integers. The input 0 signifies the end of the input. 18 SentinelValue Run ARULKUMAR V Ap/CSE SECE
  • 19. Caution item = 1 sum = 0 while item != 0: # No guarantee item will be 0 sum += item item -= 0.1 print(sum) 19 Variable item starts with 1 and is reduced by 0.1 every time the loop body is executed. The loop should terminate when item becomes 0. However, there is no guarantee that item will be exactly 0, because the floating-point arithmetic is approximated. This loop seems OK on the surface, but it is actually an infinite loop. Don’t use floating-point values for equality checking in a loop control. Since floating-point values are approximations for some values, using them could result in imprecise counter values and inaccurate results. Consider the following code for computing 1 + 0.9 + 0.8 + ... + 0.1: ARULKUMAR V Ap/CSE SECE
  • 20. for Loops i = initialValue # Initialize loop-control variable while i < endValue: # Loop body ... i++ # Adjust loop-control variable 20 for i in range(initialValue, endValue): # Loop body ARULKUMAR V Ap/CSE SECE
  • 21. range(a, b) >>> for v in range(4, 8): ... print(v) ... 4 5 6 7 >>> 21ARULKUMAR V Ap/CSE SECE
  • 22. range(b) >>> for i in range(4): ... print(i) ... 0 1 2 3 >>> 22ARULKUMAR V Ap/CSE SECE
  • 23. range(a, b, step) >>> for v in range(3, 9, 2): ... print(v) ... 3 5 7 >>> 23ARULKUMAR V Ap/CSE SECE
  • 24. range(a, b, step) >>> for v in range(5, 1, -1): ... print(v) ... 5 4 3 2 >>> 24ARULKUMAR V Ap/CSE SECE
  • 25. Nested Loops Problem: Write a program that uses nested for loops to print a multiplication table. 25 MultiplicationTable Run ARULKUMAR V Ap/CSE SECE
  • 26. Minimizing Numerical Errors Numeric errors involving floating-point numbers are inevitable. This section discusses how to minimize such errors through an example. Here is an example that sums a series that starts with 0.01 and ends with 1.0. The numbers in the series will increment by 0.01, as follows: 0.01 + 0.02 + 0.03 and so on. 26 TestSum Run ARULKUMAR V Ap/CSE SECE
  • 27. Problem: Finding the Greatest Common Divisor 27 Problem: Write a program that prompts the user to enter two positive integers and finds their greatest common divisor. Solution: Suppose you enter two integers 4 and 2, their greatest common divisor is 2. Suppose you enter two integers 16 and 24, their greatest common divisor is 8. So, how do you find the greatest common divisor? Let the two input integers be n1 and n2. You know number 1 is a common divisor, but it may not be the greatest commons divisor. So you can check whether k (for k = 2, 3, 4, and so on) is a common divisor for n1 and n2, until k is greater than n1 or n2. GreatestCommonDivisor Run ARULKUMAR V Ap/CSE SECE
  • 28. Problem: Predicting the Future Tuition 28 Problem: Suppose that the tuition for a university is $10,000 this year and tuition increases 7% every year. In how many years will the tuition be doubled? FutureTuition Run ARULKUMAR V Ap/CSE SECE
  • 29. Problem: Predicating the Future Tuition 29 year = 0 # Year 0 tuition = 10000 year += 1 # Year 1 tuition = tuition * 1.07 year += 1 # Year 2 tuition = tuition * 1.07 year += 1 # Year 3 tuition = tuition * 1.07 FutureTuition Run ARULKUMAR V Ap/CSE SECE
  • 30. Problem: Monte Carlo Simulation 30 The Monte Carlo simulation refers to a technique that uses random numbers and probability to solve problems. This method has a wide range of applications in computational mathematics, physics, chemistry, and finance. This section gives an example of using the Monto Carlo simulation for estimating . MonteCarloSimulation Run x y 1-1 1 -1 circleArea / squareArea =  / 4.  can be approximated as 4 * numberOfHits / 1000000. ARULKUMAR V Ap/CSE SECE
  • 31. Using break and continue 31 Examples for using the break and continue keywords:  TestBreak.py  TestContinue.py TestBreak TestContinue Run Run ARULKUMAR V Ap/CSE SECE
  • 32. break 32 sum = 0 number = 0 while number < 20: number += 1 sum += number if sum >= 100: break print("The number is ", number) print("The sum is ", sum) Break out of the loop ARULKUMAR V Ap/CSE SECE
  • 33. continue 33 sum = 0 number = 0 while (number < 20): number += 1 if (number == 10 or number == 11): continue sum += number print("The sum is ", sum) Jump to the end of the iteration ARULKUMAR V Ap/CSE SECE
  • 34. Guessing Number Problem Revisited Here is a program for guessing a number. You can rewrite it using a break statement. 34 GuessNumberUsingBreak Run ARULKUMAR V Ap/CSE SECE
  • 35. Problem: Displaying Prime Numbers 35 Problem: Write a program that displays the first 50 prime numbers in five lines, each of which contains 10 numbers. An integer greater than 1 is prime if its only positive divisor is 1 or itself. For example, 2, 3, 5, and 7 are prime numbers, but 4, 6, 8, and 9 are not. Solution: The problem can be broken into the following tasks: •For number = 2, 3, 4, 5, 6, ..., test whether the number is prime. •Determine whether a given number is prime. •Count the prime numbers. •Print each prime number, and print 10 numbers per line. PrimeNumber Run ARULKUMAR V Ap/CSE SECE
  • 36. Turtle: Random Walk 36 RandomWalk Run ARULKUMAR V Ap/CSE SECE