Doing something repeatedly.
Examples
Repeat doing something a known number of times.
Examples:
Keep doing something until something happens.
Throw darts!
Area of Square: \(2 \times 2 = 4\)
Area of Circle: \(\pi \times 1^2 = \pi\)
\[ \frac{\text{Area of Circle}}{\text{Area of Square}} = \frac{\pi}{4} \]
\[ \frac{\text{Area of Circle}}{\text{Area of Square}} = \frac{\pi}{4} \]
If we throw \(N\) darts: \[ \pi \approx \frac{4 \times {\color{red}{\text{# darts in circle}}}}{{\color{green}{\text{# darts in square}}}} \]
Algorithm in English:
n = 1000 # number of darts to throw
hits = 0 # number of darts that land inside circle
pi_est = 4.0 * hits / n
print("pi is approximately:", pi_est)
n = 1000 # number of darts to throw
hits = 0 # number of darts that land inside circle
for k in range(n):
pi_est = 4.0 * hits / n
print("pi is approximately:", pi_est)
n = 1000 # number of darts to throw
hits = 0 # number of darts that land inside circle
for k in range(n):
# Throw kth dart
# Did the dart land in the circle?
pi_est = 4.0 * hits / n
print("pi is approximately:", pi_est)
from random import uniform
n = 1000 # number of darts to throw
hits = 0 # number of darts that land inside circle
for k in range(n):
# Throw kth dart
x = uniform(-1, 1)
y = uniform(-1, 1)
# Did the dart land in the circle?
pi_est = 4.0 * hits / n
print("pi is approximately:", pi_est)
from random import uniform
n = 1000 # number of darts to throw
hits = 0 # number of darts that land inside circle
for k in range(n):
# Throw kth dart
x = uniform(-1, 1)
y = uniform(-1, 1)
# Did the dart land in the circle?
if x**2 + y**2 <= 1:
hits = hits + 1
pi_est = 4.0 * hits / n
print("pi is approximately:", pi_est)
from random import uniform
n = 1000 # number of darts to throw
hits = 0 # number of darts that land inside circle
for k in range(n):
# Throw kth dart
x = uniform(-1, 1)
y = uniform(-1, 1)
# Did the dart land in the circle?
if x**2 + y**2 <= 1:
hits = hits + 1
pi_est = 4.0 * hits / n
print("pi is approximately:", pi_est)
for
-loopsfor <variable> in <sequence>:
<statement>
...
<statement>
Key Concepts
range
, a list, a string)for
-loopsfor x in seq:
print(x)
range()
range
gives you an int
sequenceGeneral Usage
range(n) # 0, 1, ..., n-1
range(a,b) # a, a+1, ..., b-1
range(a,b,s) # a, a + s, a + 2s, ..., <= b-1
range()
Examplesrange(4) -->
range(-3, 2) -->
range(3, 4) -->
range(3, 3) -->
range(1, 6, 2) -->
range(6, 0, -2) -->
range(6, 0, 2) -->
range()
Examplesrange(4) --> 0, 1, 2, 3
range(-3, 2) --> -3, -2, -1, 0, 1
range(3, 4) --> 3
range(3, 3) --> # empty sequence, not error!
range(1, 6, 2) --> 1, 3, 5
range(6, 0, -2) --> 6, 4, 2
range(6, 0, 2) --> # empty sequence, not error!
n = _______
for k in range(n):
# Code that does "something" here...
n = 10
for k in range(n):
print(2**k)
Let's try it out on Python Tutor!
for
-loops and empty sequencesProgram A
for k in range(3,4):
print(k)
print('Out of loop')
Output
3
Out of loop
Program B
for k in range(3,3):
print(k)
print('Out of loop')
Output
Out of loop
for
-loops & Strings
Recall the structure for for
-loops:
for x in seq:
print(x)
seq
can be any sequence!
for
-loops & StringsProgram:
for letter in 'ABCDE':
print(letter + '!')
Output:
A!
B!
C!
D!
E!
for
-loops & listsProgram:
names = ['Alice', 'Bob', 'Eve']
for name in names:
print('Hi, ' + name + '!')
Output:
Hi, Alice!
Hi, Bob!
Hi, Eve!
Write a for
-loop to count the number of letters in s
:
s = 'pneumonoultramicroscopicsilicovolcanoconiosis'
Write a for
-loop to count the number of letters in s
:
s = 'pneumonoultramicroscopicsilicovolcanoconiosis'
count = 0 # Number of letters
print('There are', count, 'letters in s.')
Write a for
-loop to count the number of letters in s
:
s = 'pneumonoultramicroscopicsilicovolcanoconiosis'
count = 0 # Number of letters
for letter in s:
count = count + 1 # Add 1 to the count
print('There are', count, 'letters in s.')
General Pattern
count = 0 # Variable to store count in outside of loop
# Loop over each element in sequence:
for k in seq_to_count:
# Increment count by 1 for each element
count = count + 1
Write a for
-loop to compute the sum of a list:
nums = [3, 17, -2, 42, 101, -21]
Write a for
-loop to compute the sum of a list:
nums = [3, 17, -2, 42, 101, -21]
sum_so_far = 0 # Current sum
print('The sum is', sum_so_far)
Write a for
-loop to compute the sum of a list:
nums = [3, 17, -2, 42, 101, -21]
sum_so_far = 0 # Current sum
for n in nums:
# Add n to sum
sum_so_far = sum_so_far + n
print('The sum is', sum_so_far)
General Form
accum = 0 # Variable to store result
# Loop over each element in sequence:
for x in seq:
# Modify accumulated value using <OP> (e.g., +, *, -)
accum = accum <OP> x
Called the accumulator pattern as you "accumulate" your result inside of a loop
for
-loops are a form of definite iteration
range()
gives you an int
sequence
range(3) --> 0, 1, 2
range(1, 5) --> 1, 2, 3, 4
range(0, 4, 2) --> 0, 2
Use for
-loop to do something to every element of a string or list
# Prints each element of list
for x in [3, 42, -2, 5]:
print(x)