随机未在python中定义

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18727556/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 11:37:11  来源:igfitidea点击:

random is not defined in python

python

提问by user2744489

I'm trying to produce a random integer n, and create a list of n random integers with values between 0 and 9.

我正在尝试生成一个随机整数n,并创建一个包含 0 到 9 之间的值的 n 个随机整数的列表。

Here is my code:

这是我的代码:

def randomNumbers(n):
    myList = []
    needMoreNumbers = True
    while (needMoreNumbers):
        randomNumber = int(random.random() * 10)
        myList.append(randomNumber)
        n = n -1
        if (n < 1):
            needMoreNumbers = False
    return myList

When I run it, it says:

当我运行它时,它说:

NameError: global name 'random' is not defined

回答by alecxe

You haven't imported randommodule. Add this to the top of your script:

你还没有导入random模块。将此添加到脚本的顶部:

import random 

回答by JeffProd

The script file name can't be "random.py"

脚本文件名不能是“random.py”