擅长:python、mysql、java
<p>这里一切看起来都很好,但记住调用函数,然后导入random:</p>
<pre><code>from random import *
def scenario():
key = randrange(0, 21)
if key > 10:
print("A # greater than 10 has been generated")
if key < 10:
print("A # lesser than 10 has been generated")
print(key) #To see what key was printed
scenario()
</code></pre>
<p>如果不调用函数,则不会发生以下情况:</p>
<pre><code>>>> def foo():
... print 'hi'
...
>>> #This is blank till I call foo()
...
>>> foo()
hi
>>>
</code></pre>
<p>另外,如果不导入<code>random</code>,则会在<code>key = randrange(0, 21)</code>处引发错误:</p>
<pre><code>>>> import random
>>> del(random) #Reverses import
>>> random.randrange(0, 21)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'random' is not defined
>>>
</code></pre>