I have two files: in one of them (named myrandom
) I have defined a function called spinner
that would choose a random number from 1 to 6 and would return its value. In the second file, named main
, I have imported the first one (as a module) and have also called the spinner
function.
This is the code of the file myrandom
:
def spinner():
import random
val = random.choice([1, 2, 3, 4, 5, 6])
return val
And this is the code of main
:
import myrandom
x = spinner()
print(x)
My problem is that when I run main
, I get the following error message: "NameError: name spinner() is not defined". I don't know why I'm getting this error, since I have other files and modules with similar characteristics that run without problems.
Any idea?
You need to use it like:
import myrandom
x = myrandom.spinner()
Or import directly:
from myrandom import spinner
x = spinner()
Or use star import:
from myrandom import *
x = spinner()
You should import it either like this:
import myrandom
x = myrandom.spinner()
or like this:
from myrandom import spinner
x = spinner()
or like this:
from myrandom import *
x = spinner()
An explanation of the different ways of importing can be found here: Importing modules in Python - best practice
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.