Python – Loops and Iteration

14
Python – Loops and Iteration Lecture03

description

Python – Loops and Iteration. Lecture03. Sums. What’s the sums of the numbers from 1 to 10?. sum = 0 sum = sum + 1 sum = sum + 2 sum = sum + 3 sum = sum + 4 sum = sum + 5 sum = sum + 6 sum = sum + 7 sum = sum + 8 sum = sum + 9 sum = sum + 10 - PowerPoint PPT Presentation

Transcript of Python – Loops and Iteration

Page 1: Python – Loops and Iteration

Python – Loops and IterationLecture03

Page 2: Python – Loops and Iteration

SumsWhat’s the sums of the numbers from 1 to 10?

sum = 0sum = sum + 1sum = sum + 2sum = sum + 3sum = sum + 4sum = sum + 5sum = sum + 6sum = sum + 7sum = sum + 8sum = sum + 9sum = sum + 10 print sum

Page 3: Python – Loops and Iteration

SumsWhat’s the sums of the numbers from 1 to 1000?

sum = 0 for i in range(1001):   sum += i print sum

Page 4: Python – Loops and Iteration

range()The range function generates an array up to its argument.

range(start)range(start, stop)range(start, stop, increment)

Page 5: Python – Loops and Iteration

Operator - in

array = range(6) if 5 in array:   print "YEP!" for item in array:   print "YUP!"

Page 6: Python – Loops and Iteration

For LoopsWhen you know how many times you want to loop

for x in range(1,10):   pass

Page 7: Python – Loops and Iteration

While LoopsFor when you’re not sure how many times you want to iterate.

while (condition):   pass

Page 8: Python – Loops and Iteration

Keywords for Iteration

breakcontinuepass

Page 9: Python – Loops and Iteration

Break

sum = 0 for i in range(11):   sum += 1   if i == 5:      break   print sum

Page 10: Python – Loops and Iteration

Continue

sum = 0 for i in range(11):   sum += 1   if i == 5:      continue   print sum

Page 11: Python – Loops and Iteration

Pass

sum = 0 for i in range(11):   sum += 1   if i == 5:      pass   print sum

Page 12: Python – Loops and Iteration

Nesting LoopsLoops can contain loops:

sum = 0 for i in range(10):   for j in range(10):      sum += 1 print sum

Page 13: Python – Loops and Iteration

Printing a SquareIt can be accomplished the long way…

print "* * * * * * * * * *"print "* * * * * * * * * *"print "* * * * * * * * * *"print "* * * * * * * * * *"print "* * * * * * * * * *"print "* * * * * * * * * *"print "* * * * * * * * * *"print "* * * * * * * * * *"print "* * * * * * * * * *"print "* * * * * * * * * *"

Page 14: Python – Loops and Iteration

Square – Deluxe Edition

for row in range(10):   for column in range(10):      print "*",   print ""