Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

random is not defined in python

Tags:

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

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 
like image 969
user2744489 Avatar asked Sep 10 '13 19:09

user2744489


People also ask

Why is Randint not defined Python?

The Python "NameError: name 'randint' is not defined" occurs when we use the randint function without importing it first. To solve the error, import the randint function before using it - from random import randint . Here is an example of how the error occurs. Copied!

How do you import random in Python?

Using 'import random' imports the package, which you can then use the function from this package: 'random. random()'. You can use any other function from the 'random' package as well. You can also tell python to specifically import only the random function from the package random: 'from random import random'.


1 Answers

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

import random  
like image 193
alecxe Avatar answered Sep 21 '22 12:09

alecxe