1 of 20

For Loop - range

Andrea Wu

2 of 20

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

3 of 20

Baking Cookies

# Bake 400 batches of cookies.

count = 0

while count < 400:

[bake cookies]

count = count + 1

4 of 20

Baking Cookies

# Bake 400 batches of cookies.

for i in range(0, 400):

[bake cookies]

5 of 20

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

6 of 20

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

7 of 20

EdStem: range

8 of 20

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!

9 of 20

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

10 of 20

Tracing for loops

for num in range(3, 5):

print(num)

print('exited loop')

num

11 of 20

Tracing for loops

for num in range(3, 5):

print(num)

print('exited loop')

num

12 of 20

Tracing for loops

for num in range(3, 5):

print(num)

print('exited loop')

3

num

13 of 20

Tracing for loops

for num in range(3, 5):

print(num)

print('exited loop')

3

num

3

14 of 20

Tracing for loops

for num in range(3, 5):

print(num)

print('exited loop')

4

num

3

15 of 20

Tracing for loops

for num in range(3, 5):

print(num)

print('exited loop')

4

num

3

4

16 of 20

Tracing for loops

for num in range(3, 5):

print(num)

print('exited loop')

4

num

3

4

Reached 5. Nothing left!

17 of 20

Tracing for loops

for num in range(3, 5):

print(num)

print('exited loop')

4

num

3

4

exited loop

18 of 20

EdStem: for loop - range

19 of 20

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

20 of 20

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