Lookout Now This tutorial has a related video grade created by the Real Python squad. Sentry it together with the written tutorial to deepen your understanding: Python Turtle for Beginners

When I was a kid, I used to acquire Logo, a programming language that involved a turtle that you could movement effectually the screen with simply a few commands. I remember feeling like a computer genius every bit I controlled this petty object on my screen, and this was what got me interested in programming in the first identify. The Python turtle library comes with a similar interactive feature that gives new programmers a taste of what it's like to piece of work with Python.

In this tutorial, you volition:

  • Sympathise what the Python turtle library is
  • Learn how to set turtle upward on your computer
  • Programme 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 you're a beginner to Python, then this tutorial will help you as y'all have your get-go steps into the earth of programming with the aid 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 experience for what programming with Python is like in a fun and interactive way.

turtle is mainly used to introduce children to the world of computers. It'due south a straightforward all the same versatile way to understand the concepts of Python. This makes information technology a corking avenue for kids to accept their kickoff steps in Python programming. That being said, the Python turtle library is not restricted to trivial ones alone! It'south also proved extremely useful for adults who are trying their hands at Python, which makes it great for Python beginners.

With the Python turtle library, you tin describe 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, right? This is just one of many different drawings you tin make using the Python turtle library. About developers utilise turtle to draw shapes, create designs, and make images. Others use turtle to create mini-games and animations, simply similar the i you saw to a higher place.

Getting Started With turtle

Before y'all continue, there are ii of import things that you'll need to do to make the most of this tutorial:

  1. Python Surroundings: Make sure that yous're familiar with your programming surround. You tin use applications similar IDLE or Jupyter Notebook to plan with turtle. However, if you're not comfortable with them, so you can program with the REPL, which you'll utilise in this tutorial.

  2. Python Version: Ensure that you take version 3 of Python on your reckoner. If non, then you tin can download information technology from the Python website. For help setting things up, check out Python 3 Installation & Setup Guide.

The practiced thing nigh turtle is that it's a built-in library, so you don't demand to install any new packages. All y'all need to do is import the library into your Python environment, which in this instance would be the REPL. In one case you lot open up your REPL application, yous can run Python iii on it by typing the following line of code:

This calls Python 3 into your REPL awarding and opens upwards the environment for yous.

Earlier you begin your Python programming, you demand to understand what a library is. In the non-reckoner earth, a library is a place where different types of books are stored. You can access these books at whatsoever time, take whatever information you lot need from them, and return them to the same identify.

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

Now that you have turtle in your Python environment, y'all can begin programming with information technology. turtle is a graphical library, which means y'all'll need to create a split up window (called the screen) to carry out each drawing command. You can create this screen by initializing a variable for information technology.

In Python, you employ variables to store information that you'll utilise later on on in your program. You initialize a variable when you assign a starting value to it. Since the value of the variable isn't constant, information technology tin can change several times during the execution of your programme.

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

>>>

                                            >>>                                due south                =                turtle                .                getscreen                ()                          

You should come across a split up window open upwards:

Python Turtle Initial Screen New

This window is called the screen. It's where you tin view the output of your code. The picayune blackness triangular shape in the heart of the screen is called the turtle.

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

>>>

                                            >>>                                t                =                turtle                .                Turtle                ()                          

Simply like for the screen, you can as well give 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 every bit a canvas, while the turtle acts like a pen. You can program the turtle to motility around the screen. The turtle has certain changeable characteristics, like size, color, and speed. It always points in a specific direction, and will move in that direction unless you tell information technology otherwise:

  • When it's up, it means that no line volition be fatigued when information technology moves.
  • When it's downwards, it means that a line will be drawn when it moves.

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

Programming With turtle

The first affair yous'll learn when it comes to programming with the Python turtle library is how to make the turtle motility in the direction you desire it to become. Next, you'll larn 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

At that place are iv directions that a turtle can move in:

  • Forrad
  • Backward
  • Left
  • Right

The turtle moves .forward() or .astern() in the management that information technology's facing. Yous tin change this management past turning it .left() or .correct() by a sure caste. You tin can try each of these commands like and so:

>>>

                                                  >>>                                    t                  .                  right                  (                  90                  )                  >>>                                    t                  .                  forwards                  (                  100                  )                  >>>                                    t                  .                  left                  (                  xc                  )                  >>>                                    t                  .                  backward                  (                  100                  )                              

When you run these commands, the turtle will turn right past ninety degrees, go forward by a hundred units, turn left by ninety degrees, and move backward by a hundred units. You can see how this looks in the paradigm below:

Python Turtle Moving Updated

Y'all tin use the shortened versions of these commands as well:

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

You can also describe a line from your current position to whatsoever other arbitrary position on the screen. This is done with the assistance 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 plan is (0,0). This is chosen Home. To movement the turtle to any other expanse on the screen, yous use .goto() and enter the coordinates similar this:

Your output will wait 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 abode position, you type the following:

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

Cartoon a Shape

Now that y'all know the movements of the turtle, you tin can motility on to making actual shapes. You tin can first by drawing polygons since they all consist of direct lines connected at certain angles. Here's an example that you tin can endeavour:

>>>

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

Your output volition look like this:

Python Turtle Square Edit Newer

Well done! You've just drawn a square. In this fashion, the turtle can be programmed to create different shapes and images.

Now, try drawing a rectangle, using this code as a template. Remember, in a rectangle, all four sides are not equal. You'll need to modify the code accordingly. Once you do that, y'all can even try creating other polygons by increasing the number of sides and changing the angles.

Cartoon Preset Figures

Suppose y'all desire to draw a circumvolve. If you lot endeavour to draw it in the same way as you lot drew the square, and then information technology would be extremely tedious, and you'd have to spend a lot of time simply for that one shape. Thankfully, the Python turtle library provides a solution for this. You lot tin utilise a single command to describe 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 subtract the size of the circle past changing the value of its radius.

In the same way, you can also draw a dot, which is naught only a filled-in circle. Type in this command:

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

Python Turtle Dot Update

The number inside the brackets is the diameter of the dot. Just like with the circle, you tin can increase or subtract the size of the dot past changing the value of its diameter.

Great task so far! You lot've learned how to move the turtle around and create different shapes with information technology. In the side by side few sections, y'all'll run across how you tin can customize your turtle and its surround, based on your requirements.

Irresolute the Screen Color

By default, turtle always opens upwardly a screen with a white background. However, y'all tin can change the color of the screen at any time using the following command:

>>>

                                                  >>>                                    turtle                  .                  bgcolor                  (                  "blue"                  )                              

Y'all can supervene upon "blue" with any other color. Try "greenish" or "red". Yous'll get a result similar this:

Python Turtle Background Color

Yous can utilise a variety of colors for your screen simply past typing in their hex code number. To learn more about using dissimilar colors, bank check out the Python turtle library documentation.

Changing the Screen Title

Sometimes, you may want to change the title of your screen. You tin get in more personal, like "My Turtle Programme", or more suitable to what you're working on, similar "Drawing Shapes With Turtle". Y'all can change the title of your screen with the help of this command:

>>>

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

Your title bar will at present display this:

Python Turtle Screen Title Updated

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

Changing the Turtle Size

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

>>>

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

Your outputs volition wait similar this:

Python Turtle Shape Size Updated

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

  • Stretch length
  • Stretch width
  • Outline width

Y'all 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 tin alter the size of the turtle, bank check out the Python turtle library documentation.

Irresolute the Pen Size

The previous command changed the size of the turtle's shape just. Still, sometimes, you may need to increase or subtract the thickness of your pen. You can practice this using the following control:

>>>

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

This results in an outcome similar this:

Python Turtle Pen Size More NEW

Every bit y'all can see, the size of your pen is now v times the original size (which was 1). Effort drawing some more than lines of various sizes, and compare the difference in thickness between them.

Irresolute the Turtle and Pen Color

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

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

You can fifty-fifty choose both of these if you wish. Before you change the colors, increase the size of your turtle to help you see the color divergence more clearly. Type in this code:

>>>

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

At present, to change the colour of the turtle (or the fill), yous type the following:

>>>

                                                  >>>                                    t                  .                  fillcolor                  (                  "red"                  )                              

Your turtle will look like this:

Python Turtle Fill Color Red

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

>>>

                                                  >>>                                    t                  .                  pencolor                  (                  "green"                  )                              

Your turtle will expect like this:

Python Turtle Pen Color Updated Green

To change the color of both, you blazon the following:

>>>

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

Your turtle volition look like this:

Python Turtle Color Single Line Updated

Hither, the showtime color is for the pen, and the second is for the make full. Notation that irresolute the color of the pen and the fill also changes the color of the onscreen turtle accordingly.

Filling in an Image

Coloring in an image usually makes it wait better, doesn't it? The Python turtle library gives you the selection to add color to your drawings. Try typing in the following code and run across 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 lawmaking, you'll get a triangle that'southward filled in with a solid color, similar this:

Python Turtle Begin Fill End Fill New

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

Changing the Turtle Shape

The initial shape of the turtle isn't really a turtle, simply a triangular figure. Even so, you can change the way the turtle looks, and you do take a couple of options when it comes to doing so. Y'all can have a look at some of them by typing in the following commands:

>>>

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

The shape of the turtle volition change accordingly, like this:

Python Turtle Shapes

Y'all have a couple of other options that y'all tin try equally well:

  • Square
  • Arrow
  • Circumvolve
  • Turtle
  • Triangle
  • Classic

The classic shape is the original shape. Bank check out the Python turtle library documentation to learn more virtually the types of shapes that you tin apply.

Changing the Pen Speed

The turtle by and large moves at a moderate step. If yous desire to decrease or increment the speed to brand your turtle move slower or faster, then you can do and so by typing the post-obit:

>>>

                                                  >>>                                    t                  .                  speed                  (                  1                  )                  >>>                                    t                  .                  forrard                  (                  100                  )                  >>>                                    t                  .                  speed                  (                  10                  )                  >>>                                    t                  .                  forwards                  (                  100                  )                              

This code will starting time decrease the speed and motility the turtle forward, then increase the speed and motility the turtle forrad again, like this:

Python Turtle Speed Updated

The speed can be any number ranging from 0 (the slowest speed) to 10 (the highest speed). Yous can play around with your lawmaking to see how fast or tiresome the turtle will get.

Customizing in One Line

Suppose yous desire to set up your turtle's characteristics to the following:

  • Pen colour: purple
  • Fill up colour: orange
  • Pen size: 10
  • Pen speed: 9

From what you've simply learned, the code should look something similar this:

>>>

                                                  >>>                                    t                  .                  pencolor                  (                  "imperial"                  )                  >>>                                    t                  .                  fillcolor                  (                  "orange"                  )                  >>>                                    t                  .                  pensize                  (                  x                  )                  >>>                                    t                  .                  speed                  (                  9                  )                  >>>                                    t                  .                  begin_fill                  ()                  >>>                                    t                  .                  circumvolve                  (                  ninety                  )                  >>>                                    t                  .                  end_fill                  ()                              

It'due south pretty long, but not that bad, correct?

Now, just imagine if you had ten different turtles. Changing all of their characteristics would be extremely slow for you to exercise! The skilful news is that yous can reduce your workload by altering the parameters in just a single line of lawmaking, similar this:

>>>

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

This will give yous a issue like this:

Python Turtle Single Line Pen Newer

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

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

Picking the Pen Up and Down

Sometimes, you may want to move your turtle to some other bespeak on the screen without drawing anything on the screen itself. To exercise this, you use .penup(). Then, when you lot want to outset cartoon again, you use .pendown(). Requite information technology a shot using the code that you used previously to draw a square. Endeavor typing the post-obit code:

>>>

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

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

Python Turtle Pen Up Pen Down Edit

Hither, you've obtained 2 parallel lines instead of a square past adding some extra commands in between the original programme.

Undoing Changes

No matter how conscientious yous are, there'due south ever a possibility of making a mistake. Don't worry, though! The Python turtle library gives you the selection to undo what y'all've washed. If you desire to undo the very concluding affair you did, then type in the following:

This undoes the concluding control that you ran. If you want to undo your last iii commands, then you would type t.undo() 3 times.

Immigration the Screen

Correct now, you probably take a lot on your screen since you've started this tutorial. To make room for more, just type in the following control:

This will make clean up your screen so that y'all can go along drawing. Notation here that your variables will not change, and the turtle volition remain in the aforementioned position. If you have other turtles on your screen other than the original turtle, then their drawings will not be cleared out unless y'all specifically call them out in your lawmaking.

Resetting the Surroundings

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 will all be restored to their default parameters. All y'all need to to do is type in the post-obit command:

This clears the screen and takes the turtle back to its dwelling house position. Your default settings, like the turtle's size, shape, color, and other features, will also be restored.

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

Leaving a Stamp

You have the choice of leaving a postage of your turtle on the screen, which is cypher only an imprint of the turtle. Try typing in this code to see how it works:

>>>

                                                  >>>                                    t                  .                  stamp                  ()                  8                  >>>                                    t                  .                  fd                  (                  100                  )                  >>>                                    t                  .                  stamp                  ()                  ix                  >>>                                    t                  .                  fd                  (                  100                  )                              

Your output will look like this:

Python Turtle Stamps Edit

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

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

Cloning Your Turtle

Sometimes, you may demand to have more than 1 turtle on your screen. You'll see an example of this later on in the final project. For now, you tin can become another turtle by cloning your electric current turtle into your environment. 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                  (                  "red"                  )                  >>>                                    t                  .                  circle                  (                  100                  )                  >>>                                    c                  .                  circle                  (                  lx                  )                              

The output volition await like this:

Python Turtle Clone NEWER

Crawly!

Now that you have an idea of some of import commands from the Python turtle library, you lot're ready to motility on to a few more concepts that you'll need to understand. These concepts are very much needed when information technology comes to programming in whatsoever linguistic communication.

Using Loops and Provisional Statements

When you get into college-level programming, you'll find yourself using loops and conditional statements very oftentimes. That's why, in this section, you'll be going through a couple of turtle programs that brand use of these types of commands. This will give y'all a practical approach when information technology comes to understanding these concepts. Before you begin, yet, here are 3 definitions for you to proceed in heed:

  1. Loops are a set of instructions that are continuously repeated until a particular condition is satisfied.
  2. Conditional statements carry out a sure task based on a status that's satisfied.
  3. Indentations are used to define blocks of code, especially when using loops and conditional statements. In general, y'all create an indentation by borer the Tab key on the keyboard.

Now, allow'due south go ahead and explore these commands!

for Loops

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

>>>

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

A much shorter manner to do this is with the help of a for loop. Attempt running this code:

>>>

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

Here, the i is similar a counter that starts from cipher and keeps increasing by 1. When you lot say in range(4), y'all're telling the program that the value of this i should be less than 4. Information technology volition terminate the program before i reaches 4.

Here'due south a breakup of how the program works:

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

The turtle will and so get out the loop. To check the value of i, blazon i and then press the Enter cardinal. You lot'll go the value of i equal to 3:

Notation that the whitespace that comes earlier line two and line iii in the program is the indentation. This indicates that all 3 lines form a single block of code. To learn more than about for loops in Python, bank 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 lawmaking will finish the process. You tin apply a while loop to create a series of circles by typing in this code:

>>>

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

When you run this code, you lot'll see the circles appearing i afterward the other, and each new circle will be larger than the previous one:

Python Turtle While Loop Edited Newer

Hither, n is used every bit a counter. Y'all'll need to specify by how much you want the value of n to increase in each loop. Take a expect at this mini walk-through to see how the program works:

  1. At n = 10, the turtle draws a circumvolve with a radius of 10 units. After that, the value of n is increased by x.
  2. At n = xx, the turtle draws a circle with a radius of 20 units. Once more, the value of north is increased by x.
  3. At north = 30, the turtle draws a circle with a radius of 30 units. For the third time, the value of north is increased by x.
  4. At n = 40, the turtle draws a circle with a radius of twoscore units. For the last time, the value of n is increased by 10.
  5. At n = fifty, n is no longer less than or equal to 40. The loop is terminated.

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

Conditional Statements

Yous use conditional statements to check if a given condition is true. If information technology is, and so the corresponding command is executed. Try typing in this program:

>>>

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

input() is used to obtain input from the user. Hither, information technology will store the user's response under the variable u. Next, it will compare the value of u with the condition provided and bank check whether the value of u is "yes". If it'due south "yes", then your program draws a circle. If the user types in anything else, then the plan won't do anything.

When you add an else clause to an if statement, yous tin specify two results based on whether the condition is true or false. Let'south run across this in a program:

>>>

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

Here, you tell the programme to display a detail output fifty-fifty when the user does not say "aye". You use print() to display some pre-divers characters on the screen.

Note that the user doesn't demand to type "no". They can type anything else, in which case, the result will e'er be "Okay", because y'all're non explicitly telling the program that the user needs to type "no". Not to worry, nonetheless, equally that can be stock-still. You tin add an elif clause to provide the programme with several conditions and their respective outputs, as yous tin can observe here:

>>>

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

Equally you tin see, this programme now has more than one upshot, depending on the input it receives. Here's how this code works:

  • If you type in "yes", so the lawmaking processes the input and draws a circumvolve, as per your instructions.
  • If you type in "no", then the code prints out "Okay" and your program is terminated.
  • If you lot type in anything else, like "Hi" or "Sandwich", and so the lawmaking prints "Invalid Respond" and your program is terminated.

Annotation that this program is instance-sensitive, so when you're trying information technology out, be sure to put the strings in upper-case or lower-case accordingly.

To larn more well-nigh conditional statements, cheque out Provisional Statements in Python.

Terminal Projection: The Python Turtle Race

And so far, you've learned how to customize your turtle surroundings, program your turtle to move around the screen, and use loops and provisional statements to ameliorate your lawmaking. Now it's time for the most of import part of your programming journey. In this section, you'll be implementing all that yous've learned into a single plan by creating a fun game that you lot tin can play with your friends.

Before you begin, hither's what you 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 player and so moves their turtle by that many steps.
    • The players alternate turns until one of them wins.
  3. The Structure:

    • Each player had a turtle indicated by a dissimilar color. Yous tin can have more than ii players, but for the sake of this tutorial, you'll be creating a two-player game.
    • Each turtle has a home position that information technology must reach.
    • Each player uses a die to choose a value at random for their plow. In your program, the die is represented by a list of numbers from 1 to 6.

At present that you've understood the logic of the game, you can go ahead and begin creating it! First, you'll demand to set up the environment.

Setting Upwardly the Game Environs

Showtime past importing the Python turtle library. Afterwards this, import the built-in random library, which you'll use randomly select an item from a listing:

>>>

                                                  >>>                                    import                  turtle                  >>>                                    import                  random                              

Once these libraries are successfully called into your environment, you lot can proceed with the rest of your program.

Setting Upwardly the Turtles and Homes

Y'all at present have to create the two turtles that will correspond the players. Each turtle volition exist a different color, corresponding to the different players. Here, player one is green and player two is blue:

>>>

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

One yous've created the turtles, you place them at their starting positions and make sure that these positions are aligned. Annotation that you lot created thespian two's turtle by cloning player 1'southward turtle, changing its color, and placing it at a different starting point.

You lot at present need to fix up homes for the turtles. These homes volition act as the finishing points for each turtle. Each of the turtles' homes will be represented past a circle. Hither, you need to make sure that both homes are equidistant from the starting point:

>>>

                                                  >>>                                    player_one                  .                  goto                  (                  300                  ,                  60                  )                  >>>                                    player_one                  .                  pendown                  ()                  >>>                                    player_one                  .                  circle                  (                  xl                  )                  >>>                                    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                  )                              

Later on drawing the respective homes, you send the turtles back to their starting positions:

Python Turtle Race Setup Updated

Awesome! The visual aspects of your game are complete. Y'all tin can now create the die that you'll exist using to play the game.

Creating the Dice

You can create a virtual dice for your game with a list, which is an ordered sequence of items. In existent life, you might ready grocery lists and to-exercise lists to help yous stay organized. In Python, lists work in a similar way.

In this case, y'all'll be using a list to create your die. Beginning, y'all define your list of numbers in ascending order from 1 to 6. You tin define a list past giving information technology a name and then enclosing its items within square brackets, like this:

>>>

                                                  >>>                                    die                  =                  [                  1                  ,                  2                  ,                  three                  ,                  4                  ,                  five                  ,                  6                  ]                              

This list has now become your die. To roll the dice, all you have to practise is programme your system to randomly select a number from it. The number that is selected will be considered as the output of the die.

Developing the Game

It's time to develop the code for the rest of the game. You lot'll exist using loops and conditional statements here, so you need to be careful with the indentations and spaces. To start, take a look at the steps your program will demand to take to run the game:

  1. Step 1: You'll start by telling your programme to cheque if either turtle has reached its dwelling house.
  2. Pace 2: If they haven't, and so you'll tell your programme to permit the players to go on trying.
  3. Pace 3: In each loop, you tell your programme to roll the die by randomly picking a number from the list.
  4. Stride 4: You then tell information technology to motility 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 in one case one of the turtles reaches the goal. Hither's how the lawmaking looks:

>>>

                                                                      i                  >>>                                    for                  i                  in                  range                  (                  twenty                  ):                                      ii                  ...                                    if                  player_one                  .                  pos                  ()                  >=                  (                  300                  ,                  100                  ):                                      iii                  ...                                    impress                  (                  "Player One Wins!"                  )                                      4                  ...                                    break                                      v                  ...                                    elif                  player_two                  .                  pos                  ()                  >=                  (                  300                  ,                  -                  100                  ):                                      6                  ...                                    print                  (                  "Player Two Wins!"                  )                                      7                  ...                                    break                                      viii                  ...                                    else                  :                                      9                  ...                                    player_one_turn                  =                  input                  (                  "Press 'Enter' to roll the die "                  )                  10                  ...                                    die_outcome                  =                  random                  .                  choice                  (                  die                  )                  11                  ...                                    impress                  (                  "The result of the die roll is: "                  )                  12                  ...                                    print                  (                  die_outcome                  )                  13                  ...                                    impress                  (                  "The number of steps will be: "                  )                  14                  ...                                    print                  (                  20                  *                  die_outcome                  )                  15                  ...                                    player_one                  .                  fd                  (                  20                  *                  die_outcome                  )                  16                  ...                                    player_two_turn                  =                  input                  (                  "Press 'Enter' to ringlet the die "                  )                  17                  ...                                    die_outcome                  =                  random                  .                  choice                  (                  die                  )                  eighteen                  ...                                    impress                  (                  "The consequence of the dice roll is: "                  )                  xix                  ...                                    impress                  (                  die_outcome                  )                  20                  ...                                    print                  (                  "The number of steps volition exist: "                  )                  21                  ...                                    impress                  (                  20                  *                  die_outcome                  )                  22                  ...                                    player_two                  .                  fd                  (                  twenty                  *                  die_outcome                  )                              

Your concluding output volition 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 ane to 20.

  2. Lines two through 7 check if either player has reached their goal. If i of them has, then the program prints out the corresponding statement and breaks the loop.

  3. Line 8 moves the program on to the next set of steps if neither histrion has won.

  4. Line nine prints out a statement asking histrion one to press the Enter central to roll the die.

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

  6. Line 11 prints a statement prior to displaying the outcome of the dice whorl.

  7. Line 12 prints the die outcome.

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

  9. Line 15 moves actor 1'south turtle frontward by this number of steps.

  10. Lines 16 to 22 repeat these steps for player 2.

The entire for loop is repeated until ane of the player'due south turtles reaches the final position.

Retrieve, you can customize the game still y'all want, and then go ahead and play around with it! You lot tin can add together more turtles, change the colors, change the speed, or fifty-fifty create some obstacles to challenge your players. Information technology's all up to yous as the developer of the game!

Conclusion

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

Now you can:

  • Gear up upward the Python turtle library
  • Move your turtle effectually
  • Customize your turtle and its environment
  • Program your turtle
  • Use basic programming concepts
  • Create a game that yous tin can play with friends

Now yous're prepare to venture into some higher-level Python programming. To progress further in your Python journey, check out Introduction to Python and 11 Beginner Tips for Learning Python Programming. Just remember to work difficult and keep practicing, and you'll notice that you're a Python expert in no time!

Watch Now This tutorial has a related video course created past the Real Python squad. Scout it together with the written tutorial to deepen your understanding: Python Turtle for Beginners