Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
4 views
in Python by (50.2k points)

I am first time using the turtle package in python but I am not able to import that package in my python environment:

Here's my code:

from turtle import *

pen1 = Pen()

pen2 = Pen()

pen1.screen.bgcolour("#2928A7") 

and here is the error I get:

Traceback (most recent call last):

  File "C:\Python34\Python saves\turtle.py", line 2, in <module>

    from turtle import *

  File "C:\Python34\Python saves\turtle.py", line 5, in <module>

    pen1 = Pen()

NameError: name 'Pen' is not defined

Can anyone tell me what I did wrong?

2 Answers

0 votes
by (107k points)
edited by

Please be informed that your main issue is that you've defined your program "turtle.py".

So if Python encounters the below statement

from turtle import *

#the first matching package named turtle that it finds is your program, "turtle.py".

In other words, your program is essentially importing itself and not the turtle graphics module.

import turtle

foo = 42

print(turtle.foo)

help(turtle)

The code will print:

When we execute it as turtle.py it prints the following "help" info:

Help on module turtle:

NAME

    turtle - Mock Turtle

FILE

    /mnt/sda4/PM2Ring/Documents/python/turtle.py

DESCRIPTION

    Demonstrate what happens when you give your program the same name

    as a module you want to import.

    See http://stackoverflow.com/q/32180949/4014959

    Written by PM 2Ring 2015.08.24

DATA

    foo = 42

(END) 

When you hit Q to get out of the Help, the Help info is displayed again. When you hit Q for the second time, then

42

42

#is printed.

The message is displayed twice because all the code in turtle.py is executed when it's imported, and then again when it's confronted after the import statement.

If you are a total beginner and wish to learn python, then do check out the below python tutorial video for better understanding: 

0 votes
by (1.3k points)

import turtle

pen1 = turtle.Turtle()

pen2 = turtle.Turtle()

turtle.Screen().bgcolor("#2928A7")

pen1.forward(100)

pen2.right(90)

pen2.forward(100)

turtle.done()

The error you’re encountered is due to naming conflict between your script and the turtle module. You have named your script turtle.py, Python tries to import from your script instead of the built-in module, that caused the NameError.

Related questions

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...