Watch Now This tutorial has a related video course created past the Real Python team. Lookout man it together with the written tutorial to deepen your agreement: Python Turtle for Beginners

When I was a kid, I used to larn Logo, a programming language that involved a turtle that you could movement around the screen with just a few commands. I recollect feeling similar a computer genius as I controlled this little object on my screen, and this was what got me interested in programming in the outset identify. The Python turtle library comes with a similar interactive characteristic that gives new programmers a taste of what it's similar to work with Python.

In this tutorial, you volition:

  • Empathise what the Python turtle library is
  • Learn how to gear up turtle up on your computer
  • Program with the Python turtle library
  • Grasp some important Python concepts and turtle commands
  • Develop a brusque just entertaining game using what you've learned

If you're a beginner to Python, then this tutorial will help yous as you accept your beginning steps into the globe of programming with the assistance of the Python turtle library!

Getting to Know the Python turtle Library

turtle is a pre-installed Python library that enables users to create pictures and shapes by providing them with a virtual canvas. The onscreen pen that you use for drawing is called the turtle and this is what gives the library its name. In short, the Python turtle library helps new programmers get a feel for what programming with Python is like in a fun and interactive style.

turtle is mainly used to introduce children to the world of computers. It's a straightforward nevertheless versatile way to understand the concepts of Python. This makes information technology a great artery for kids to take their offset steps in Python programming. That being said, the Python turtle library is not restricted to little ones alone! It's likewise proved extremely useful for adults who are trying their hands at Python, which makes it groovy for Python beginners.

With the Python turtle library, you can draw and create various types of shapes and images. Here's a sample of the kinds of drawings you can make with turtle:

Python Turtle Initial Demo

Absurd, correct? This is just one of many different drawings you tin can make using the Python turtle library. Most developers use turtle to draw shapes, create designs, and make images. Others use turtle to create mini-games and animations, just similar the one yous saw to a higher place.

Getting Started With turtle

Before y'all continue, there are 2 important things that you'll need to exercise to make the most of this tutorial:

  1. Python Environment: Make certain that you're familiar with your programming environment. Yous can use applications like IDLE or Jupyter Notebook to plan with turtle. However, if you lot're not comfortable with them, then you tin can programme with the REPL, which you lot'll employ in this tutorial.

  2. Python Version: Ensure that y'all take version 3 of Python on your calculator. If not, then you can download it from the Python website. For aid setting things up, check out Python 3 Installation & Setup Guide.

The skillful thing virtually turtle is that it's a built-in library, then you don't demand to install any new packages. All you need to do is import the library into your Python surround, which in this instance would be the REPL. Once you open your REPL application, you can run Python 3 on it by typing the following line of lawmaking:

This calls Python iii into your REPL application and opens up the environment for you.

Before you brainstorm your Python programming, yous need to understand what a library is. In the non-computer earth, a library is a place where different types of books are stored. You can access these books at any time, have whatever data you need from them, and return them to the same identify.

In the estimator world, a library works similarly. Past definition, a library is a fix of important functions and methods that you can access to make your programming easier. The Python turtle library contains all the methods and functions that you'll demand to create your images. To access a Python library, you need to import information technology into your Python environment, like this:

Now that you have turtle in your Python environment, you tin can brainstorm programming with it. turtle is a graphical library, which means you'll need to create a separate window (called the screen) to carry out each drawing command. You can create this screen past initializing a variable for information technology.

In Python, you apply variables to store information that you'll apply later on in your plan. You initialize a variable when you assign a starting value to information technology. Since the value of the variable isn't abiding, information technology tin change several times during the execution of your plan.

Now, to open the turtle screen, you lot initialize a variable for it in the following way:

>>>

                                            >>>                                s                =                turtle                .                getscreen                ()                          

You should see a dissever window open up:

Python Turtle Initial Screen New

This window is chosen the screen. Information technology'due south where you can view the output of your code. The little black triangular shape in the centre of the screen is called the turtle.

Next, you initialize the variable t, which you'll so utilize throughout the program to refer to the turtle:

>>>

                                            >>>                                t                =                turtle                .                Turtle                ()                          

Only like for the screen, y'all can also requite this variable another name like a or Jane or even my_turtle, but in this case, you'll stick with t.

You now have your screen and your turtle. The screen acts as a canvas, while the turtle acts like a pen. You tin can program the turtle to motility around the screen. The turtle has certain changeable characteristics, like size, colour, and speed. It always points in a specific direction, and will move in that direction unless yous tell it otherwise:

  • When it'due south up, it means that no line will be drawn when it moves.
  • When it'southward down, it ways that a line volition be drawn when it moves.

In the next section, you'll explore the different ways of programming with the Python turtle library.

Programming With turtle

The starting time matter you'll larn when information technology comes to programming with the Python turtle library is how to make the turtle movement in the direction you want it to go. Next, you'll acquire how to customize your turtle and its environment. Finally, you'll learn a couple of extra commands with which you can perform some special tasks.

Moving the Turtle

In that location are four directions that a turtle can movement in:

  • Frontwards
  • Backward
  • Left
  • Correct

The turtle moves .forrad() or .backward() in the direction that it's facing. You can alter this management by turning it .left() or .right() by a certain caste. You can attempt each of these commands like and so:

>>>

                                                  >>>                                    t                  .                  correct                  (                  90                  )                  >>>                                    t                  .                  forward                  (                  100                  )                  >>>                                    t                  .                  left                  (                  xc                  )                  >>>                                    t                  .                  astern                  (                  100                  )                              

When y'all run these commands, the turtle will plow correct past 90 degrees, go forward past a hundred units, turn left past xc degrees, and move backward by a hundred units. Yous can encounter how this looks in the image below:

Python Turtle Moving Updated

You can use the shortened versions of these commands as well:

  • t.rt() instead of t.correct()
  • t.fd() instead of t.forward()
  • t.lt() instead of t.left()
  • t.bk() instead of t.astern()

Y'all can also draw a line from your current position to any other arbitrary position on the screen. This is done with the help of coordinates:

Python Turtle Coordinates New

The screen is divided into iv quadrants. The point where the turtle is initially positioned at the beginning of your program is (0,0). This is called Home. To motion the turtle to whatsoever other expanse on the screen, you use .goto() and enter the coordinates like this:

Your output will look like this:

Python Turtle GOTO NEWER

You've drawn a line from your electric current position to the point (100,100) on the screen.

To bring the turtle dorsum to its domicile position, you type the following:

This is like a shortcut command that sends the turtle back to the indicate (0,0). Information technology's quicker than typing t.goto(0,0).

Drawing a Shape

Now that you know the movements of the turtle, y'all tin motility on to making bodily shapes. You lot tin start by cartoon polygons since they all consist of directly lines connected at certain angles. Here's an example that you can try:

>>>

                                                  >>>                                    t                  .                  fd                  (                  100                  )                  >>>                                    t                  .                  rt                  (                  xc                  )                  >>>                                    t                  .                  fd                  (                  100                  )                  >>>                                    t                  .                  rt                  (                  xc                  )                  >>>                                    t                  .                  fd                  (                  100                  )                  >>>                                    t                  .                  rt                  (                  xc                  )                  >>>                                    t                  .                  fd                  (                  100                  )                              

Your output will expect like this:

Python Turtle Square Edit Newer

Well done! Y'all've just fatigued a square. In this way, the turtle can be programmed to create different shapes and images.

At present, try drawing a rectangle, using this code as a template. Call up, in a rectangle, all 4 sides are not equal. You'll need to alter the code accordingly. Once yous do that, you lot tin can fifty-fifty try creating other polygons past increasing the number of sides and changing the angles.

Cartoon Preset Figures

Suppose you want to draw a circle. If you attempt to describe it in the same way as you drew the square, so it would exist extremely tedious, and you'd accept to spend a lot of time just for that one shape. Thankfully, the Python turtle library provides a solution for this. Y'all can use a single command to depict a circle:

You'll get an output like this:

Python Turtle Circle Updated

The number inside the brackets is the radius of the circle. Y'all can increase or decrease the size of the circle by changing the value of its radius.

In the same way, y'all can also depict a dot, which is cipher but a filled-in circle. Type in this command:

You'll get a filled-in circumvolve like this:

Python Turtle Dot Update

The number within the brackets is the bore of the dot. Just like with the circle, y'all can increase or decrease the size of the dot by changing the value of its diameter.

Smashing chore and then far! Y'all've learned how to move the turtle around and create different shapes with it. In the next few sections, you'll see how you can customize your turtle and its environs, based on your requirements.

Changing the Screen Color

By default, turtle e'er opens up a screen with a white background. Nevertheless, you lot can change the color of the screen at any time using the post-obit command:

>>>

                                                  >>>                                    turtle                  .                  bgcolor                  (                  "blue"                  )                              

Yous tin can supersede "bluish" with any other color. Effort "green" or "red". Yous'll get a event like this:

Python Turtle Background Color

You lot tin can use a multifariousness of colors for your screen just by typing in their hex code number. To learn more than near using unlike colors, bank check out the Python turtle library documentation.

Changing the Screen Title

Sometimes, you lot may want to change the title of your screen. You tin can make information technology more personal, like "My Turtle Plan", or more suitable to what you're working on, like "Drawing Shapes With Turtle". You tin change the title of your screen with the assist of this command:

>>>

                                                  >>>                                    turtle                  .                  title                  (                  "My Turtle Program"                  )                              

Your title bar will now display this:

Python Turtle Screen Title Updated

In this fashion, you tin can change the heading of your screen according to your preference.

Changing the Turtle Size

You can increase or decrease the size of the onscreen turtle to make it bigger or smaller. This changes only the size of the shape without affecting the output of the pen as information technology draws on the screen. Try typing in the following commands:

>>>

                                                  >>>                                    t                  .                  shapesize                  (                  one                  ,                  v                  ,                  10                  )                  >>>                                    t                  .                  shapesize                  (                  ten                  ,                  v                  ,                  ane                  )                  >>>                                    t                  .                  shapesize                  (                  1                  ,                  10                  ,                  v                  )                  >>>                                    t                  .                  shapesize                  (                  x                  ,                  i                  ,                  5                  )                              

Your outputs volition look like this:

Python Turtle Shape Size Updated

The numbers given are the parameters for the size of the turtle:

  • Stretch length
  • Stretch width
  • Outline width

Yous can change these according to your preference. In the example given above, you can see a visible divergence in the appearance of the turtle. For more information on how you can change the size of the turtle, bank check out the Python turtle library documentation.

Changing the Pen Size

The previous command changed the size of the turtle's shape only. However, sometimes, you may need to increase or decrease the thickness of your pen. Y'all can do this using the following command:

>>>

                                                  >>>                                    t                  .                  pensize                  (                  five                  )                  >>>                                    t                  .                  frontwards                  (                  100                  )                              

This results in an consequence like this:

Python Turtle Pen Size More NEW

As yous tin encounter, the size of your pen is now five times the original size (which was ane). Try drawing some more lines of various sizes, and compare the difference in thickness between them.

Changing the Turtle and Pen Color

When you first open a new screen, the turtle starts out as a black effigy and draws with black ink. Based on your requirements, you can practise two things:

  • Modify the color of the turtle: This changes the fill color.
  • Alter the color of the pen: This changes the outline or the ink color.

Yous can fifty-fifty cull both of these if you wish. Earlier you change the colors, increase the size of your turtle to help yous come across the colour divergence more clearly. Type in this code:

>>>

                                                  >>>                                    t                  .                  shapesize                  (                  iii                  ,                  3                  ,                  iii                  )                              

Now, to change the color of the turtle (or the fill), you blazon the following:

>>>

                                                  >>>                                    t                  .                  fillcolor                  (                  "red"                  )                              

Your turtle will look like this:

Python Turtle Fill Color Red

To change the colour of the pen (or the outline), you type the following:

>>>

                                                  >>>                                    t                  .                  pencolor                  (                  "green"                  )                              

Your turtle will look like this:

Python Turtle Pen Color Updated Green

To change the colour of both, you type the following:

>>>

                                                  >>>                                    t                  .                  colour                  (                  "green"                  ,                  "ruddy"                  )                              

Your turtle will expect like this:

Python Turtle Color Single Line Updated

Here, the kickoff color is for the pen, and the 2d is for the fill. Note that irresolute the color of the pen and the fill likewise changes the colour of the onscreen turtle appropriately.

Filling in an Epitome

Coloring in an paradigm usually makes information technology look improve, doesn't it? The Python turtle library gives you the option to add color to your drawings. Try typing in the following code and meet what happens:

>>>

                                                  >>>                                    t                  .                  begin_fill                  ()                  >>>                                    t                  .                  fd                  (                  100                  )                  >>>                                    t                  .                  lt                  (                  120                  )                  >>>                                    t                  .                  fd                  (                  100                  )                  >>>                                    t                  .                  lt                  (                  120                  )                  >>>                                    t                  .                  fd                  (                  100                  )                  >>>                                    t                  .                  end_fill                  ()                              

When you execute this code, yous'll get a triangle that'due south filled in with a solid colour, like this:

Python Turtle Begin Fill End Fill New

When you lot utilize .begin_fill(), y'all're telling your program that you're going to exist drawing a closed shape which will need to be filled in. And so, you use .end_fill() to betoken that you lot're done creating your shape and information technology can now be filled in.

Changing the Turtle Shape

The initial shape of the turtle isn't really a turtle, but a triangular effigy. Nevertheless, you tin change the way the turtle looks, and you do have a couple of options when it comes to doing so. Yous tin take a look at some of them past typing in the post-obit commands:

>>>

                                                  >>>                                    t                  .                  shape                  (                  "turtle"                  )                  >>>                                    t                  .                  shape                  (                  "pointer"                  )                  >>>                                    t                  .                  shape                  (                  "circle"                  )                              

The shape of the turtle will alter accordingly, like this:

Python Turtle Shapes

You take a couple of other options that you lot tin endeavor besides:

  • Square
  • Pointer
  • Circle
  • Turtle
  • Triangle
  • Classic

The classic shape is the original shape. Cheque out the Python turtle library documentation to learn more about the types of shapes that you tin use.

Changing the Pen Speed

The turtle generally moves at a moderate footstep. If you want to subtract or increment the speed to make your turtle move slower or faster, then you can do then by typing the following:

>>>

                                                  >>>                                    t                  .                  speed                  (                  1                  )                  >>>                                    t                  .                  forward                  (                  100                  )                  >>>                                    t                  .                  speed                  (                  x                  )                  >>>                                    t                  .                  forward                  (                  100                  )                              

This code will showtime decrease the speed and movement the turtle forward, then increase the speed and move the turtle forward once again, similar this:

Python Turtle Speed Updated

The speed can exist whatever number ranging from 0 (the slowest speed) to x (the highest speed). Yous tin play around with your lawmaking to come across how fast or ho-hum the turtle will go.

Customizing in One Line

Suppose y'all want to fix your turtle'south characteristics to the following:

  • Pen colour: purple
  • Fill color: orange
  • Pen size: 10
  • Pen speed: nine

From what you've but learned, the lawmaking should await something like this:

>>>

                                                  >>>                                    t                  .                  pencolor                  (                  "purple"                  )                  >>>                                    t                  .                  fillcolor                  (                  "orange"                  )                  >>>                                    t                  .                  pensize                  (                  ten                  )                  >>>                                    t                  .                  speed                  (                  9                  )                  >>>                                    t                  .                  begin_fill                  ()                  >>>                                    t                  .                  circle                  (                  90                  )                  >>>                                    t                  .                  end_fill                  ()                              

It'southward pretty long, but not that bad, right?

Now, only imagine if you had ten unlike turtles. Changing all of their characteristics would be extremely tiresome for you to exercise! The good news is that y'all tin reduce your workload by altering the parameters in just a single line of code, like this:

>>>

                                                  >>>                                    t                  .                  pen                  (                  pencolor                  =                  "purple"                  ,                  fillcolor                  =                  "orangish"                  ,                  pensize                  =                  10                  ,                  speed                  =                  9                  )                  >>>                                    t                  .                  begin_fill                  ()                  >>>                                    t                  .                  circle                  (                  90                  )                  >>>                                    t                  .                  end_fill                  ()                              

This volition give you a effect like this:

Python Turtle Single Line Pen Newer

This single line of code changed the entire pen, without you having to change each characteristic individually. To learn more about this control, cheque out the Python turtle library documentation.

Neat job! Now that you've learned to customize your turtle and the screen, take a look at some other important commands that are required while drawing with the Python turtle library.

Picking the Pen Upwards and Downward

Sometimes, yous may want to movement your turtle to some other point on the screen without cartoon anything on the screen itself. To practice this, y'all apply .penup(). Then, when you lot want to first drawing over again, you use .pendown(). Give it a shot using the code that you used previously to describe a foursquare. Try typing the following code:

>>>

                                                  >>>                                    t                  .                  fd                  (                  100                  )                  >>>                                    t                  .                  rt                  (                  90                  )                  >>>                                    t                  .                  penup                  ()                  >>>                                    t                  .                  fd                  (                  100                  )                  >>>                                    t                  .                  rt                  (                  90                  )                  >>>                                    t                  .                  pendown                  ()                  >>>                                    t                  .                  fd                  (                  100                  )                  >>>                                    t                  .                  rt                  (                  90                  )                  >>>                                    t                  .                  penup                  ()                  >>>                                    t                  .                  fd                  (                  100                  )                  >>>                                    t                  .                  pendown                  ()                              

When yous run this lawmaking, your output volition wait like this:

Python Turtle Pen Up Pen Down Edit

Here, you've obtained two parallel lines instead of a foursquare past adding some extra commands in between the original plan.

Undoing Changes

No matter how conscientious you are, at that place's always a possibility of making a fault. Don't worry, though! The Python turtle library gives you the option to undo what you've done. If yous desire to undo the very last affair you did, and then type in the post-obit:

This undoes the final control that you ran. If y'all want to undo your last three commands, then you would type t.disengage() three times.

Immigration the Screen

Right at present, you probably accept a lot on your screen since yous've started this tutorial. To make room for more than, just type in the following control:

This will clean up your screen so that you can go on drawing. Notation here that your variables will non change, and the turtle will remain in the same position. If you lot have other turtles on your screen other than the original turtle, then their drawings will non be cleared out unless you lot specifically call them out in your lawmaking.

Resetting the Environment

You also have the pick to beginning on a clean slate with a reset command. The screen will get cleared upwards, and the turtle's settings will all be restored to their default parameters. All you need to to do is blazon in the post-obit control:

This clears the screen and takes the turtle back to its home position. Your default settings, like the turtle'due south size, shape, color, and other features, volition as well be restored.

Now that you've learned the fundamentals of programming with the Python turtle library, y'all'll bank check out some bonus features that you lot may want to use while programming.

Leaving a Stamp

You have the selection of leaving a stamp of your turtle on the screen, which is nothing but an imprint of the turtle. Try typing in this lawmaking to come across how it works:

>>>

                                                  >>>                                    t                  .                  postage                  ()                  viii                  >>>                                    t                  .                  fd                  (                  100                  )                  >>>                                    t                  .                  postage                  ()                  ix                  >>>                                    t                  .                  fd                  (                  100                  )                              

Your output will look like this:

Python Turtle Stamps Edit

The numbers that appear are the turtle's location or stamp ID. At present, if y'all want to remove a item stamp, then merely use the following:

This volition clear the ane with the stamp ID of 8.

Cloning Your Turtle

Sometimes, yous may need to have more than one turtle on your screen. You'll see an instance of this later on in the final project. For now, you lot can get another turtle by cloning your current turtle into your environs. Try running this code to create a clone turtle, c, and then move both the turtles on the screen:

>>>

                                                  >>>                                    c                  =                  t                  .                  clone                  ()                  >>>                                    t                  .                  colour                  (                  "magenta"                  )                  >>>                                    c                  .                  colour                  (                  "red"                  )                  >>>                                    t                  .                  circle                  (                  100                  )                  >>>                                    c                  .                  circle                  (                  60                  )                              

The output will look like this:

Python Turtle Clone NEWER

Awesome!

Now that you have an idea of some important commands from the Python turtle library, y'all're set to motion on to a few more than concepts that you'll need to understand. These concepts are very much needed when it comes to programming in whatsoever language.

Using Loops and Conditional Statements

When you get into higher-level programming, y'all'll find yourself using loops and conditional statements very often. That'due south why, in this section, you'll be going through a couple of turtle programs that make use of these types of commands. This volition give you a practical approach when it comes to understanding these concepts. Before you brainstorm, however, hither are three definitions for y'all to go along in heed:

  1. Loops are a set up of instructions that are continuously repeated until a particular condition is satisfied.
  2. Provisional statements carry out a certain task based on a condition that's satisfied.
  3. Indentations are used to define blocks of code, especially when using loops and conditional statements. In general, yous create an indentation by tapping the Tab primal on the keyboard.

At present, allow's go ahead and explore these commands!

for Loops

Exercise you lot recollect the programme that y'all used to create a foursquare? You had to repeat the same line of code iv times, similar this:

>>>

                                                  >>>                                    t                  .                  fd                  (                  100                  )                  >>>                                    t                  .                  rt                  (                  ninety                  )                  >>>                                    t                  .                  fd                  (                  100                  )                  >>>                                    t                  .                  rt                  (                  90                  )                  >>>                                    t                  .                  fd                  (                  100                  )                  >>>                                    t                  .                  rt                  (                  ninety                  )                  >>>                                    t                  .                  fd                  (                  100                  )                  >>>                                    t                  .                  rt                  (                  xc                  )                              

A much shorter way to do this is with the aid of a for loop. Try running this code:

>>>

                                                  >>>                                    for                  i                  in                  range                  (                  four                  ):                  ...                                    t                  .                  fd                  (                  100                  )                  ...                                    t                  .                  rt                  (                  90                  )                              

Here, the i is like a counter that starts from nothing and keeps increasing by one. When you say in range(4), you lot're telling the program that the value of this i should be less than iv. It will end the program earlier i reaches 4.

Here's a breakdown of how the programme works:

  1. At i = 0, the turtle moves forward past 100 units and so turns xc degrees to the right.
  2. At i = 0 + 1 = ane, the turtle moves forward by 100 units and and then turns 90 degrees to the correct.
  3. At i = 1 + 1 = ii, the turtle moves forward by 100 units and so turns 90 degrees to the right.
  4. At i = 2 + 1 = three, the turtle moves forrard by 100 units and and then turns 90 degrees to the right.

The turtle volition so exit the loop. To check the value of i, type i and then printing the Enter key. Y'all'll get the value of i equal to 3:

Note that the whitespace that comes before line 2 and line 3 in the program is the indentation. This indicates that all 3 lines class a single block of lawmaking. To learn more than about for loops in Python, cheque out Python "for" Loops (Definite Iteration).

while Loops

The while loop is used to perform a certain task while a condition is still satisfied. If the status is no longer satisfied, then your code volition finish the process. You tin utilise a while loop to create a series of circles by typing in this code:

>>>

                                                  >>>                                    due north                  =                  x                  >>>                                    while                  northward                  <=                  xl                  :                  ...                                    t                  .                  circle                  (                  north                  )                  ...                                    due north                  =                  north                  +                  10                              

When you lot run this lawmaking, you'll run into the circles appearing one after the other, and each new circle will be larger than the previous 1:

Python Turtle While Loop Edited Newer

Here, due north is used as a counter. You'll need to specify by how much you want the value of due north to increase in each loop. Take a expect at this mini walk-through to run across how the program works:

  1. At n = 10, the turtle draws a circle with a radius of ten units. After that, the value of north is increased past x.
  2. At n = xx, the turtle draws a circle with a radius of 20 units. Once once again, the value of n is increased past 10.
  3. At n = 30, the turtle draws a circle with a radius of 30 units. For the third time, the value of n is increased by 10.
  4. At northward = xl, the turtle draws a circle with a radius of 40 units. For the last time, the value of n is increased by 10.
  5. At due north = 50, n is no longer less than or equal to forty. The loop is terminated.

To read more about while loops, check out Python "while" Loops (Indefinite Iteration).

Conditional Statements

You utilize provisional statements to cheque if a given condition is true. If it is, then the corresponding command is executed. Try typing in this programme:

>>>

                                                  >>>                                    u                  =                  input                  (                  "Would you like me to draw a shape? Blazon aye or no: "                  )                  >>>                                    if                  u                  ==                  "yes"                  :                  ...                                    t                  .                  circle                  (                  fifty                  )                              

input() is used to obtain input from the user. Here, it will store the user's response nether the variable u. Adjacent, information technology volition compare the value of u with the condition provided and bank check whether the value of u is "yep". If it'due south "yes", and so your program draws a circle. If the user types in anything else, so the program won't practice anything.

When you add together an else clause to an if argument, yous can specify ii results based on whether the condition is true or simulated. Permit's see this in a program:

>>>

                                                  >>>                                    u                  =                  input                  (                  "Would y'all similar me to draw a shape? Type yeah or no: "                  )                  >>>                                    if                  u                  ==                  "yes"                  :                  ...                                    t                  .                  circle                  (                  fifty                  )                  >>>                                    else                  :                  ...                                    print                  (                  "Okay"                  )                              

Hither, yous tell the plan to display a detail output even when the user does not say "yep". You lot use print() to brandish some pre-divers characters on the screen.

Note that the user doesn't need to type "no". They can type annihilation else, in which instance, the result will always exist "Okay", because y'all're not explicitly telling the programme that the user needs to type "no". Not to worry, notwithstanding, equally that can be fixed. Yous can add together an elif clause to provide the plan with several conditions and their respective outputs, equally you can observe here:

>>>

                                                  >>>                                    u                  =                  input                  (                  "Would you lot like me to draw a shape? Type aye or no: "                  )                  >>>                                    if                  u                  ==                  "yes"                  :                  ...                                    t                  .                  circle                  (                  50                  )                  >>>                                    elif                  u                  ==                  "no"                  :                  ...                                    print                  (                  "Okay"                  )                  >>>                                    else                  :                  ...                                    impress                  (                  "Invalid Reply"                  )                              

As yous can see, this plan now has more than than one event, depending on the input it receives. Here's how this lawmaking works:

  • If you blazon in "aye", then the code processes the input and draws a circumvolve, every bit per your instructions.
  • If yous type in "no", so the code prints out "Okay" and your program is terminated.
  • If you type in annihilation else, like "How-do-you-do" or "Sandwich", and so the lawmaking prints "Invalid Respond" and your program is terminated.

Note that this plan is instance-sensitive, and then when you're trying it out, be sure to put the strings in upper-case or lower-case appropriately.

To learn more near conditional statements, check out Provisional Statements in Python.

Final Project: The Python Turtle Race

And then far, you've learned how to customize your turtle environs, program your turtle to move around the screen, and apply loops and conditional statements to improve your code. Now it's time for the about important part of your programming journey. In this section, you'll exist implementing all that you've learned into a single program by creating a fun game that you tin play with your friends.

Earlier you begin, here'due south what you demand to know about the game:

  1. The Objective: The player whose turtle reaches its home first wins the game.

  2. How to Play:

    • Each thespian rolls a dice to get a number.
    • The role player then moves their turtle by that many steps.
    • The players alternate turns until 1 of them wins.
  3. The Structure:

    • Each actor had a turtle indicated by a different color. You tin can have more than two players, but for the sake of this tutorial, you'll exist creating a two-player game.
    • Each turtle has a home position that it must reach.
    • Each actor uses a die to choose a value at random for their turn. In your programme, the die is represented by a list of numbers from 1 to 6.

Now that you've understood the logic of the game, yous can go ahead and begin creating information technology! First, you'll need to gear up the environment.

Setting Up the Game Environment

First by importing the Python turtle library. Afterward this, import the congenital-in random library, which you lot'll use randomly select an item from a list:

>>>

                                                  >>>                                    import                  turtle                  >>>                                    import                  random                              

Once these libraries are successfully called into your environs, you can keep with the residue of your program.

Setting Up the Turtles and Homes

You at present accept to create the ii turtles that will stand for the players. Each turtle volition be a different color, corresponding to the unlike players. Here, thespian one is green and actor 2 is blueish:

>>>

                                                  >>>                                    player_one                  =                  turtle                  .                  Turtle                  ()                  >>>                                    player_one                  .                  colour                  (                  "green"                  )                  >>>                                    player_one                  .                  shape                  (                  "turtle"                  )                  >>>                                    player_one                  .                  penup                  ()                  >>>                                    player_one                  .                  goto                  (                  -                  200                  ,                  100                  )                  >>>                                    player_two                  =                  player_one                  .                  clone                  ()                  >>>                                    player_two                  .                  color                  (                  "blue"                  )                  >>>                                    player_two                  .                  penup                  ()                  >>>                                    player_two                  .                  goto                  (                  -                  200                  ,                  -                  100                  )                              

One you've created the turtles, you place them at their starting positions and make sure that these positions are aligned. Notation that y'all created player 2's turtle by cloning actor one's turtle, changing its color, and placing information technology at a different starting point.

You lot now need to gear up upwards homes for the turtles. These homes will act as the finishing points for each turtle. Each of the turtles' homes will be represented by a circle. Here, y'all need to make sure that both homes are equidistant from the starting point:

>>>

                                                  >>>                                    player_one                  .                  goto                  (                  300                  ,                  60                  )                  >>>                                    player_one                  .                  pendown                  ()                  >>>                                    player_one                  .                  circumvolve                  (                  40                  )                  >>>                                    player_one                  .                  penup                  ()                  >>>                                    player_one                  .                  goto                  (                  -                  200                  ,                  100                  )                  >>>                                    player_two                  .                  goto                  (                  300                  ,                  -                  140                  )                  >>>                                    player_two                  .                  pendown                  ()                  >>>                                    player_two                  .                  circle                  (                  xl                  )                  >>>                                    player_two                  .                  penup                  ()                  >>>                                    player_two                  .                  goto                  (                  -                  200                  ,                  -                  100                  )                              

Subsequently drawing the corresponding homes, you ship the turtles back to their starting positions:

Python Turtle Race Setup Updated

Awesome! The visual aspects of your game are consummate. Yous tin now create the die that you'll be using to play the game.

Creating the Die

Yous can create a virtual die for your game with a listing, which is an ordered sequence of items. In real life, yous might prepare grocery lists and to-exercise lists to help you stay organized. In Python, lists work in a similar way.

In this case, y'all'll be using a list to create your die. First, you define your listing of numbers in ascending order from 1 to 6. Yous can define a list past giving it a name and so enclosing its items within foursquare brackets, like this:

>>>

                                                  >>>                                    dice                  =                  [                  1                  ,                  2                  ,                  3                  ,                  4                  ,                  5                  ,                  6                  ]                              

This listing has at present become your dice. To roll the dice, all yous accept to do is program your system to randomly select a number from information technology. The number that is selected will exist considered as the output of the die.

Developing the Game

It's time to develop the code for the rest of the game. You'll exist using loops and conditional statements here, then yous need to be careful with the indentations and spaces. To offset, take a look at the steps your program volition need to have to run the game:

  1. Step 1: Yous'll start by telling your program to check if either turtle has reached its home.
  2. Step 2: If they haven't, then yous'll tell your program to allow the players to continue trying.
  3. Step 3: In each loop, you tell your program to ringlet the die past randomly picking a number from the list.
  4. Step four: You so tell it to movement the respective turtle accordingly, with the number of steps based on the outcome of this random selection.

The program keeps repeating this process, and stops once one of the turtles reaches the goal. Here's how the code looks:

>>>

                                                                      ane                  >>>                                    for                  i                  in                  range                  (                  20                  ):                                      2                  ...                                    if                  player_one                  .                  pos                  ()                  >=                  (                  300                  ,                  100                  ):                                      3                  ...                                    print                  (                  "Player One Wins!"                  )                                      four                  ...                                    break                                      5                  ...                                    elif                  player_two                  .                  pos                  ()                  >=                  (                  300                  ,                  -                  100                  ):                                      6                  ...                                    print                  (                  "Player Two Wins!"                  )                                      7                  ...                                    interruption                                      8                  ...                                    else                  :                                      ix                  ...                                    player_one_turn                  =                  input                  (                  "Press 'Enter' to ringlet the dice "                  )                  10                  ...                                    die_outcome                  =                  random                  .                  choice                  (                  die                  )                  11                  ...                                    print                  (                  "The upshot of the die roll is: "                  )                  12                  ...                                    print                  (                  die_outcome                  )                  xiii                  ...                                    impress                  (                  "The number of steps will exist: "                  )                  14                  ...                                    impress                  (                  20                  *                  die_outcome                  )                  15                  ...                                    player_one                  .                  fd                  (                  20                  *                  die_outcome                  )                  16                  ...                                    player_two_turn                  =                  input                  (                  "Press 'Enter' to gyre the die "                  )                  17                  ...                                    die_outcome                  =                  random                  .                  choice                  (                  die                  )                  18                  ...                                    print                  (                  "The event of the dice roll is: "                  )                  19                  ...                                    print                  (                  die_outcome                  )                  20                  ...                                    print                  (                  "The number of steps volition be: "                  )                  21                  ...                                    impress                  (                  20                  *                  die_outcome                  )                  22                  ...                                    player_two                  .                  fd                  (                  20                  *                  die_outcome                  )                              

Your terminal output will look a little something like this:

Python Turtle Race Updated

In summary, this is what the code is doing:

  1. Line 1 sets up a for loop with a range from i to 20.

  2. Lines ii through vii check if either player has reached their goal. If one of them has, then the programme prints out the corresponding argument and breaks the loop.

  3. Line eight moves the programme on to the adjacent set of steps if neither player has won.

  4. Line 9 prints out a statement asking player one to press the Enter key to whorl the die.

  5. Line ten takes a random value from the list die and stores it in die_outcome.

  6. Line eleven prints a statement prior to displaying the outcome of the dice curl.

  7. Line 12 prints the die outcome.

  8. Line fourteen multiplies this value by 20 to reduce the overall number of steps required to complete the game.

  9. Line 15 moves player one's turtle forward by this number of steps.

  10. Lines xvi to 22 echo these steps for player two.

The entire for loop is repeated until one of the player's turtles reaches the final position.

Remember, you can customize the game however you want, then get ahead and play around with information technology! Yous can add more turtles, change the colors, change the speed, or even create some obstacles to challenge your players. It's all up to you equally the programmer of the game!

Determination

In this tutorial, yous've learned how to programme with the Python turtle library and grasped some very of import programming concepts. You lot know how to deal with variable initialization, loops, conditional statements, indentations, lists, and operators. This is a great first for you, peculiarly if you're new to the Python programming language!

At present you can:

  • Set upwards the Python turtle library
  • Move your turtle around
  • Customize your turtle and its environment
  • Plan your turtle
  • Use bones programming concepts
  • Create a game that you can play with friends

Now you're gear up to venture into some higher-level Python programming. To progress further in your Python journeying, check out Introduction to Python and eleven Beginner Tips for Learning Python Programming. But call back to work hard and keep practicing, and you'll observe that you're a Python expert in no fourth dimension!

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your agreement: Python Turtle for Beginners