I am trying to draw squares using turtle in python, and every time I want to command it to do something I must write turtle.
import turtle
turtle.forward(100)
turtle.right(90)
turtle.forward(100)
turtle.right(90)
turtle.forward(100)
turtle.right(90)
turtle.forward(100)
turtle.right(90)
turtle.back(100)
turtle.right(90)
turtle.forward(100)
turtle.right(90)
turtle.back(100)
turtle.right(90)
turtle.forward(100)
turtle.right(90)
turtle.back(200)
turtle.right(90)
turtle.forward(100)
turtle.right(90)
turtle.back(100)
turtle.exitonclick()
I expect to write my code without having to write turtle every time
You can import everything from the turtle module by writing
from turtle import * # this is a wildcard import
Instead, however, you should just import turtle as t (or whatever else you want), like so:
import turtle as t # you can replace t with any valid variable name
Because wildcard imports tend to create function definition conflictions
Conversely, you could import only the classes (or methods) you need from from the module. Turtle is a necessary import:
from turtle import Turtle
Now, we have to instantiate it:
t = Turtle()
Now we can use it:
t.do_something() # methods that act on the turtle, like forward and backward
That will not import the Screen module however, so you won't be able to use exitonclick() unless you import Screen too:
from turtle import Turtle, Screen
s = Screen()
s.exitonclick()
As @cdlane notes though, loops may actually be your best bet for reducing the amount of code you have to write. This code:
for _ in range(x):
turtle.forward(100)
turtle.right(90)
Moves the turtle forwards then rightwards x times.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With