# Using For Loops # http://10.c1021.fun ### David Rossiter, Gibson Lam and Sung Kim ## Outcomes ### After completing this presentation, you are expected to be able to: 1. Use the range command to make a range of numbers 1. Write loops using the `for` command ## Typical loops * `n` iterations * `print` 0 to 9 num = 0 while num < 10: print (num) num = num + 1 ## Writing Loops Using For * Previously, we have discussed the use of while loops to do things repeatedly in Python * In this presentation, we will look at another way of doing loops, using for loops * Using a for loop: * perform some actions a particular number of times, or: * loop through a set of data, performing the same actions on every item in the set for num in range (1, 10): print(num) ## For Loops ``` for item in a list of items (range (1, 10)): . . .statement(s). . . ``` # Sum from 1-9 sum = 0 for i in range (1, 10): sum = sum + i print("Sum", sum) ## Do n times * `range(0, 4)` or `range(4)` for i in range(4): print("OK") ## Drawing a Square Using a For Loop ![image](https://user-images.githubusercontent.com/901975/65469362-c18b3880-de99-11e9-82a7-78e9b719cff0.png) import turtle for i in range(4): turtle.forward(100) turtle.right(90) ## Drawing a Star Shape Using a For Loop ![image](https://user-images.githubusercontent.com/901975/65469507-44ac8e80-de9a-11e9-9614-1b37f8126269.png) import turtle for i in range(?): turtle.forward(100) turtle.right(144) ## start, end, step * `range(0, 100, 2)` * `range(99, 0, -2)` for i in range(0, 10, 2): print("I", i) print("----") for j in range(9, 0, -2): print("J", j) ## Spiral Patterns Created Using Turtle * In the following two examples, patterns are created using for loops and some cleverly chosen numbers * The turtle draws ‘squares’ using a slightly different angle and a slightly different length for each side ![image](https://user-images.githubusercontent.com/901975/65469663-c8667b00-de9a-11e9-9b51-80dc35df6be2.png) * Start with simple sqares ![image](https://user-images.githubusercontent.com/901975/65469893-a4f00000-de9b-11e9-96c4-7ca650eb00dd.png) ![image](https://user-images.githubusercontent.com/901975/65469996-06b06a00-de9c-11e9-8a80-d75c7624ef84.png) * for loop: 5, 10, 15, ... * `range (0, 200, 5)` import turtle turtle.speed(10) for i in range(0, 200, 5): turtle.forward(i) turtle.right(90) ## Spiral Patterns Created Using Turtle ![image](https://user-images.githubusercontent.com/901975/65470153-98b87280-de9c-11e9-815c-7650543cadac.png) import turtle turtle.speed(10) for i in range(0, 300, 3): turtle.forward(i) turtle.right(91) ## Flower Spiral Patterns ![image](https://user-images.githubusercontent.com/901975/65471046-48431400-dea0-11e9-9495-5164d77b5654.png) ![image](https://user-images.githubusercontent.com/901975/65471077-66107900-dea0-11e9-96a2-4461e12a8bb1.png) ![image](https://user-images.githubusercontent.com/901975/65471098-7cb6d000-dea0-11e9-931c-282930554805.png) ![image](https://user-images.githubusercontent.com/901975/65471595-4a0dd700-dea2-11e9-85c8-baf14ec16908.png) import turtle turtle.speed(0) turtle.color('purple') for i in range(0, 400, 2): turtle.forward(i) turtle.right(89) for i in range(401, 0, -2): turtle.forward(i) turtle.right(89) ## Nested for loops * for loops in side for loops for i in range(10): for j in range (10): print("I & J", i, j) ## Multiplication table ![image](https://user-images.githubusercontent.com/901975/65472037-29df1780-dea4-11e9-8d74-6f8fa5b50425.png) for i in range(2, 10): for j in range (2, 10): print(i, "X", j, "=", i * j) print("---") ## The Flower Pattern Created By Hexagons ![image](https://user-images.githubusercontent.com/901975/65471863-724a0580-dea3-11e9-971d-ec9525c26a10.png) ![image](https://user-images.githubusercontent.com/901975/65472375-c524bc80-dea5-11e9-86fc-4bcf239e385a.png) import turtle for _ in range(6): turtle.forward(100) turtle.right(60) import turtle turtle.speed(0) for _ in range(10): for _ in range(6): turtle.forward(100) turtle.right(60) turtle.right(36) ## Drawing a Pyramid of Dots * Simple dots #three dots import turtle size = 5 turtle.up() for j in range(3): turtle.dot(size) turtle.forward(size*3) turtle.hideturtle() ![image](https://user-images.githubusercontent.com/901975/65472922-49783f00-dea8-11e9-9c82-21ca824236a3.png) import turtle size = 5 turtle.up() for i in range(7): for j in range(i): turtle.dot(size) turtle.forward(size*3) turtle.goto(0, i*size*3) turtle.hideturtle() ![image](https://user-images.githubusercontent.com/901975/65472988-82181880-dea8-11e9-9584-fb383f524b8b.png) #three dots import turtle size = 5 turtle.up() for i in range(7): for j in range(i): turtle.dot(size) turtle.forward(size*3) turtle.goto(0, -i*size*3) turtle.hideturtle() # http://10.c1021.fun ![image](https://user-images.githubusercontent.com/901975/65473115-0c607c80-dea9-11e9-9d25-91da842767c8.png) import turtle size = 5 turtle.up() for i in range(7): for j in range(i): turtle.dot(size) turtle.forward(size*3) turtle.goto(-i*size*3, -i*size*3) turtle.hideturtle() import turtle size = 5 turtle.up() for i in range(7): for j in range(i): turtle.dot(size) turtle.forward(size*3) turtle.goto(-i*size*3/2, -i*size*3) turtle.hideturtle() # Print with end for i in range(5): print(i) for i in range(5): print(i, end=":") for i in range(5): print(i, end=" OK ") print("") for i in range(5): print("*", end="") ![image](https://user-images.githubusercontent.com/901975/65555061-fa8ce100-df5d-11e9-8340-d7ffe86590bf.png) # Five star for i in range(1, 6): for j in range(i): print ('* ', end="") print('') ![image](https://user-images.githubusercontent.com/901975/65555093-16908280-df5e-11e9-99f4-c9a0051821aa.png) n=5; for i in range(n,0,-1): for j in range(i): print('* ', end="") print('') ![image](https://user-images.githubusercontent.com/901975/65555128-358f1480-df5e-11e9-92df-8d71f08c13df.png) n=5; for i in range(n): for j in range(i): print ('* ', end="") print('') for i in range(n,0,-1): for j in range(i): print('* ', end="") print('') # Can you do with one loop? for i in range(11): for j in range(i): print ('* ', end="") print('') # Can you do with one loop? for i in range(11): jj = i if i>5: jj = 10 - i for j in range(jj): print ('* ', end="") print('') ## Python magic: str * input print("hi" * 5) print("* " * 3) ``` # # # # # # # # # # # # # # # ``` # Five star for i in range(1, 6): print ('# ' * i) ![image](https://user-images.githubusercontent.com/901975/65555572-95d28600-df5f-11e9-9714-9321214a9356.png) # Seven pyramind for i in range(8): print(" " * i, end = "") for j in range(i): print ("* ", end="") print('') # Seven pyramind for i in range(8): print(" " * (7-i), end = "") for j in range(i): print ("* ", end="") print('') # Seven pyramind with str * int for i in range(8): print(" " * (7-i), end = "") print ("* " * i) # Lists and Tuples * After completing this presentation, you are expected to be able to: * Manage a collection of things using a list or a tuple in Python * Explain the major difference between lists and tuples * Create a two dimensional structure using lists or tuples ## Dealing with scores * Three student scores: 91, 80, 99. * print their scores * find the max and min scores s1 = 91 s2 = 80 s3 = 99 print(s1, s2, s3) # Find max # Find min ## 7 Student Scores * 92, 96, 89, 78, 99, 88, 100 * print, find max, find min * sorting * change it to letter grade * ... ![image](https://d24fkeqntp1r7r.cloudfront.net/wp-content/uploads/2019/04/30075227/shutterstock_1010935825-2.jpg) score = [92, 96, 89, 78, 99, 88, 100] print("length", len(score)) print("score 0", score[0]) print("score 3", score[3]) print("score 8", score[8]) score = [92, 96, 89, 78, 99, 88, 100] length = len(score) for i in range(0, length): print(score[i]) # Find MAX score = [92, 96, 89, 78, 99, 88, 100] length = len(score) # put a small number max = 0 for i in range(0, length): if score[i] > max: max = score[i] print("Max score is", max) http://pythontutor.com/iframe-embed.html#code=%23%20Find%20MAX%0Ascore%20%3D%20%5B92,%2096,%2089,%2078,%2099,%2088,%20100%5D%0Alength%20%3D%20len%28score%29%0A%0A%23%20put%20a%20small%20number%0Amax%20%3D%200%0A%0Afor%20i%20in%20range%280,%20length%29%3A%0A%20%20if%20score%5Bi%5D%20%3E%20max%3A%0A%20%20%20%20max%20%3D%20score%5Bi%5D%0A%0Aprint%28%22Max%20score%20is%22,%20max%29&codeDivHeight=400&codeDivWidth=350&cumulative=false&curInstr=0&heapPrimitives=nevernest&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false score = [92, 96, 89, 78, 99, 88, 100] for s in score: print(s) # Find MAX score = [92, 96, 89, 78, 99, 88, 100] # put a small number max = 0 for s in score: if s > max: max = s print("Max score is", max) # Find Min score = [92, 96, 89, 78, 99, 88, 100] for s in score: print("min score is", ) ## List Exercises * Find avg * Find median value * If there is an even number of observations, then there is no single middle value; the median is then usually defined to be the mean of the two middle values. * More list exercises at https://www.w3resource.com/python-exercises/list/ ## The Range Command * The range command creates a range of numbers * Make a range of numbers between 1 and 5 using the following code: `range(1, 6)`` * Returns a range of numbers which includes 1, 2, 3, 4 and 5 print(list(range(1, 6))) print(list(range(5, 10))) # 5 to 9 (5 inclusive, but 9 exclusive) print(list(range(1, 11))) # 1 to 11 (1 inclusive, but 11 exclusive) print("default start is 0") print(list(range(10))) print("Step size is 2") print(list(range(0, 10, 2))) print(list(range(1, 10, 2))) print("Step size is 3") print(list(range(0, 10, 3))) ## More examples print(list(range(-1,-10,-2))) print(list(range(10, 1))) print(list(range(-10, 1,-1))) print(list(range(-10, 1, 1))) print(list(range(-10, 1, 0))) ## For Loops ``` for item in a list of items : . . .statement(s). . . ``` * You need to give a list of items to a for loop * This is where the range command is commonly used * prints out a list of four numbers: * The end value means a space is put at the end of the number when it is printed, instead of moving to the next line `print(i, end=" ")` for i in range(4): print(i, end=" ") ## Excercises * Print odd nemers from 0 to 100 * Print numbers from 0 to 100 but not multiple of 3 * 0 1 4 5 7 8 10 11 13 ... for i in range( ): print(i, end=" ") ## Using a ‘Fixed’ List in a For Loop * For loop is an iterator or any given list, `[1, 4, -4, 2]` * We can make a string list, `["apple", "banana", "cherry"]` for i in [1, 4, -4, 2]: print(i, end=" ") fruits = ["apple", "banana", "cherry"] for fruit in fruits: print("I like", fruit) ## Nested for loops # Example from w3school adj = ["red", "big", "tasty"] fruits = ["apple", "banana", "cherry"] for a in adj: for f in fruits: print(a, f) ## Using a String in a For Loop * A string will be changed into a list of letters automatically when it is used in a for loop * String "Wild hair" becomes
 `["W","i","l","d"," ","h","a","i","r"]` for i in "This is Sung!": print(i, end="*") ## Excercise * Replace `s` to `x` for i in "This is Sung!": if i is 's': print('x', end="") else: print(i, end="") ## More examples * https://www.geeksforgeeks.org/python-list/ ## Break and Continue * https://www.programiz.com/python-programming/break-continue ![image](https://user-images.githubusercontent.com/901975/65563406-0d161300-df7c-11e9-89d7-e79f41e405b7.png) ![image](https://user-images.githubusercontent.com/901975/65563319-c6c0b400-df7b-11e9-8b9d-a3ca5ade09f2.png) ![iamge](https://cdn.programiz.com/sites/tutorial2program/files/how-break-statement-works.jpg) # Use of break statement inside loop for s in "lovesung": if s == 's': break print(s) print("The end") ![image](https://cdn.programiz.com/sites/tutorial2program/files/how-continue-statment-works.jpg) # Use of continue statement inside loop for s in "lovesung": if s == 's': continue print(s) print("The end") # Prime using for sum = 0 for i in range (2, 100): is_prime = True for j in range(3, i): if i%j == 0: is_prime = False if is_prime: print("Prime: ", i) sum = sum + i print("Sum = " , sum) ## More Excercise * Add 1 to 100 * Add even numbers from 10 to 1000 * Add two spaces between words * Reverse string * Write prime number sum using `if` and `break` * Rewrite the turtle race using for loops ![image](https://user-images.githubusercontent.com/901975/64474918-ffa40f00-d1ad-11e9-862c-3b5622c8281e.png)