GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing opentechschool.github.io — Loops — Introduction to Programming with Python Loops¶Introduction¶Something you might have noticed: our programs often feature repetition. Python has a powerful concept it makes use of called looping (jargon: iteration), which we can use to cut out our reptitive code! For now, try this easy example: for name in "John", "Sam", "Jill": print("Hello " + name) This is incredibly helpful if we want to do something multiple times — say, drawing the individual border lines of a shape — but only want to write that action once. Here’s another version of a loop: for i in range(10): print(i) Notice how we write only one line of code using The You can also loop over elements of your choice: total = 0 for i in 5, 7, 11, 13: print(i) total = total + i print(total) Write this example out and run it with python, to check it works how you might expect. Note Notice how above, the lines of code that are looped, are the ones that
are indented. This is an important concept in Python - that’s how it
knows which lines should be used in the Sometimes you want to repeat some code a number of times, but don’t care about
the value of the for _ in range(10): print("Hello!") You may or may not be wondering about the variable for drink in list_of_beverages: print("Would you like a " + drink + "?") This is immediately clearer to understand than if we had used Drawing a dashed line¶Exercise¶Draw a dashed line. You can move the turtle without the turtle drawing its
movement by using the
Solution¶for i in range(10): turtle.forward(15) turtle.penup() turtle.forward(5) turtle.pendown() Bonus¶Can you make the dashes become larger as the line progresses?
Hint Feeling lost? Inspect for i in range(10): print(i) # write more code here Can you utilize Comments¶In the example above, the line that starts with a Comments can also go at the end of a line, like this: turtle.left(20) # tilt our next square slightly More Efficient Squares¶Exercise¶The squares we were drawing at the start of this tutorial had a lot of repeated lines of code. Can you write out a square drawing program in fewer lines by utilizing loops? Solution¶for _ in range(4): turtle.forward(100) turtle.left(90) Bonus¶Try nesting loops, by putting one right under (inside) the other, with some drawing code that’s inside both. Here’s what it can look like: for ...:
for ...:
# drawing code inside the inner loop goes here
...
# you can put some code here to move
# around after!
...
Replace the |
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |