I’m trying to write in Visual Studio Code for Linux a simple roll dice program, but for some reason I have an Unexpected NameError that make me mad.
This is my code:
from random import randint
class Dice:
def __init__(self, sides):
self.sides = sides
def roll(self):
play = randint (1, Dice.sides)
print (play)
dado = Dice(6)
roll()
When I try to run program it fails with this error:
NameError: name ‘roll’ is not defined
I don’t understand why, I know is probably a very stupid thing, but I don’t see any problem whit the name "roll"…
2
Answers
In your code, you are doing Object Oriented Programming (OOP), which in Python, consists of classes.
The
roll
function is inside theDice
class, so just doingroll()
is not enough.You need to first create an instance of the class, and use that instance to run the
roll
function:As for your example, you could do this:
You should create an instance of the class first. Also, there is an error in roll function – you should use self.sides instead of Dice.sides. So, resulting code should look like this: