0

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?

Me All
  • 269
  • 1
  • 5
  • 17

2 Answers2

0

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()
Nouman
  • 6,947
  • 7
  • 32
  • 60
0

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

berkelem
  • 2,005
  • 3
  • 18
  • 36