views:

105

answers:

2

I'm writing a silly program in python for a friend that prints "We are the knights who say 'Ni'!". then sleeps for 3 seconds, and then prints "Ni!" twenty times at random intervals using the random module's uniform() method. Here's my code:

from time import sleep
import random

def knights_of_ni():
    generator = random.Random()
    print "We are the knights who say 'ni'."
    sleep(3)
    for i in range(0,20):
        print "Ni!"
        sleep(generator.uniform(0,2))

I've tried to import this module by typing in the interpreter from silly import knights_of_ni() and import silly, then calling the function with either knights_of_ni() or silly.knights_of_ni() (respectively), but I always get the same exception:

 NameError: global name 'time' is not defined

What is causing this error and how can I fix my code?

Edit: quite frankly, I'm not sure what problem I was having either. I ran the code the next morning and it worked just fine. I swear that the code produced errors last night... Anyway, thanks for your insight.

+2  A: 

That's impossible. Your code example isn't the same as the code that produced that error.

Perhaps you had time.sleep(..) instead of sleep(..). You have done from time import sleep. To use the time.sleep(..) form you must import time

Jerub
Yeah I have no idea what happened, I'm certain this code produced an error last night, but no matter, it works now.... Thanks for convincing me to try running it again.
Rafe Kettler
Actually, I know exactly what happened.... I had done some things with `time` in the interpreter, and when I called `knights_of_ni` it must have gotten confused.
Rafe Kettler
A: 

What Jerub said. I ran your exact code and it worked:

>>> import silly
>>> silly.knights_of_ni()
We are the knights who say 'ni'.
Ni!
Ni!
Ni!
Ni!
Ni!
Ni!
katrielalex