For Loop - range
Andrea Wu
Review: For Loop
What is it?
Control structure that runs block of code repeatedly by iterating over elements in sequence
for [variable] in [sequence]:
[execute code]
Why is it important?
Ability to do something a certain number of times
Do not need to copy and paste same code over and over
For vs While
for runs code predetermined / known number of times
while runs until certain condition is no longer met
Baking Cookies
# Bake 400 batches of cookies.
count = 0
while count < 400:
[bake cookies]
count = count + 1
Baking Cookies
# Bake 400 batches of cookies.
for i in range(0, 400):
[bake cookies]
range()
range(): returns sequence from start to end (not including end)
Use range() with for loops to repeat a loop when need numbers
range(5, 8)
5 6 7
range(0, 5)
0 1 2 3 4
range()
Can give it just one number instead of two - end index (not including it) starting from 0
range(3) is equivalent to range(0, 3) - both will give 0, 1, 2
range(5)
0 1 2 3 4
range(1)
0
EdStem: range
range() vs while loop
i = 0
while i < 10:
print(i)
i = i + 1
for i in range(0, 10):
print(i)
these are equivalent!
in vs range
letter data type?
ALWAYS string
for num in range(5):
print(num)
for letter in '123':
print(letter)
num data type?
ALWAYS integer
Tracing for loops
for num in range(3, 5):
print(num)
print('exited loop')
num
Tracing for loops
for num in range(3, 5):
print(num)
print('exited loop')
num
Tracing for loops
for num in range(3, 5):
print(num)
print('exited loop')
3
num
Tracing for loops
for num in range(3, 5):
print(num)
print('exited loop')
3
num
3
Tracing for loops
for num in range(3, 5):
print(num)
print('exited loop')
4
num
3
Tracing for loops
for num in range(3, 5):
print(num)
print('exited loop')
4
num
3
4
Tracing for loops
for num in range(3, 5):
print(num)
print('exited loop')
4
num
3
4
Reached 5. Nothing left!
Tracing for loops
for num in range(3, 5):
print(num)
print('exited loop')
4
num
3
4
exited loop
EdStem: for loop - range
for … in ...
for … in range(...)
for [variable] in [sequence]:
[code]
for [variable] in range(...):
[code]
Iterating over a sequence, like a string
for letter in 'dog'
letter will be each character in 'dog'
Iterating over numbers
for number in range(10)
number will be a number from 0 to 10
Review: For Loop
What is it?
Control structure that runs block of code repeatedly by iterating over elements in sequence
for [variable] in [sequence]:
[execute code]
for [variable] in range(start, end):
[execute code]
[variable] is ALWAYS string
[variable] is ALWAYS integer