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 makes 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"...
In your code, you are doing Object Oriented Programming (OOP), which in Python, consists of classes.
The roll
function is inside the Dice
class, so just doing roll()
is not enough.
You need to first create an instance of the class, and use that instance to run the roll
function:
dice = Dice(6)
dice.roll()
As for your example, you could do this:
dado.roll()