1 of 10

CS 149

Professor: Alvin Chao

For loops

2 of 10

Counting Loops

  • Common to write loops that execute some fixed number of times:

frame = 1

scores = [9, 7, 8, 5, 4, 9, 8, 6, 2, 1]

total = 0

for i in range(0,len(scores)):

// Get bowling scores for this frame.

// Do some fancy calculations.

// Show a turkey animation if needed...

total += scores[i]

3 of 10

For Loops pre-test

  • For loops provide more concise syntax for the same logic:

frame = 1

scores = [9, 7, 8, 5, 4, 9, 8, 6, 2, 1]

total = 0

for i in range(0,len(scores)):

// Get bowling scores for this frame.

// Do some fancy calculations.

// Show a turkey animation if needed...

total += scores[i]

4 of 10

Loops and Scope

  • Notice the subtle difference between these loops

for i in range(0,9):

print(i)

for i in “0123456789”:

print(i)

5 of 10

Problem #1

  • What will be printed when this code executes?

for i in range(0, 3):

print(i)

6 of 10

Problem #1

  • What will be printed when this code executes?

for i in range(0, 3):

print(i)

0

1

2

7 of 10

Naming Index Variables

def count_x(word):

count = 0

for i in range(len(word)):

if (word[i] == 'X'):

count += 1

return count

8 of 10

Naming Index Variables

  • Why “i” and “j”? Aren't we supposed to pick meaningful names?

  • Yes, but i and j are a widely used conventions for cases where:
    • We are only using the variable to keep track of how many times the loop has executed
    • We are using the variables to “i”ndex into some sequence...

9 of 10

Coding Bat

https://codingbat.com/python

List-1 problems: first_last6, common_end, sum3, reverse3

Setup an account with your dukes.jmu.edu email and link the Teacher Share in preferences to my chaoaj@jmu.edu account

10 of 10

  • Acknowledgements

Parts of this activity are based on materials developed by Chris Mayfield and Nathan Sprague.

</end>