For Loops

Loops, In General

Does anyone remember the two broad categories of loops? What are they, and how are they different?

Condition Controlled Loops in Python

What programming construct (repetition structure) do we use in Python to create a condition-controlled loop?

A while loop is a repetition structure in Python that repeats a block of code as long as a check for a particular condition is true.

Count-Controlled Loops

For Loops

An Example

for i in range(5):
	print(i)

Its output:

0
1
2
3
4

For Loop Syntax

for loops repeat code by iterating over every item in some group / collection of items:

"""
for <loop variable> in <iterable object>:
	(<loop variable> can be used here)
"""

Again, the same example:

"""
 keyword    loop    an iterable object,
     for  variable  like range
       |     |      |
       |     |      |
        for i in range(5):
              print(i)
"""

Let's Break That Down a Bit

A for loop:

For Loops - Details, Details, Details

What Does It Do?

A for loop:

For Loops

A more technical explanation is: for loops iterate over every item in an iterable object.

An iterable object:

Range and Range Objects

A range object is another data type! It represents an arithmetic sequence, such as 0, 1, 2, 3, 4.

Showing the Results of Range

Let's see if we can make sense of this:

#  make a range object - an arithmetic sequence from 0 through 5
numbers = range(5)

#  let's look at that object
print(numbers)

#  what type is it?
print(type(numbers))

#  can we actually see the sequence?  yes, but we have to use list.
print(list(numbers))
range(0, 5)
<class 'range'>
[0, 1, 2, 3, 4]

So… All of That Meant…

Quick Summary So Far…

We've learned two new built in functions

Range Life…

Range

range() returns a range object, an arithmetic sequence of numbers.

Range (Continued)

(continued from previous slide)

Some Other Things You Should Know About Range

Guess That Series of Numbers

Given the following calls to the range function, what is the start, stop, and step? What is the resulting arithmetic sequence? →

range(3)
#  start:0, end:3, step:1
0, 1, 2
range(10, 16)
#  start:10, end:16, step:1
10, 11, 12, 13, 14, 15
range(-2, 3)
#  start:-2, end:3, step:1
-2, -1, 0, 1, 2

Guess That Series of Numbers

What is the start, stop, and step? What is the resulting arithmetic sequence? →

range(200, 501, 100)
#  start:200, end:501, step:100
200, 300, 400, 500
range(0, 10, 5)
#  start:0, end:10, step: 5
0, 5
range(5, -11, -5)
#  start:5, end:-11, step:-5
5, 0, -5, -10

For Loop Examples

And Now, Back to For Loops

for whatevs in range(1, 4):
		print(str(whatevs) + " Mississippi")
1 Mississippi
2 Mississippi
3 Mississippi

Let's Take a Closer Look

for whatevs in range(1, 4):
		print(str(whatevs) + " Mississippi")

Going over this step-by-step, what is the value of whatevs, and what is printed? →

Another For Loop Example

for num in range(6, 13, 3):
	result = num * num
	print(str(num) + " squared is " + str(result))

And… step-by-step, that's: →

And by using pythontutor.com

How About Another?

What is the output of this code? Let's read through it line-by-line to figure it out. →

for whatevs in range(1, 4):
	if whatevs == 2:
		print("let's skip this one")
	else:
		print(str(whatevs) + " Mississippi")
1 Mississippi
let's skip this one
3 Mississippi

And again, step-by-step

For Loop Exercises

Some Quick Excercises

Let's do these together →

Fizz Buzz

FizzBuzz Output

1
2
Fizz
4
Buzz
Fizz
.
.
14
FizzBuzz
16
.
.
98
Fizz
Buzz

FizzBuzz Solution

for i in range(1, 101):
	if i % 3 == 0 and i % 5 == 0:
		print("FizzBuzz")
	elif i % 3 == 0:
		print("Fizz")
	elif i % 5 == 0:
		print("Buzz")
	else:
		print(i)

Using an Accumulator Variable

Accumulator Variable

An accumulator variable is a variable used to keep the running total of a repeated calculation or operation that's within a loop:

Some examples include:

Summing Numbers

total = 0
for i in range(1, 101):
	total = total + i
print(total)

Counting Dice For Loop

Roll a die 1000 times; count how many times a one is rolled! Print out the result. Use a for loop.→

import random
ones = 0
for count in range(1, 1000):
	roll = random.randint(1, 6)
	if roll == 1:
		ones = ones + 1
print(str(ones) + " of 1000 rolls were ones")

Counting Dice While Loop

Roll a die 1000 times; count how many times a one is rolled! Print out the result. Use a while loop.→

import random
ones = 0
count = 0
while count < 1000:
	roll = random.randint(1, 6)
	if roll == 1:
		ones = ones + 1
	count = count + 1
print(str(ones) + " of 1000 rolls were ones")

Using User Input to Influence Number of Repetitions

Controlling a For Loop With User Input

We can base the number of repetitions that a for loop goes through by asking the user to enter a value.

Let's check out a programming problem where this idea might come in handy…

A Ladder

Make me a ladder!

How tall do you want this ladder to be?
> 3

 ========
 |      |
 ========
 |      |
 ========
 |      |

A Ladder Implementation

(Or… two implementations, really)

height = int(input('How tall do you want this ladder to be?'))

for i in range(height):
	print('========\n|      |')

#  or... just multiply instead of using the for loop
#  print(height * '========\n|      |')