[Tutor] Fwd: Turtle

Steven D'Aprano steve at pearwood.info
Sun Jun 19 06:09:50 EDT 2016


On Sat, Jun 18, 2016 at 08:46:53PM -0700, Hershel Millman wrote:

> > I followed your instruction and typed "import turtle" into the terminal on my mac, and nothing happened.

If you're talking about the Python prompt, that's good. That means 
turtle is installed. Importing a module either succeeds, or gives a 
traceback. Compare the difference between these two imports:

py> import turtle
py> import octopus
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named 'octopus'


[...]
> > In pycharm, when I enter the following, it replies with the 
> > following error message:
> > 
> > from turtle import *
> > 
> > def drawSquare(size=100):
> >    turtle.pendown()
[...]

> > Traceback (most recent call last):
> >  File "/Users/Hershel/PycharmProjects/Project 1/practicefornotturtle.py", line 14, in <module>
> >    drawSquare(50)
> >  File "/Users/Hershel/PycharmProjects/Project 1/practicefornotturtle.py", line 4, in drawSquare
> >    turtle.pendown()
> > NameError: global name 'turtle' is not defined

This is the difference between plain "import" and "from ... import".

Here is a simplified example that hopefully will be clear:


py> import math
py> math.pi
3.141592653589793
py> pi
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'pi' is not defined



With a regular import, the math module is loaded and made available 
using the module name. To see inside the module, you have to use the dot 
operator (it's not really an operator, but I'll call it that) to get 
access to functions and variables inside the math module. Hence you must 
say "math.pi".

If you say "pi" on its own, Python looks for a variable called pi, 
doesn't find one, and complains.


If I quit out of Python and start again, in a fresh session:

py> from math import pi
py> math.pi
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'math' is not defined
py> pi
3.141592653589793


"from ... import" works the opposite way. It still loads the math 
module, but this time it DOESN'T make it available under that name, so 
"math.pi" fails. Instead, it cretaes a new variable called pi, set to 
math.pi.


Finally:

from math import *

doesn't just import pi, but ALL the functions and variables from the 
math module. That is generally not a good idea. There are very 
occasional times were it is useful, but in general you should only 
import what you need:

    from math import pi, sin, cos

or import the entire module:

    import math




-- 
Steve


More information about the Tutor mailing list