442 likes | 989 Views
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
E N D
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 printsum
Sums What’s the sums of the numbers from 1 to 1000? sum = 0 for i inrange(1001): sum += i printsum
range() The range function generates an array up to its argument. range(start) range(start, stop) range(start, stop, increment)
Operator - in array = range(6) if5inarray: print"YEP!" for item inarray: print"YUP!"
For Loops When you know how many times you want to loop for x inrange(1,10): pass
While Loops For when you’re not sure how many times you want to iterate. while (condition): pass
Keywords for Iteration break continue pass
Break sum = 0 foriinrange(11): sum += 1 ifi == 5: break printsum
Continue sum = 0 foriinrange(11): sum += 1 ifi == 5: continue printsum
Pass sum = 0 foriinrange(11): sum += 1 ifi == 5: pass printsum
Nesting Loops Loops can contain loops: sum = 0 foriinrange(10): for j inrange(10): sum += 1 printsum
Printing a Square It can be accomplished the long way… print"* * * * * * * * * *" print"* * * * * * * * * *" print"* * * * * * * * * *" print"* * * * * * * * * *" print"* * * * * * * * * *" print"* * * * * * * * * *" print"* * * * * * * * * *" print"* * * * * * * * * *" print"* * * * * * * * * *" print"* * * * * * * * * *"
Square – Deluxe Edition for row inrange(10): for column inrange(10): print"*", print""