Lec14

[Pages:28]CSE 115

Introduction to Computer Science I

Road map

Review

exercise from last time

code template / pattern

exercise

lists / arrays revisited

exercise

range examples

range(5) consists of the values 0, 1, 2, 3, and 4.

range(3,7) consists of the values 3, 4, 5, and 6.

range(3,7,2) consists of the values 3 and 5.

for



for var in sequence: statement0 statement1 ... statementN

A range is one of many kinds of sequences in Python.

Various JS loops

JavaScript/Python comparison

for statement

for..in loops over elements

function printSequence_0(seq) { for (var i = 0; i < seq.length; i = i + 1){ console.log(seq[i]); }

}

def printSequence(seq): for x in seq: print(x)

printSequence_0(['a', 'b', 'c']);

printSequence(['a', 'b', 'c'])

a

a

b

b

c

c

Various JS loops

JavaScript/Python comparison

for..in loops over indices

function printSequence_1(seq) { for (var i in seq) { console.log(seq[i]); }

}

printSequence_1(['a', 'b', 'c']);

a b c

for..in loops over elements

def printSequence(seq): for x in seq: print(x)

printSequence(['a', 'b', 'c'])

a b c

Various JS loops

JavaScript/Python comparison

for..in loops over indices

function printSequence_2(seq) { for (var i in seq) { console.log(i); }

}

printSequence_2(['a', 'b', 'c']);

0 1 2

for..in loops over elements

def printSequence(seq): for x in seq: print(x)

printSequence(['a', 'b', 'c'])

a b c

Various JS loops

JavaScript/Python comparison

for..of has similar behavior

function printSequence_3(seq) { for (var i of seq) { console.log(i); }

}

printSequence_3(['a', 'b', 'c']);

a b c

def printSequence(seq): for x in seq: print(x)

printSequence(['a', 'b', 'c'])

a b c

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download