Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to shorten my code so that I don't have to write "turtle." every time I use functions from the turtle module?

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

like image 428
Baraa najjar Avatar asked Dec 02 '22 09:12

Baraa najjar


1 Answers

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.

like image 94
Alec Avatar answered Dec 04 '22 01:12

Alec