Nate Brunelle Today: Repetition, Repetition CS1110 Nate Brunelle Today: Repetition, Repetition
Questions?
Last Time While loops For loops
“While” Loops while loop Keep repeating until the boolean expression is False “so long as this is True, keep doing the action” Guard Condition while boolean expression: action1 action2 Body/ Inside
Rules for While Loops Some aspect of the Guard Condition must change in the body It must change in a way such that it will eventually become false Note: The guard is checked at the end
“for” Loops For loop for [variable v] in [collection]: action Do the action a certain number of times “do the action once per each thing in here” The variable takes the value of each thing in the collection in order for [variable v] in [collection]: action for i in range(5): print(‘hi’) Range(5) -> [0,1,2,3,4]
Collections Order doesn’t matter, No Repetition Order Matters, Repetition ok Examples: String List Tuple Range Counting starts at 0 collection[index] gives a specific value in the collection Order doesn’t matter, No Repetition Examples: Set Dict
Range range(x) range(x,y) Gives all integers from 0 (inclusive) to x (exclusive) range(5) -> 0,1,2,3,4 range(x,y) Gives all integers from x (inclusive) to y (exclusive) Range (2, 6) -> 2,3,4,5 [lower, upper)
hello Strings Collection of characters Order Matters Repetition ok X = “hello” X[0] -> h hello 1 2 3 4 Indices
Which kind of loop? I know condition to stop repeating I know the number of times I want to repeat I want to repeat once per thing in a collection