The purpose of a for loop is to repeat one or more lines of code a certain number of times. Here's an example:
First we're going to use a turtle to draw something without using any loops:
from turtle import Turtle
chewbacca = Turtle()
The first line tells Python that we want to use turtles, and the second makes a new turtle. I've named my turtle chewbacca
, but you can give yours whatever name you choose!
chewbacca.forward(100)
chewbacca.right(120)
Then, we tell chewbacca
to move forward by 100 steps, and then turn right by 120 degrees. A circle has 360 degrees, so 120 degrees means to turn 1/3 of the way around.
for i in range(3):
chewbacca.forward(100)
chewbacca.right(120)
This is the same as the two lines above, but now we tell Python that we want those 2 lines to be looped over 3 times. This is a for loop!
points = 3
for i in range(points):
chewbacca.forward(100)
chewbacca.right(360/points)
This does the same thing, except now we've made a variable called points
. Then we repeat the move and turn steps as many times as points
is set to. We also adjust the size of our turn, so that we end up turning a total of 360 degrees.
points = 7
Try running this chunk of code yourself, and see what happens if you change points
to different numbers.
points = 7
for i in range(points):
chewbacca.forward(100)
chewbacca.right(180 - (180/points))
We can make our drawing a little fancier by changing the angle we turn by. The extra brackets around 180/points
tell Python that it should divide before subtracting from 180.
This will work with any odd number as long as it's 5 or more.
There's one more thing we can do with for loops! In the examples above we have a variable called i
that we never used. Behind the scenes, Python is changing the variable i
to a different number on each run of the loop. But, that variable can be something besides just a number!
for color in ['red', 'blue', 'green', 'purple', 'cyan', 'orange', 'magenta']:
chewbacca.color(color)
chewbacca.forward(100)
chewbacca.right(180 - (180/7))
Here, the variable color
changes its value each time through the loop. We use that variable to set the color when we run chewbacca.color(color)
.
The stuff in the square brackets is called a list. We can construct a list by hand like in this example, or using the range()
function like we did above.
Can you put a for loop inside of another for loop? Yup!!!
for i in range(3):
for color in ['red', 'blue', 'green', 'purple', 'cyan', 'orange', 'magenta']:
chewbacca.color(color)
chewbacca.forward(100)
chewbacca.right(180 - (180/7))
chewbacca.right(360/3)
Here, the inner for loop tells us to draw 7 lines to make a star, and the outer for loop for i in range(3)
tells us to repeat the star 3 times.
Pay attention to how the lines are indented, since this is how we tell Python what's part of the inner loop and what's part of the outer loop!
Want more details on for loops? Check out this page!
Want to try practicing for loops? Head to the mini-challenges page and try the "For loop drawing challenge" or the "Baby shark challenge".
Something we might want to do when making a game is to keep track of the user's data. We've already seen how to keep track of the current score using a variable, but maybe we want to keep the data more permanently so we can track high scores. Here we're going to talk about how to output data to something called a CSV file.
For this activity, we'll be working with this Pokemon Snake game in Trinket.
The first thing we need to do is make a file we can write our data to. To do that, we use the command open()
.
file = open('my_file.csv', 'a')
'a' stands for 'append', meaning that if the file already exists then we'll add onto the end of it instead of overwriting it. You only need to run this step once, probably near the very beginning of your code!
Now that we have a file, how do we add data to it?
file.write('The data I want to write to my file').
file
here is whatever you named your file when you opened it. It doesn't need to be the word 'file'!
There are a ton of different ways we could choose to record the data from our game. In this case, we're going to add a line to our file each time we catch a Pokemon. We'll record which Pokemon we caught, the current time, and the X and Y coordinates of the player (how far left/right and how far up/down). Each item is separated by a comma (CSV stands for 'comma separated values').
To get the current time, you can write:
import time
time.time()
The import time
step only needs to happen once in your whole program, so stick it at the top with the other import steps. time.time()
is a function that will return a number representing the current time.
Another thing you'll need to know to record your data is how to make a line break. All you need to do is type '\n'
where you want to line break to appear. If we write:
file = open('my_file.csv', 'a')
file.write('Baby shark,')
file.write('doo doo doo doo doo doo')
file.write('Baby shark,')
file.write('doo doo doo doo doo doo')
file.write('Baby shark,')
file.write('doo doo doo doo doo doo')
file.write('Baby shark!')
...we get this:
Uh oh!
But if we add line breaks...
file = open('my_file.csv', 'a')
file.write('Baby shark,')
file.write('doo doo doo doo doo doo' + '\n')
file.write('Baby shark,')
file.write('doo doo doo doo doo doo' + '\n')
file.write('Baby shark,')
file.write('doo doo doo doo doo doo' + '\n')
file.write('Baby shark!')
We get something that makes a lot more sense:
Hints:
score += 1
to increase the score, and put your file output step right after!pokemon
stores the name of the pokemon we're currently checking the position of.pos
stores our current position. You can get the x or y coordinate by typing str(pos[0])
or str(pos[1])
.If we want to create a new file every time the program runs, instead of 'my_file.csv' we can name our file based on the exact time we created it:
str(time.time()) + '.csv'
It's a good idea to wait until the end to add this feature, since otherwise you'll accumulate a lot of CSV files you might not want while you're troubleshooting!
See if you can get Trinket to record your Pokemon-catching events in a new file for each game you play. If you have extra time, think about what other information you might want to record in addition and add that to your code.
Once you have data recorded from a few times playing the game, you can try plotting it! You can download all your CSV files from Trinket by clicking the menu on the left and then "Download". Then in Kaggle, click "File" and "Add or upload dataset" to add your data. We also have some sample data pre-recorded that you can use!
Want more details on writing to and reading from files? Check out this page!