上游充通大 ParisTech SHANGHAI JIAO TONG UNIVERSITY INSTITUT DES SCIENCES ET TECHNOLOGIES PARIS INSTITUTE OF TECHNOLOGY For Loops:A Quick Review We've run into some of these things before! -A series of numbers could be handled by some sort of loop.If there are n numbers,the loop should execute n times. We need a running sum.This will use an accumulator. 6
6 For Loops: A Quick Review • We‟ve run into some of these things before! – A series of numbers could be handled by some sort of loop. If there are n numbers, the loop should execute n times. – We need a running sum. This will use an accumulator
上降充通大 ParisTech SHANGHAI JIAO TONG UNIVERSITY INSTITUT DES SCIENCES ET TECHNOLOGIES PARIS INSTITUTE OF TECHNOLOGY For Loops:A Quick Review Input the count of the numbers,n 。Initialize sum to 0 ·Loop n times Input a number,x -Add x to sum Output average as sum/n 7
7 For Loops: A Quick Review • Input the count of the numbers, n • Initialize sum to 0 • Loop n times – Input a number, x – Add x to sum • Output average as sum/n
上游充通大学 ParisTech SHANGHAI JIAO TONG UNIVERSITY INSTITUT DES SCIENCES ET TECHNOLOGIES PARIS INSTITUTE OF TECHNOLOGY For Loops:A Quick Review averagel.py 井 A program to average a set of numbers 井 Illustrates counted loop with accumulator def main(): n input ("How many numbers do you have?" sum 0.0 for i in range(n): x input ("Enter a number >" sumsum x print "\nThe average of the numbers is",sum/n Note that sum is initialized to 0.0 so that sum/n returns a float! 8
8 For Loops: A Quick Review # average1.py # A program to average a set of numbers # Illustrates counted loop with accumulator def main(): n = input("How many numbers do you have? ") sum = 0.0 for i in range(n): x = input("Enter a number >> ") sum = sum + x print "\nThe average of the numbers is", sum/n • Note that sum is initialized to 0.0 so that sum/n returns a float!
上游充通大 ParisTech SHANGHAI JIAO TONG UNIVERSITY INSTITUT DES SCIENCES ET TECHNOLOGIES PARIS INSTITUTE OF TECHNOLOGY For Loops:A Quick Review How many numbers do you have?5 Enter a number >32 Enter a number >45 Enter a number >34 Enter a number >76 Enter a number >45 The average of the numbers is 46.4 9
9 For Loops: A Quick Review How many numbers do you have? 5 Enter a number >> 32 Enter a number >> 45 Enter a number >> 34 Enter a number >> 76 Enter a number >> 45 The average of the numbers is 46.4
上游充通大学 ParisTech SHANGHAI JIAO TONG UNIVERSITY INSTITUT DES SCIENCES ET TECHNOLOGIES PARIS INSTITUTE OF TECHNOLOGY Remember break and continue? continue for i in[1,2,3,4,5,6,7,8,9,10]: more items in no if i ==5: <sequence> break yes print i <var>=next item <body> for i in[1,2,3,4,5,6,7,8,9,10]: if i==5: continue break print i 10
Remember break and continue? for i in [1,2,3,4,5,6,7,8,9,10]: if i == 5: break print i for i in [1,2,3,4,5,6,7,8,9,10]: if i == 5: continue print i 10