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?

1 Answer

0 votes
by (108k 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: 

Related questions

Browse Categories

...