Code up your digital turtle mascot and watch him dash around the screen in this simple Python coding activity.
If we put the numbers 1-100 in a hat and draw them out one by one, what kind of sequence could we get? What if we shuffle the numbers back in once they’ve been picked?
Randomness is one of those tricky concept that pops up everywhere in computer science. It looks simple on the outside, but it quickly gets convoluted as you wander farther in it. To get a clear picture of what randomness looks like, we’re going to use Python and Turtle!
1. Navigate to www.repl.it
2. In the ‘Search for a Language’ bar, type ‘python’ and select the option ‘Python (with Turtle)’. Make sure that Turtle is included!
3. In the code editor on the left-hand side, write:
from turtle import Turtle, Screen from random import randint
These two lines allow us to access modules of code written by professionals. Complicated tasks — like generating random numbers — can now be done in one line instead of 100!
Functions and objects
The goal of functions is to hide pesky programming details and leave developers free to focus on the logic of their code. As a real-life example, picture chatting with your best friend. Are you thinking about the movement of your tongue, lips, or throat? Probably not; that stuff happens automatically! Your brain is essentially passing chosen words to a ‘talk’ function that takes care of coordinating your body parts into pronouncing those words correctly.
In Python, you can recognize functions because they end with brackets: (). Inside those brackets are the function parameters: the important information that directs the behaviour of the function.
An object is a collection of data and functions that can be accessed through a single variable. Picture this: a person is a collection of arms, legs, thoughts, and feelings, and each one is referenced by a unique name. Objects make it easier to organize and understand code. For example, it’s a lot nicer to say ‘Katie’s arm’ than ‘Arm #345567’.
An object is created using a constructor, a special function whose name starts with a capital letter. In this program, we have two objects: a Screen and a Turtle.
Add the following code to your left-hand editor:
playground = Screen() playground.setup(500, 500) playground.setworldcoordinates(0, 0, 500, 500)
This code sets up a square digital playground that our turtle can explore. Imagine that the screen object is separated into a grid, like a chess board. Each square is defined by two numbers: a row and a column. So if we pick two numbers out of a hat, we can use them to pinpoint a specific square on the grid. This method of “mapping” numbers to squares is called a coordinate system. Ours works like this:
The bottom-left corner is (0, 0). The higher the first number gets, the more we travel to the right. The higher the second number gets, the more we travel upwards, all the way to the top-right corner, which maxes out at (500, 500).
Add the following code to your left-hand editor:
thomas = Turtle() thomas.shape('turtle') thomas.stamp()
The first line creates our turtle object, and the second changes its image from a small arrow to a picture of a turtle. The “stamp” function in the third line leaves an impression of the turtle image on the screen, allowing us to tell exactly where Thomas has been. Now, finish off the program with the following code:
while True: num1 = randint(0, 500) num2 = randint(0, 500) thomas.goto(num1, num2) thomas.stamp()
A while loop keeps running the code inside until its condition becomes false. For example, the statement ‘while cake not eaten’ loops until there’s no cake left, and ‘while skittles < 10’ continues until the program has 10 or more skittles. In our program, we want the loop to run forever, so our chosen condition is ‘True’. This is normally a big no-no in programming. It works in this scenario because we have a button that can stop the program by hand. Still — don’t tell the coding police! Shh! Inside the while loop, we start by choosing two random numbers between 0 and 500. Next, we tell Thomas to make a beeline for these coordinates. The moment he arrives, he leaves a stamp. These actions are repeated until we choose to end the program.
Complete code listing
from turtle import Turtle, Screen from random import randint playground = Screen() playground.setup(500, 500) playground.setworldcoordinates(0, 0, 500, 500) thomas = Turtle() thomas.shape('turtle') thomas.stamp() while True: num1 = randint(0, 500) num2 = randint(0, 500) thomas.goto(num1, num2) thomas.stamp()
- Check that each open bracket has a closing bracket
- Check that ‘True’, ‘Turtle()’, and ‘Screen()’ all start with capital letters
- Make sure that you’ve imported your packages
- Check that the four lines inside the while loop all start with a tab or two spaces. Don’t mix tabs and spaces or you’ll get an error!
You’re all ready to go! Hit the ‘run’ button at the top of the screen!
As Thomas zooms around from right to left and top to bottom, we get an exact record of the all the random numbers “picked out of a hat”. Do a few trial runs, then leave the program running for 10-15 minutes while you go do something else. What do you see when you come back?
The picture tells us which numbers were picked, but it doesn’t tell us anything about the order. Can you think of a way to add this into the code? What if you added colours?
Intro to Python with Turtle
Other activities with Python and Turtle:
Article from “Wired” about Visualizing Randomness:
Also In The June 2018 Issue
Create a fun adventure game with sprites using a retro fantasy computer.
Hide information in plain sight using a clever code and a good book.
Logic puzzles help develop reasoning skills useful for programming, computer science, and anything you might do.
Find perfect and fun gifts for your loved ones that teach STEAM concepts and skills.
From light-up bow-ties to conductive thread, you’ll be the life of the party with this STEAM-inspired gear.
A free online test service reveals how much personal data your web browser is giving away.
Add more tools to your command line arsenal, including running mini-scripts and making backup copies.
Use switches to take your robotic creations to the next level.
Create the American flag in SketchUp using this detailed tutorial.
From lasers to supernovas, Berboucha is making science communication a priority.
Code can always be improved. Check out these tips to make you the best programmer you can be!
It’s a programming language unlike any you’ve seen before. Check out this symbolic system designed for mathematical calculations.
It’s a game that’s obsessing the world. Harmful, or a potential gateway to new skills?
Some fun Python code that introduces you to the arcane world of event handling.
New, improved, faster, and sleeker - it’s Scratch 3, your new favourite block language!
Learn about the brilliant algorithm behind all of your GPS devices.
It’s free, comprehensive, and available on-the-go. This cool app helps you master Python faster than ever before.
Open up whole new worlds to explore through these interesting, diverse add-ons.
Links from the bottom of all the October 2018 articles, collected in one place for you to print, share, or bookmark.
Interesting stories about computer science, software programming, and technology for October 2018.