Loops
- While loop
- Repeatedly echo
input()
untilq
-
q
is a “sentinel value”str = input() while str != 'q': print('You said: ', str) str = input()
- Repeatedly echo
-
Get numbers until sentinel is seen to compute average (from book)
values_sum = 0 num_values = 0 curr_value = int(input()) while curr_value > 0: # Get values until 0 (or less) values_sum += curr_value num_values += 1 curr_value = int(input()) print(f'Average: {values_sum / num_values:.0f}\n')
-
Print growth of savings in an account (from book)
initial_savings = 10000 interest_rate = 0.05 print(f'Initial savings of ${initial_savings}') print(f'at {interest_rate*100:.0f}% yearly interest.\n') years = int(input('Enter years: ')) print() savings = initial_savings i = 1 # Loop variable while i <= years: # Loop condition print(f' Savings at beginning of year {i}: ${savings:.2f}') savings = savings + (savings*interest_rate) i = i + 1 # Increment loop variable print('\n')
-
How to add additional principal once per year?
- Quick intro to a list
- Note: Avoid using
list
as a variable name.
lst = ['a', 'b', 'c', 'd', 'e'] print(lst[0]) print(lst[3]) lst[4] = 'changed' print(lst)
- Note: Avoid using
- Use
for
loop to sum over a list. - Use
for
to loop through a string and count ‘e’s - inClass basic loops:
- guessing game
- count_evens
- max_int
- contains_negative
- is_prime
- num_primes
Range
- Write tests for
strictly-increasing
(In-Class 6) -
Try to do
strictly-increasing
with standard for-each loop. - When you loop over part of a list or string, you need to specify the indices you want.
- In this case, you often need to know the length of the item:
-
Use built-in function
len
to get the lengthlst = ['a', 'b', 'c', 'd', 'e'] print(len(lst))
range
- end value not included.
- can add a step
- step can be negative (to count down)
- What happens if step is negative but range is not
range(5, 10, -1)
-
range
is better thanwhile
since range won’t let you accidentally write an infinite loopfor index in range(3, 5): print(f"value at {index}: {lst[index]}")
- use
list(range(...))
to demonstrate what range is created.
- Show how to do
is_strictly_increasing
withrange
- Look at
is_equal
on in-Class 6.
Break and Continue
-
break
immediately ends a loop:for val in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]: if val > 5: break print(val)
-
Show how to do
is_strictly_increasing
withbreak
-
Continue skips the rest of the loop
for val in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]: if val % 3 == 0 continue print(val)
Loop else
-
If you put an
else
on a loop, that block runs only if the loop runs to completion.for val in [1, 3, 5, 9, 7, 11, 221, 339, 446]: if val % 2 == 0: print(f"{val} is the first even number on the list") break else: print("There were no even numbers on the list")
-
When you want both the index and the value, use
enumerate
origins = [4, 8, 10] for (index, value) in enumerate(origins): print(f'Element {index}: {value}')
-
Do
count_successors
for homework