CIS 111 Repetition

Objectives

  • Solve problems using Python repetition
  • Use Python while statements
  • Use Python for statements
  • Use Python nested repetition
  • Validate user input

Terminology

  • loop body: the statements within a loop
  • accumulator: a variable used to sum up values
  • counter controlled: a loop where the number of repetitions are controlled by a variable used as a loop counter
  • loop counter: a variable used to control the number of times a loop executes, usually by counting up or down
  • sentinel value: a special value in the input data used to signal the end of input or special processing
  • priming read: a read of input before a loop to decide if the loop will run at all which is repeated at the end of the loop body

"while" statement - counter controlled

i = 1 while i <= 10: print(i) i = i + 1

Counter controlled while statement

"while" statement - sentinel value, accumulator, priming read

sum = 0 strIn = input("Enter number to add (QUIT to exit): ") while strIn.upper() != "QUIT": num = float(strIn) sum = sum + num strIn = input("Enter number to add (QUIT to exit): ") else: print("The sum is %f" % sum)

Sentinel controlled while statement

"while" statement - input validation

valid = False while not valid: n = int(input("Enter an integer from 1 through 10: ")) if n < 1: print("Error: Below minimum value of 1"); elif n > 10: print("Error: Above maximum value of 10"); else: valid = True print("You entered: %d" % n)

Input validation loop

"for" loop - iteration through string

for letter in "CIS 111": print(letter)

for loop iterating through string

"for" loop - iteration through list

for num in [1, 7, 12, -4, 5]: print(num)

for loop iterating through list

"for" loop - iteration through tuple

for num in 1, 7, 12, -4, 5: # parentheses optional around tuple print(num)

for loop iterating through tuple

"for" loop - iteration through range

sum = 0 for n in range(1, 101, 2): # 1, 3, ..., 99 sum = sum + n print("The sum is %f" % sum)

for loop iterating through range