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

When I was a kid, I used to learn Logo, a programming language that involved a turtle that you could motility around the screen with only a few commands. I remember feeling like a computer genius as I controlled this little object on my screen, and this was what got me interested in programming in the first place. The Python turtle library comes with a similar interactive feature that gives new programmers a sense of taste of what it's like to piece of work with Python.

In this tutorial, you lot will:

  • Understand what the Python turtle library is
  • Larn how to gear up turtle up on your reckoner
  • Program with the Python turtle library
  • Grasp some important Python concepts and turtle commands
  • Develop a short but entertaining game using what you've learned

If y'all're a beginner to Python, then this tutorial will aid you every bit you take your first steps into the world 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 sheet. The onscreen pen that you employ for drawing is called the turtle and this is what gives the library its proper name. In brusque, the Python turtle library helps new programmers go a feel for what programming with Python is like in a fun and interactive manner.

turtle is mainly used to introduce children to the world of computers. It'south a straightforward yet versatile manner to understand the concepts of Python. This makes it a great artery for kids to take their beginning steps in Python programming. That existence said, the Python turtle library is not restricted to little ones lone! It'due south likewise proved extremely useful for adults who are trying their hands at Python, which makes it slap-up for Python beginners.

With the Python turtle library, you can describe and create various types of shapes and images. Hither's a sample of the kinds of drawings you tin brand with turtle:

Python Turtle Initial Demo

Absurd, right? This is just one of many unlike drawings you can make using the Python turtle library. About developers use turtle to draw shapes, create designs, and make images. Others use turtle to create mini-games and animations, just like the one you saw to a higher place.

Getting Started With turtle

Earlier you proceed, in that location are two important things that yous'll need to exercise to make the most of this tutorial:

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

  2. Python Version: Ensure that you lot have version 3 of Python on your computer. If non, and then you tin download it from the Python website. For help setting things up, cheque out Python iii Installation & Setup Guide.

The skilful thing about turtle is that it's a built-in library, so y'all don't need to install any new packages. All y'all demand to do is import the library into your Python environment, which in this case would exist the REPL. In one case yous open your REPL application, y'all can run Python 3 on it by typing the post-obit line of code:

This calls Python 3 into your REPL application and opens upwards the environs for you lot.

Before you begin your Python programming, you demand to understand what a library is. In the not-computer world, a library is a place where different types of books are stored. You can access these books at whatever fourth dimension, have whatever data you need from them, and return them to the same place.

In the figurer globe, a library works similarly. By definition, a library is a set of important functions and methods that you can access to brand your programming easier. The Python turtle library contains all the methods and functions that yous'll need to create your images. To access a Python library, you need to import it into your Python surroundings, like this:

Now that you have turtle in your Python environment, y'all can begin 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 by initializing a variable for it.

In Python, you use variables to shop data that yous'll use later on in your program. You initialize a variable when you assign a starting value to it. Since the value of the variable isn't abiding, it tin can change several times during the execution of your program.

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

>>>

                                            >>>                                south                =                turtle                .                getscreen                ()                          

Y'all should see a split window open up:

Python Turtle Initial Screen New

This window is chosen the screen. Information technology's where you can view the output of your lawmaking. The picayune black triangular shape in the heart of the screen is called the turtle.

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

>>>

                                            >>>                                t                =                turtle                .                Turtle                ()                          

Just similar for the screen, you tin can also give this variable another proper noun like a or Jane or even my_turtle, but in this example, y'all'll stick with t.

You lot now have your screen and your turtle. The screen acts as a sheet, while the turtle acts similar a pen. You can program the turtle to move around the screen. The turtle has certain changeable characteristics, like size, color, and speed. It e'er points in a specific management, and will motion in that direction unless y'all tell it otherwise:

  • When it's upward, information technology means that no line will exist drawn when it moves.
  • When it's down, it means that a line will be drawn when information technology moves.

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

Programming With turtle

The get-go affair you'll larn when it comes to programming with the Python turtle library is how to brand the turtle move in the direction y'all desire information technology to get. Next, you'll learn how to customize your turtle and its environment. Finally, you'll acquire a couple of extra commands with which you can perform some special tasks.

Moving the Turtle

In that location are 4 directions that a turtle tin move in:

  • Forward
  • Astern
  • Left
  • Right

The turtle moves .forward() or .backward() in the direction that it's facing. Yous can alter this management past turning it .left() or .right() by a certain caste. Y'all tin try each of these commands like so:

>>>

                                                  >>>                                    t                  .                  correct                  (                  90                  )                  >>>                                    t                  .                  forwards                  (                  100                  )                  >>>                                    t                  .                  left                  (                  90                  )                  >>>                                    t                  .                  backward                  (                  100                  )                              

When yous run these commands, the turtle will turn right by xc degrees, go frontward by a hundred units, plow left by ninety degrees, and motility astern by a hundred units. Y'all tin can see how this looks in the image beneath:

Python Turtle Moving Updated

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

  • t.rt() instead of t.right()
  • t.fd() instead of t.forrad()
  • t.lt() instead of t.left()
  • t.bk() instead of t.backward()

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

Python Turtle Coordinates New

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

Your output volition look like this:

Python Turtle GOTO NEWER

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

To bring the turtle back to its dwelling position, you type the post-obit:

This is similar a shortcut command that sends the turtle back to the point (0,0). It'due south quicker than typing t.goto(0,0).

Drawing a Shape

Now that you lot know the movements of the turtle, you lot can move on to making actual shapes. You can offset by cartoon polygons since they all consist of directly lines continued at certain angles. Here's an example that yous can try:

>>>

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

Your output will await like this:

Python Turtle Square Edit Newer

Well done! You've merely fatigued a square. In this way, the turtle can be programmed to create unlike shapes and images.

At present, try drawing a rectangle, using this code as a template. Think, in a rectangle, all 4 sides are not equal. You'll demand to alter the code appropriately. One time yous exercise that, you can even endeavour creating other polygons by increasing the number of sides and changing the angles.

Drawing Preset Figures

Suppose yous want to draw a circle. If yous attempt to describe it in the same way equally you drew the square, and so it would be extremely wearisome, and y'all'd have to spend a lot of fourth dimension just for that one shape. Thankfully, the Python turtle library provides a solution for this. You can apply a single control to draw a circle:

You'll get an output like this:

Python Turtle Circle Updated

The number within the brackets is the radius of the circle. You can increase or decrease the size of the circle by changing the value of its radius.

In the same way, y'all tin can also depict a dot, which is goose egg but a filled-in circle. Blazon in this control:

You'll get a filled-in circle similar this:

Python Turtle Dot Update

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

Great chore so far! You've learned how to move the turtle around and create dissimilar shapes with information technology. In the adjacent few sections, you'll come across how you tin can customize your turtle and its environment, based on your requirements.

Irresolute the Screen Color

By default, turtle always opens upwardly a screen with a white groundwork. However, you can alter the color of the screen at any time using the following command:

>>>

                                                  >>>                                    turtle                  .                  bgcolor                  (                  "blue"                  )                              

Yous can replace "blue" with any other color. Try "greenish" or "ruby". Y'all'll get a result like this:

Python Turtle Background Color

You tin use a variety of colors for your screen just by typing in their hex code number. To larn more about using unlike colors, check out the Python turtle library documentation.

Irresolute the Screen Title

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

>>>

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

Your title bar will now display this:

Python Turtle Screen Title Updated

In this way, yous can change the heading of your screen according to your preference.

Changing the Turtle Size

Yous 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 equally information technology draws on the screen. Endeavour typing in the following commands:

>>>

                                                  >>>                                    t                  .                  shapesize                  (                  1                  ,                  5                  ,                  10                  )                  >>>                                    t                  .                  shapesize                  (                  10                  ,                  5                  ,                  i                  )                  >>>                                    t                  .                  shapesize                  (                  1                  ,                  10                  ,                  5                  )                  >>>                                    t                  .                  shapesize                  (                  10                  ,                  1                  ,                  v                  )                              

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

You lot can change these co-ordinate to your preference. In the example given higher up, you tin can see a visible difference in the appearance of the turtle. For more than information on how you lot tin modify the size of the turtle, check out the Python turtle library documentation.

Irresolute the Pen Size

The previous command inverse the size of the turtle'south shape simply. However, sometimes, yous may need to increment or subtract the thickness of your pen. You can do this using the post-obit command:

>>>

                                                  >>>                                    t                  .                  pensize                  (                  5                  )                  >>>                                    t                  .                  forward                  (                  100                  )                              

This results in an outcome like this:

Python Turtle Pen Size More NEW

As you can run into, the size of your pen is now five times the original size (which was one). Try drawing some more lines of various sizes, and compare the difference in thickness betwixt them.

Changing the Turtle and Pen Color

When you first open up a new screen, the turtle starts out as a blackness figure and draws with black ink. Based on your requirements, yous tin exercise two things:

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

You tin even choose both of these if you wish. Before you change the colors, increase the size of your turtle to help you see the color difference more clearly. Blazon in this code:

>>>

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

At present, to change the color of the turtle (or the fill), you type the post-obit:

>>>

                                                  >>>                                    t                  .                  fillcolor                  (                  "red"                  )                              

Your turtle volition look like this:

Python Turtle Fill Color Red

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

>>>

                                                  >>>                                    t                  .                  pencolor                  (                  "light-green"                  )                              

Your turtle will look similar this:

Python Turtle Pen Color Updated Green

To modify the color of both, you blazon the post-obit:

>>>

                                                  >>>                                    t                  .                  color                  (                  "green"                  ,                  "reddish"                  )                              

Your turtle will wait like this:

Python Turtle Color Single Line Updated

Hither, the start colour is for the pen, and the second is for the fill. Note that changing the color of the pen and the fill also changes the colour of the onscreen turtle accordingly.

Filling in an Image

Coloring in an image unremarkably makes information technology look better, doesn't it? The Python turtle library gives yous the option to add colour to your drawings. Try typing in the following code and see what happens:

>>>

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

When y'all execute this lawmaking, you lot'll go a triangle that's filled in with a solid colour, like this:

Python Turtle Begin Fill End Fill New

When you lot use .begin_fill(), you're telling your program that you're going to be drawing a airtight shape which will need to be filled in. And then, yous use .end_fill() to indicate that you're done creating your shape and it tin now be filled in.

Changing the Turtle Shape

The initial shape of the turtle isn't really a turtle, but a triangular effigy. Nonetheless, you lot can change the way the turtle looks, and you exercise have a couple of options when information technology comes to doing so. You tin can take a expect at some of them by typing in the following commands:

>>>

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

The shape of the turtle will change accordingly, similar this:

Python Turtle Shapes

You take a couple of other options that you tin can try besides:

  • Square
  • Arrow
  • Circle
  • Turtle
  • Triangle
  • Archetype

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

Changing the Pen Speed

The turtle generally moves at a moderate pace. If you want to decrease or increment the speed to make your turtle move slower or faster, and then y'all can practise then past typing the following:

>>>

                                                  >>>                                    t                  .                  speed                  (                  ane                  )                  >>>                                    t                  .                  forwards                  (                  100                  )                  >>>                                    t                  .                  speed                  (                  10                  )                  >>>                                    t                  .                  forward                  (                  100                  )                              

This code will commencement decrease the speed and motion the turtle forward, then increase the speed and move the turtle forward again, like this:

Python Turtle Speed Updated

The speed tin exist any number ranging from 0 (the slowest speed) to x (the highest speed). You can play effectually with your code to run across how fast or slow the turtle will get.

Customizing in I Line

Suppose y'all want to set your turtle's characteristics to the post-obit:

  • Pen color: majestic
  • Fill up color: orange
  • Pen size: 10
  • Pen speed: nine

From what y'all've simply learned, the code should look something like this:

>>>

                                                  >>>                                    t                  .                  pencolor                  (                  "imperial"                  )                  >>>                                    t                  .                  fillcolor                  (                  "orange"                  )                  >>>                                    t                  .                  pensize                  (                  ten                  )                  >>>                                    t                  .                  speed                  (                  ix                  )                  >>>                                    t                  .                  begin_fill                  ()                  >>>                                    t                  .                  circumvolve                  (                  xc                  )                  >>>                                    t                  .                  end_fill                  ()                              

It'due south pretty long, simply non that bad, right?

At present, but imagine if you had ten different turtles. Irresolute all of their characteristics would be extremely deadening for you lot to do! The skillful news is that y'all tin reduce your workload past altering the parameters in only a unmarried line of lawmaking, like this:

>>>

                                                  >>>                                    t                  .                  pen                  (                  pencolor                  =                  "purple"                  ,                  fillcolor                  =                  "orange"                  ,                  pensize                  =                  ten                  ,                  speed                  =                  ix                  )                  >>>                                    t                  .                  begin_fill                  ()                  >>>                                    t                  .                  circle                  (                  90                  )                  >>>                                    t                  .                  end_fill                  ()                              

This will requite y'all a upshot like this:

Python Turtle Single Line Pen Newer

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

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

Picking the Pen Up and Down

Sometimes, y'all may want to motion your turtle to another bespeak on the screen without drawing anything on the screen itself. To do this, you use .penup(). And then, when y'all want to offset drawing again, yous utilize .pendown(). Give it a shot using the lawmaking that yous used previously to draw a square. Try typing the following lawmaking:

>>>

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

When you run this code, your output will look like this:

Python Turtle Pen Up Pen Down Edit

Hither, yous've obtained two parallel lines instead of a square by adding some extra commands in between the original program.

Undoing Changes

No matter how conscientious you are, there'southward always a possibility of making a fault. Don't worry, though! The Python turtle library gives you the option to undo what you lot've done. If you want to undo the very last thing you did, then blazon in the following:

This undoes the final command that you ran. If you want to undo your last 3 commands, then you lot would blazon t.undo() 3 times.

Clearing the Screen

Right now, yous probably have a lot on your screen since yous've started this tutorial. To make room for more, merely type in the following command:

This will clean up your screen then that y'all can continue cartoon. Note here that your variables will not change, and the turtle will remain in the same position. If you take other turtles on your screen other than the original turtle, then their drawings volition non be cleared out unless y'all specifically call them out in your code.

Resetting the Environment

You also have the pick to start on a clean slate with a reset command. The screen will get cleared up, and the turtle's settings volition all exist restored to their default parameters. All yous demand to to do is type in the following command:

This clears the screen and takes the turtle dorsum to its home position. Your default settings, like the turtle'southward size, shape, color, and other features, will as well exist restored.

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

Leaving a Stamp

You take the option of leaving a stamp of your turtle on the screen, which is nothing merely an imprint of the turtle. Effort typing in this code to come across how it works:

>>>

                                                  >>>                                    t                  .                  stamp                  ()                  eight                  >>>                                    t                  .                  fd                  (                  100                  )                  >>>                                    t                  .                  stamp                  ()                  9                  >>>                                    t                  .                  fd                  (                  100                  )                              

Your output will await similar this:

Python Turtle Stamps Edit

The numbers that announced are the turtle'southward location or postage stamp ID. Now, if you want to remove a particular stamp, so only use the following:

This will articulate the one with the stamp ID of 8.

Cloning Your Turtle

Sometimes, you may need to take more than than ane turtle on your screen. Yous'll see an example of this later on in the final project. For now, y'all 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                  .                  color                  (                  "magenta"                  )                  >>>                                    c                  .                  color                  (                  "carmine"                  )                  >>>                                    t                  .                  circle                  (                  100                  )                  >>>                                    c                  .                  circle                  (                  60                  )                              

The output volition await like this:

Python Turtle Clone NEWER

Awesome!

Now that you have an idea of some important commands from the Python turtle library, yous're ready to move on to a few more than concepts that yous'll need to empathize. These concepts are very much needed when it comes to programming in any language.

Using Loops and Provisional Statements

When you get into higher-level programming, you'll notice yourself using loops and provisional statements very oft. That's why, in this section, you lot'll be going through a couple of turtle programs that make utilize of these types of commands. This will give you a practical approach when it comes to agreement these concepts. Before you begin, withal, here are three definitions for you lot to keep in listen:

  1. Loops are a set up of instructions that are continuously repeated until a particular condition is satisfied.
  2. Conditional statements carry out a certain task based on a condition that'due south satisfied.
  3. Indentations are used to define blocks of lawmaking, especially when using loops and provisional statements. In general, you create an indentation by tapping the Tab fundamental on the keyboard.

Now, allow'southward go ahead and explore these commands!

for Loops

Do you remember the program that you used to create a square? You had to repeat the same line of code iv times, like this:

>>>

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

A much shorter way to exercise this is with the assist of a for loop. Attempt running this code:

>>>

                                                  >>>                                    for                  i                  in                  range                  (                  4                  ):                  ...                                    t                  .                  fd                  (                  100                  )                  ...                                    t                  .                  rt                  (                  ninety                  )                              

Here, the i is like a counter that starts from zip and keeps increasing past 1. When you say in range(four), you're telling the program that the value of this i should be less than 4. It will cease the program earlier i reaches four.

Hither's a breakdown of how the plan works:

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

The turtle will then exit the loop. To check the value of i, blazon i and then printing the Enter key. You'll get the value of i equal to 3:

Annotation that the whitespace that comes earlier line 2 and line three in the programme is the indentation. This indicates that all three lines class a single block of code. To larn more about for loops in Python, check out Python "for" Loops (Definite Iteration).

while Loops

The while loop is used to perform a certain task while a status is all the same satisfied. If the condition is no longer satisfied, then your code will terminate the process. You can apply a while loop to create a series of circles by typing in this code:

>>>

                                                  >>>                                    north                  =                  10                  >>>                                    while                  due north                  <=                  forty                  :                  ...                                    t                  .                  circle                  (                  n                  )                  ...                                    northward                  =                  n                  +                  10                              

When you run this code, yous'll see 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. Y'all'll need to specify by how much you want the value of northward to increase in each loop. Accept a look at this mini walk-through to run into how the program works:

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

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

Provisional Statements

Y'all employ conditional statements to check if a given status is truthful. If it is, and so the corresponding command is executed. Attempt typing in this program:

>>>

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

input() is used to obtain input from the user. Here, it will store the user's response nether the variable u. Next, information technology volition compare the value of u with the status provided and check whether the value of u is "yep". If information technology's "yeah", and so your program draws a circle. If the user types in annihilation else, and so the plan won't exercise annihilation.

When y'all add an else clause to an if statement, yous can specify 2 results based on whether the condition is truthful or simulated. Let'due south come across this in a program:

>>>

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

Here, you tell the program to display a particular output even when the user does not say "yes". You use impress() to brandish some pre-divers characters on the screen.

Note that the user doesn't demand to blazon "no". They can type anything else, in which case, the outcome will always be "Okay", considering yous're not explicitly telling the program that the user needs to type "no". Non to worry, however, as that tin be fixed. You can add an elif clause to provide the plan with several conditions and their respective outputs, equally y'all can discover hither:

>>>

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

As you lot can see, this program now has more than ane effect, depending on the input it receives. Hither's how this lawmaking works:

  • If you blazon in "yes", then the code processes the input and draws a circle, as per your instructions.
  • If you type in "no", then the code prints out "Okay" and your program is terminated.
  • If you type in anything else, like "Hello" or "Sandwich", then the code prints "Invalid Answer" and your program is terminated.

Note that this programme is example-sensitive, and then when y'all're trying it out, be sure to put the strings in upper-instance or lower-case accordingly.

To learn more most conditional statements, bank check out Conditional Statements in Python.

Final Projection: The Python Turtle Race

So far, yous've learned how to customize your turtle environment, plan your turtle to motion around the screen, and use loops and conditional statements to better your code. Now it's fourth dimension for the near important part of your programming journey. In this section, you'll exist implementing all that you've learned into a single plan past creating a fun game that you can play with your friends.

Before y'all begin, here'south what yous need to know about the game:

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

  2. How to Play:

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

    • Each player had a turtle indicated past a different color. You can have more than than two players, but for the sake of this tutorial, you'll be creating a two-role player game.
    • Each turtle has a home position that it must reach.
    • Each player 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 i to 6.

Now that you've understood the logic of the game, yous tin become ahead and begin creating it! First, y'all'll need to set up up the environment.

Setting Up the Game Environment

Outset past importing the Python turtle library. Afterward this, import the built-in random library, which you'll utilise randomly select an item from a list:

>>>

                                                  >>>                                    import                  turtle                  >>>                                    import                  random                              

Once these libraries are successfully chosen into your surround, you tin can keep with the rest of your program.

Setting Upwardly the Turtles and Homes

You lot now have to create the 2 turtles that volition represent the players. Each turtle volition be a different color, respective to the unlike players. Here, role player one is green and player ii is bluish:

>>>

                                                  >>>                                    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 y'all've created the turtles, you place them at their starting positions and brand sure that these positions are aligned. Note that you created player 2'south turtle by cloning histrion i's turtle, irresolute its color, and placing information technology at a different starting indicate.

Yous now need to gear up homes for the turtles. These homes will deed every bit the finishing points for each turtle. Each of the turtles' homes volition exist represented by a circle. Here, you need to brand sure that both homes are equidistant from the starting betoken:

>>>

                                                  >>>                                    player_one                  .                  goto                  (                  300                  ,                  threescore                  )                  >>>                                    player_one                  .                  pendown                  ()                  >>>                                    player_one                  .                  circle                  (                  40                  )                  >>>                                    player_one                  .                  penup                  ()                  >>>                                    player_one                  .                  goto                  (                  -                  200                  ,                  100                  )                  >>>                                    player_two                  .                  goto                  (                  300                  ,                  -                  140                  )                  >>>                                    player_two                  .                  pendown                  ()                  >>>                                    player_two                  .                  circle                  (                  forty                  )                  >>>                                    player_two                  .                  penup                  ()                  >>>                                    player_two                  .                  goto                  (                  -                  200                  ,                  -                  100                  )                              

After cartoon the respective homes, you send the turtles dorsum to their starting positions:

Python Turtle Race Setup Updated

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

Creating the Dice

Y'all can create a virtual die for your game with a list, which is an ordered sequence of items. In real life, you might ready grocery lists and to-do lists to assistance you stay organized. In Python, lists work in a similar way.

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

>>>

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

This list has now go your die. To roll the dice, all you accept to do is program your system to randomly select a number from it. The number that is selected will exist considered as the output of the dice.

Developing the Game

It'due south time to develop the code for the balance of the game. You'll be using loops and conditional statements here, and then y'all need to be careful with the indentations and spaces. To commencement, take a look at the steps your program volition need to take to run the game:

  1. Step 1: You lot'll beginning by telling your program to bank check if either turtle has reached its dwelling.
  2. Step ii: If they oasis't, and so you'll tell your program to allow the players to proceed trying.
  3. Footstep 3: In each loop, yous tell your program to roll the die by randomly picking a number from the list.
  4. Step 4: Yous then tell information technology to motility the respective turtle accordingly, with the number of steps based on the issue of this random selection.

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

>>>

                                                                      i                  >>>                                    for                  i                  in                  range                  (                  20                  ):                                      2                  ...                                    if                  player_one                  .                  pos                  ()                  >=                  (                  300                  ,                  100                  ):                                      3                  ...                                    impress                  (                  "Player I Wins!"                  )                                      4                  ...                                    break                                      5                  ...                                    elif                  player_two                  .                  pos                  ()                  >=                  (                  300                  ,                  -                  100                  ):                                      6                  ...                                    print                  (                  "Player Two Wins!"                  )                                      7                  ...                                    interruption                                      8                  ...                                    else                  :                                      nine                  ...                                    player_one_turn                  =                  input                  (                  "Printing 'Enter' to roll the dice "                  )                  10                  ...                                    die_outcome                  =                  random                  .                  option                  (                  dice                  )                  11                  ...                                    print                  (                  "The upshot of the die gyre is: "                  )                  12                  ...                                    impress                  (                  die_outcome                  )                  13                  ...                                    print                  (                  "The number of steps will be: "                  )                  fourteen                  ...                                    print                  (                  xx                  *                  die_outcome                  )                  15                  ...                                    player_one                  .                  fd                  (                  20                  *                  die_outcome                  )                  16                  ...                                    player_two_turn                  =                  input                  (                  "Press 'Enter' to roll the dice "                  )                  17                  ...                                    die_outcome                  =                  random                  .                  choice                  (                  die                  )                  18                  ...                                    print                  (                  "The upshot of the dice gyre is: "                  )                  19                  ...                                    print                  (                  die_outcome                  )                  20                  ...                                    print                  (                  "The number of steps will be: "                  )                  21                  ...                                    print                  (                  twenty                  *                  die_outcome                  )                  22                  ...                                    player_two                  .                  fd                  (                  20                  *                  die_outcome                  )                              

Your terminal output will look a piddling 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 one to 20.

  2. Lines 2 through 7 bank check if either role player has reached their goal. If one of them has, so the programme prints out the corresponding statement and breaks the loop.

  3. Line viii moves the program on to the next set of steps if neither role player has won.

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

  5. Line 10 takes a random value from the listing die and stores it in die_outcome.

  6. Line 11 prints a statement prior to displaying the issue of the dice roll.

  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 repeat these steps for role player two.

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

Remember, you lot can customize the game however y'all want, and then become ahead and play around with it! You can add together more turtles, change the colors, change the speed, or even create some obstacles to claiming your players. It's all up to you as the developer of the game!

Conclusion

In this tutorial, yous've learned how to programme with the Python turtle library and grasped some very important programming concepts. Yous know how to bargain with variable initialization, loops, provisional statements, indentations, lists, and operators. This is a slap-up offset for you, especially if you lot're new to the Python programming linguistic communication!

Now y'all can:

  • Ready the Python turtle library
  • Move your turtle around
  • Customize your turtle and its environs
  • Program your turtle
  • Utilise basic programming concepts
  • Create a game that you tin can play with friends

Now yous're ready to venture into some college-level Python programming. To progress farther in your Python journey, bank check out Introduction to Python and 11 Beginner Tips for Learning Python Programming. Just remember to work hard and go on practicing, and you'll find that you're a Python adept in no time!

Watch At present This tutorial has a related video course created by the Existent Python team. Lookout information technology together with the written tutorial to deepen your understanding: Python Turtle for Beginners