Repetition - PowerPoint PPT Presentation

About This Presentation
Title:

Repetition

Description:

mystring = 'CS is cool!' for c in mystring: print c. Loop iterates over a list ... break #combines intialization and update. Problem. Print ... – PowerPoint PPT presentation

Number of Views:20
Avg rating:3.0/5.0
Slides: 17
Provided by: csUs7
Learn more at: https://www.cs.usfca.edu
Category:

less

Transcript and Presenter's Notes

Title: Repetition


1
Repetition
2
Examples
  • When is repetition necessary/useful?

3
Types of Loops
  • Counting loop
  • Know how many times to loop
  • Sentinel-controlled loop
  • Expect specific input value to end loop
  • Endfile-controlled loop
  • End of data file is end of loop
  • Input validation loop
  • Valid input ends loop
  • General conditional loop
  • Repeat until condition is met

4
while
  • while condition
  • statements
  • x1
  • while x lt 10
  • print x
  • x x 1

5
while
  • x1 initialization of control variable
  • while x lt 10 condition
  • print x task to be repeated
  • x x 1 update - VERY VERY IMPORTANT

6
Sentinel-controlled
  • num input("Enter number - 0 to quit ")
  • while num ! 0
  • print You entered , num
  • num input("Enter number - 0 to quit ")
  • Which is the control variable?

7
Input Validation
  • num input("Enter number between 0 and 100 ")
  • while num lt 0 or num gt 100 a more complex
    condition
  • print "Invalid input"
  • num input("Enter number between 0 and
    100 ")

8
for
  • for x in range(10)
  • print x
  • mystring "CS is cool!"
  • for c in mystring
  • print c
  • Loop iterates over a list
  • Initialization and update happen automatically

9
Infinite Loops
  • If your program hangs you probably forgot to
    update your control variable
  • x1
  • while x1
  • print x is 1
  • Why is this bad?
  • x1
  • end_value10
  • while x ! end_value
  • do something

10
Infinite Loops
  • Why is this bad?
  • x1
  • end_value10
  • while x ! end_value
  • do something
  • x 2
  • x1
  • end_value10
  • while x lt end_value better
  • do something

11
Alternative
  • while 1
  • num input(Enter a number - 0 to quit )
  • if num 0
  • break combines intialization and update

12
Problem
  • Print
  • The only print statements you can use are the
    following
  • print , the comma prevents the \n
  • print


13
Nested Loops
  • print a rectangle of stars
  • 3 times
  • print a line of stars

14
Nested Loops
  • print a rectangle of stars
  • x1
  • while x lt 3
  • print a line of stars
  • print a line of stars
  • y1
  • while ylt3
  • print ,

15
Nested Loops
  • print a rectangle of stars
  • x1
  • while x lt 3
  • print a line of stars
  • y1
  • while ylt3
  • print ,
  • DONE?

16
Nested Loops
  • print a rectangle of stars
  • x1
  • while x lt 3
  • print a line of stars
  • y1
  • while ylt3
  • print ,
  • y1
  • print
  • x1
Write a Comment
User Comments (0)
About PowerShow.com