Today I tried to make a project where I need to use import random
, but when I use it, its imports not library but only function random, and I get alert: NameError: name 'randint' is not defined
.
My code looks like:
import random
randomList = []
def randoming() :
for i in range(8) :
randomNum = randint(2, 8)
randomList.append(randomNum)
randoming()
def sixCounter() :
sixNums = 0
for a in range(8) :
if randomList[a] == 6 :
sixNums = sixNums 1
print(f"In that list are {sixNums} six numbers")
print("The numbers in list are:")
print(*randomList, sep = ", ")
sixCounter()
CodePudding user response:
You either need to reference randint as random.randin or import randint from random
i.e. either:
from random import randint
randomList = []
def randoming() :
for i in range(8) :
randomNum = randint(2, 8)
randomList.append(randomNum)
randoming()
def sixCounter() :
sixNums = 0
for a in range(8) :
if randomList[a] == 6 :
sixNums = sixNums 1
print(f"In that list are {sixNums} six numbers")
print("The numbers in list are:")
print(*randomList, sep = ", ")
sixCounter()
or
import random
randomList = []
def randoming() :
for i in range(8) :
randomNum = random.randint(2, 8)
randomList.append(randomNum)
randoming()
def sixCounter() :
sixNums = 0
for a in range(8) :
if randomList[a] == 6 :
sixNums = sixNums 1
print(f"In that list are {sixNums} six numbers")
print("The numbers in list are:")
print(*randomList, sep = ", ")
sixCounter()
CodePudding user response:
THE PROBLEM
When you import any module as following,
import module
to call any function from the module, you have to do it as an attribute of the module. Like this:
module.function()
Calling only the function will raise an undefinition error.
THE SOLUTION
To solve your problem, call the randint function like this:
random.randint()
OR import the module like this
from random import *
This instruction will "move" all the functions of the module random to your code, so that you don't have to call any function as an attribute of the module.