所以我正在研究一个在1到20之间随机生成数字的场景。我需要将这个数字存储一段时间,因为根据生成的数字,会有不同的结果。我知道您可以randrange
和randint
生成数字,但我想知道您是否可以将其存储到变量中。例如,我试过这个:
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
我只是打印1和2以查看它是否有效然后打印键,以便我可以看到它是否已生成。有没有具体的方法来使这项工作?因为当我尝试时,它会在我运行时留空。如果它不起作用,我真的不想深入研究这个问题,但我只是在问我是否遗漏了一些显而易见的东西,或者它是否只是不起作用。无论哪种方式,如果它有效或无效,我可能会找到解决方法。谢谢你的帮助。
答案 0 :(得分:1)
一般来说,您的代码看起来很好。你错过了一些重要的部分吗?如果要使用它,则需要导入randrange。而你需要实际调用你的功能。除此之外它看起来很好
from random import randrange
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()
答案 1 :(得分:1)
这里的一切看起来都很好,但只记得调用你的函数,并随机导入:
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()
如果您没有调用某个函数,则不会发生任何事情:
>>> def foo():
... print 'hi'
...
>>> #This is blank till I call foo()
...
>>> foo()
hi
>>>
此外,如果您不导入random
,则会在key = randrange(0, 21)
处引发错误:
>>> 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
>>>
答案 2 :(得分:0)
from random import randint
def scenario():
key = randint(0, 20)
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()