Indefinite Iteration


CS 1109


July 10th, 2023

Administrative

  • Assignment 2 is due today at 9:00pm!
    • OH from 1-4pm today (Gates 333)
  • Read Think Python Ch. 7.3 for tomorrow
  • Assignment 3 out at 5pm
    • Due Friday (7/14) at 9:00pm

Motivation

Indefinite Iteration

  • Indefinite Iteration: Keep doing something until something happens.
    • Unknown number of repetitions
  • Examples
    • Move robot forward 1ft. until it hits a wall
    • Ask for password until password is correct

Example: Input Validation

  • Frequently want to ask for user input
    • Problem: What if the user provides an incorrect input?
    • Example: Prompt asks for an integer but user enters a string
  • If incorrect input is given, need to re-prompt user
    • Number of re-prompts is unknown!

When number of repetitions is unknown

Example: Input Validation

num = int(input('Enter an even integer: '))
while num % 2 != 0:
		num = int(input('Enter an even integer: '))

  1. Initially ask for an even integer from user.

Example: Input Validation

num = int(input('Enter an even integer: '))
while num % 2 != 0:
		num = int(input('Enter an even integer: '))
  1. Initially ask for an even integer from user.
  2. Check if num is not even
    • If not even (i.e. num % 2 != 0 is True), execute body of while-loop
    • Otherwise, end the loop

Example: Input Validation

num = int(input('Enter an even integer: '))
while num % 2 != 0:
		num = int(input('Enter an even integer: '))
  1. Initially ask for an even integer from user.
  2. Check if num is not even
    • If not even (i.e. num % 2 != 0 is True), execute body of while-loop
    • Otherwise, end the loop
  3. Body of while-loop asks re-prompts user and updates num

Example: Input Validation

num = int(input('Enter an even integer: '))
while num % 2 != 0:
		num = int(input('Enter an even integer: '))
  1. Initially ask for an even integer from user.
  2. Check if num is not even
    • If not even (i.e. num % 2 != 0 is True), execute body of while-loop
    • Otherwise, end the loop
  3. Body of while-loop asks re-prompts user and updates num
  4. Go back to step 2 to recheck num

Example: Input Validation

num = int(input('Enter an even integer: '))
while num % 2 != 0:
		num = int(input('Enter an even integer: '))

while-loops

Execution of while-loops

while test:
		<STATEMENT>
		...
		<STATEMENT>

while-loop Guarantee

while-loops ensure a condition is False

num = int(input('Enter an even integer: '))

while num % 2 != 0:
		num = int(input('Enter an even integer: '))

# num is guaranteed to be even after the while-loop!

Example: Double until over 100

Write a program with a while-loop that doubles an integer until it is greater than 100.

n = int(input('Enter an integer: '))





Example: Double until over 100

Write a program with a while-loop that doubles an integer until it is greater than 100.

n = int(input('Enter an integer: '))

while n <= 100:
		# If n <= 100, double it.
		n = n * 2

Example: Double until over 100

Write a program with a while-loop that doubles an integer until it is greater than 100.

n = int(input('Enter an integer: '))

while n <= 100:
		# If n <= 100, double it.
		n = n * 2
# After loop: n > 100

Example: Snake Eyes

snake_eyes.jpg

Write a while-loop to count how many times it takes to roll snake eyes given two fair die.

Example: Snake Eyes

Write a while-loop to count how many times it takes to roll snake eyes given two fair die.

# Import randint() function from Python's random module
from random import randint
d1 = randint(1,6) # Roll a 6-sided die
d2 = randint(1,6) # Roll another 6-sided die









Example: Snake Eyes

Write a while-loop to count how many times it takes to roll snake eyes given two fair die.

# Import randint() function from Python's random module
from random import randint
d1 = randint(1,6) # Roll a 6-sided die
d2 = randint(1,6) # Roll another 6-sided die
count = 1 # Number of times dice have been rolled








Example: Snake Eyes

Write a while-loop to count how many times it takes to roll snake eyes given two fair die.

# Import randint() function from Python's random module
from random import randint
d1 = randint(1,6) # Roll a 6-sided die
d2 = randint(1,6) # Roll another 6-sided die
count = 1 # Number of times dice have been rolled
while not (d1 == 1 and d2 == 1):







Example: Snake Eyes

Write a while-loop to count how many times it takes to roll snake eyes given two fair die.

# Import randint() function from Python's random module
from random import randint
d1 = randint(1,6) # Roll a 6-sided die
d2 = randint(1,6) # Roll another 6-sided die
count = 1 # Number of times dice have been rolled
while not (d1 == 1 and d2 == 1):
		# Roll dice again
		d1 = randint(1,6)
		d2 = randint(1,6)




Example: Snake Eyes

Write a while-loop to count how many times it takes to roll snake eyes given two fair die.

# Import randint() function from Python's random module
from random import randint
d1 = randint(1,6) # Roll a 6-sided die
d2 = randint(1,6) # Roll another 6-sided die
count = 1 # Number of times dice have been rolled
while not (d1 == 1 and d2 == 1):
		# Roll dice again
		d1 = randint(1,6)
		d2 = randint(1,6)
		# Update count
		count = count + 1


Example: Snake Eyes

Write a while-loop to count how many times it takes to roll snake eyes given two fair die.

# Import randint() function from Python's random module
from random import randint
d1 = randint(1,6) # Roll a 6-sided die
d2 = randint(1,6) # Roll another 6-sided die
count = 1 # Number of times dice have been rolled
while not (d1 == 1 and d2 == 1):
		# Roll dice again
		d1 = randint(1,6)
		d2 = randint(1,6)
		# Update count
		count = count + 1
# d1 == 1 and d2 == 1 (snake eyes!)
print(count)

WARNING: This loop theoretically could never end…

Spot the Bug

n = 0
while n >= 0:
		n = n + 1
		print(n)

The loop condition is always True!

Infinite Loop

while True:
		# Will greet the world, over and over, forever...
		print('Hello, World!')

Exercise: Translation

"Stop asking when user enters 0."

n = int(input('Enter an int: '))
while ___:
		n = int(input('Enter an int: '))

"Keep asking until user enters 0."

n = int(input('Enter an int: '))
while ___:
		n = int(input('Enter an int: '))

Exercise: Translation

"Stop asking when user enters 0."

n = int(input('Enter an int: '))
while n != 0:
		n = int(input('Enter an int: '))

"Keep asking until user enters 0."

n = int(input('Enter an int: '))
while n != 0:
		n = int(input('Enter an int: '))

while-loops repeat while the condition is True

Continuation Condition

Check whether to continue looping

Stopping Condition

Check whether to stop looping

Exercise: Translation 2.0

  1. "Stop looping when x is greater than 100."
    • Stopping Condition:

      x > 100
      
    • Continutation Condition:

      x <= 100
      not (x > 100)
      
  2. "Keep looping until x is greater than 0 and less than 10"
    • Stopping Condition:

      x > 0 and x < 10
      
    • Continuation Condition:

      x <= 0 or x >= 10
      not (x > 0 and x < 10)
      

while-loops use the continuation condition!

while vs. for

for-loops are while-loops

Sum the first 10 positive integers.

for

s = 0
for n in range(1,11):
		s = s + n

while

s = 0
n = 1 # Need to initialize n!
while n < 11:
		s = s + n
		# Need to increment n!
		n = n + 1 

These loops are equivalent!

for vs. while

for

  • Often simpler and requires less code
    • Python decides when to exit (e.g., list is exhausted)
  • Does something a known number of times
  • Examples:
    • Send 20 emails
    • Sum together numbers in list

while

  • More general, but requires more code
    • You decide when to exit
  • Does something an unknown number of times
  • Examples:
    • Re-prompt user until input is valid
    • Move robot until it hits wall
    • Double number until over 100

Designing Loops

Four Questions

  1. Is it definite or indefinite iteration?
    • Definite: Use for-loop
    • Indefinite: Use while-loop
  2. When should the repetition stop?
    • What should the stopping or continuation condition be?
  3. How should the repetition start?
    • Are all variables initialized?
    • What should the starting value be?
  4. What should be repeated?
    • Are you updating the loop variable if using a while-loop?

Exercise: Number Guessing Game

"""
Returns the number of times a user takes to guess a randomly
generated int between 1 and 100.

Prints feedback for the user after each guess. Prints message indicating
correct guess.
"""
  1. Is it definite or indefinite iteration?
  2. When should the repetition stop?
  3. How should the repetition start?
  4. What should be repeated?

Exercise: Number Guessing Game

"""
Returns the number of times a user takes to guess a randomly
generated int between 1 and 100.

Prints feedback for the user after each guess. Prints message
indicating correct guess.
"""
  1. Is it definite or indefinite iteration?
    • Indefinite
  2. When should the repetition stop?
    • Stopping Condition: when user guesses correctly
  3. How should the repetition start?
    • Pick random number between 1 and 100
    • Ask user for first guess
    • Initialize variable to store number of guesses (e.g., num_guesses)
  4. What should be repeated?
    • Provide feedback about guess
    • Ask user for new guess
    • Increment num_guesses

while-loop Checklist

  1. Are all the variables in the loop condition initialized?
  2. Is the loop condition the continuation condition?
    • If the stopping condition, negate it!
  3. Did you update the loop variables in the loop body?
  4. Can the loop ever stop?

Review

Review: Indefinite Iteration

  • Indefinite iteration repeats something an unknown number of times
  • while-loop: repeats body while condition is True

    while condition:
    		<STATEMENT>
    		...
    		<STATEMENT>
    
  • Continuation vs. Stopping conditions
  • for vs. while loops
  • Loop design tips